Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/peering-admin-visibility.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"nostream": minor
---

feat(peering): show relationship state, terms and traffic split in admin

The Peering console now shows each peer's relationship state and current terms,
reconciliation and peer-request activity, and the existing budget and
held-invoice panels in one place. Relationship state follows the same access
window as the relay, so an ended period no longer appears active.
8 changes: 6 additions & 2 deletions docs/PEERING.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,12 @@ reconciliation from being reported as stale.

Each reconciliation writes the peer's state to Redis and exposes it at
`GET /admin/peering`: status, last reconciliation, latest event age ("lag"),
and the number of events the last reconciliation found missing. The admin
console shows the same rows under Operations → Peering.
the number of events the last reconciliation found missing, and how many events
it stored. The admin console shows the same rows under Operations → Peering,
with the peer's current terms and an explicit relationship state (`active`,
`suspended`, `lapsed`, `unpaid`, `free` or `removed`). It also shows reconciled
events, peer requests and all events served, plus the per-peer and global
budget counters and held invoices with Approve/Reject actions.

NIP-77 must be enabled on the source relay (`nip77.enabled` and the PostgreSQL
event store). `peering.peers` on the receiving relay is the only trust material
Expand Down
63 changes: 47 additions & 16 deletions resources/admin/assets/admin-ops.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,25 @@
return `${Math.round(seconds / 86400)}d`
}

const peeringBillingBadge = (billing) => {
if (!billing?.status) {
return '<span class="status-badge"><span class="status-led" aria-hidden="true"></span>Not billed</span>'
const peeringStateBadge = (relationship) => {
const status = String(relationship || 'removed')
const degraded = ['lapsed', 'unpaid', 'suspended', 'removed'].includes(status)
return `<span class="status-badge${degraded ? ' status-degraded' : ''}"><span class="status-led" aria-hidden="true"></span>${escapeHtml(status)}</span>`
}

const formatPeeringPeriod = (seconds) => {
if (seconds % 86400 === 0) return `${seconds / 86400}d`
if (seconds % 3600 === 0) return `${seconds / 3600}h`
if (seconds % 60 === 0) return `${seconds / 60}m`
return `${seconds}s`
}

const peeringTerms = (terms) => {
if (!terms?.amountMsats || !terms?.periodSeconds) {
return 'Free'
}

const status = String(billing.status)
const degraded = status === 'lapsed' || status === 'unpaid'
return `<span class="status-badge${degraded ? ' status-degraded' : ''}"><span class="status-led" aria-hidden="true"></span>${escapeHtml(status)}</span>`
return `${Math.round(Number(BigInt(terms.amountMsats) / 1000n))} sats / ${formatPeeringPeriod(terms.periodSeconds)}`
Comment thread
Ferryx349 marked this conversation as resolved.
Resolved
}

const peeringSignalBadge = (row) => {
Expand Down Expand Up @@ -209,9 +220,10 @@
.join('')
}

const renderPeering = (rows) => { if (!Array.isArray(rows) || !rows.length) {
const renderPeering = (rows) => {
if (!Array.isArray(rows) || !rows.length) {
elements.peeringBody.innerHTML =
'<tr><td colspan="10" class="admin-muted small">No peering peers configured.</td></tr>'
'<tr><td colspan="12" class="admin-muted small">No peering peers configured.</td></tr>'
return
}

Expand All @@ -224,13 +236,15 @@
return `<tr>
<td><code class="small" title="${escapeAttr(title)}">${escapeHtml(shortPubkey(row.pubkey))}</code></td>
<td class="small">${escapeHtml(row.relayUrl)}</td>
<td>${peeringBillingBadge(row.billing)}</td>
<td class="small">${escapeHtml(peeringTerms(row.terms))}</td>
<td>${peeringStateBadge(row.relationship)}</td>
<td class="small">${escapeHtml(formatTime(row.billing?.periodEnd))}</td>
<td class="small">${escapeHtml(formatTime(state?.lastReconciledAt))}</td>
<td>${escapeHtml(formatLag(state?.lagSeconds))}</td>
<td class="small">${escapeHtml(state?.receivedEvents ?? 0)}</td>
<td>${escapeHtml(state?.missingEvents ?? '—')}</td>
<td class="small">${escapeHtml(requests?.eventsServed ?? 0)}</td>
Comment thread
Ferryx349 marked this conversation as resolved.
Resolved
<td>${escapeHtml(requests?.requests ?? 0)}</td>
<td>${escapeHtml(requests?.eventsServed ?? 0)}</td>
<td>${peeringSignalBadge(row)}</td>
</tr>`
})
Expand Down Expand Up @@ -437,19 +451,36 @@
}

const decidePeeringInvoice = async (paymentHash, action) => {
const response = await adminFetch('/peering/invoices/decision', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ paymentHash, action }),
})
let response
try {
response = await adminFetch('/peering/invoices/decision', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ paymentHash, action }),
})
} catch (error) {
if (elements.peeringInvoicesSync) {
elements.peeringInvoicesSync.innerHTML = `<span class="prompt-char">&gt;</span><span class="text-danger"> invoice: ${escapeHtml(error instanceof Error ? error.message : 'decision request failed')}</span>`
}
return
}

const payload = await response.json().catch(() => ({}))
if (!response.ok) {
if (elements.peeringInvoicesSync) {
elements.peeringInvoicesSync.innerHTML = `<span class="prompt-char">&gt;</span><span class="text-danger"> invoice: ${escapeHtml(payload.error || 'decision failed')}</span>`
}
return
}
await loadPeering()

try {
await loadPeering()
} catch {
if (elements.peeringInvoicesSync) {
elements.peeringInvoicesSync.innerHTML =
'<span class="prompt-char">&gt;</span><span class="text-warning"> invoice saved; refresh failed</span>'
}
}
}

const refreshAll = async () => {
Expand Down
10 changes: 6 additions & 4 deletions resources/admin/dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -236,18 +236,20 @@ <h2 class="section-title">Peering</h2>
<tr>
<th scope="col">Peer</th>
<th scope="col">Relay</th>
<th scope="col">Billing</th>
<th scope="col">Terms</th>
<th scope="col">State</th>
<th scope="col">Access until</th>
<th scope="col">Last reconciliation</th>
<th scope="col">Lag</th>
<th scope="col" title="Events stored during the latest reconciliation">Reconciled</th>
<th scope="col">Missing</th>
<th scope="col">Requests</th>
<th scope="col">Events served</th>
<th scope="col" title="All outgoing events sent to this peer, including the standing feed">Events served</th>
<th scope="col" title="REQ, NEG-OPEN and COUNT requests from this peer">Peer requests</th>
<th scope="col">Signal</th>
</tr>
</thead>
<tbody id="peering-body">
<tr><td colspan="10" class="admin-muted small">No peering peers configured.</td></tr>
<tr><td colspan="12" class="admin-muted small">No peering peers configured.</td></tr>
</tbody>
</table>
</div>
Expand Down
19 changes: 16 additions & 3 deletions src/controllers/admin/get-admin-peering-controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request, Response } from 'express'

import { IController } from '../../@types/controllers'
import { PeeringInvoice } from '../../@types/peering'
import { PeeringInvoice, PeeringInvoiceStatus } from '../../@types/peering'
import { IPeeringPaymentRepository } from '../../@types/repositories'
import { IPeeringBuyerService } from '../../@types/services'
import { Settings } from '../../@types/settings'
Expand All @@ -10,6 +10,9 @@ import { PeeringRequestStatsStore } from '../../utils/peering-request-stats'
import { PeeringSyncStateStore } from '../../utils/peering-sync-state'
import { loadMergedSettings } from '../../utils/settings-config'

const ADMIN_RECENT_INVOICES = 50
const ADMIN_HELD_INVOICES = 500

export const serializePeeringInvoice = (invoice: PeeringInvoice) => ({
paymentHash: invoice.paymentHash,
eventId: invoice.eventId,
Expand Down Expand Up @@ -38,14 +41,24 @@ export class GetAdminPeeringController implements IController {
) {}

public async handleRequest(_request: Request, response: Response): Promise<void> {
const [states, settings, requestStats, billing, invoices, budgets] = await Promise.all([
const [states, settings, requestStats, billing, recentInvoices, heldInvoices, budgets] = await Promise.all([
this.stateStore.list(),
this.getSettings(),
this.requestStatsStore?.list() ?? [],
this.peeringPaymentRepository?.list() ?? [],
this.peeringBuyerService?.list(undefined, 50) ?? [],
this.peeringBuyerService?.list(undefined, ADMIN_RECENT_INVOICES) ?? [],
this.peeringBuyerService?.list(
[PeeringInvoiceStatus.HELD, PeeringInvoiceStatus.FAILED],
ADMIN_HELD_INVOICES,
) ?? [],
this.peeringBuyerService?.budgetSummary() ?? [],
])
const invoicesByHash = new Map(
[...heldInvoices, ...recentInvoices].map((invoice) => [invoice.paymentHash, invoice]),
)
const invoices = [...invoicesByHash.values()].sort(
(left, right) => right.createdAt.getTime() - left.createdAt.getTime(),
)
const peers = mergePeeringRows(settings, states, undefined, requestStats, billing)

response
Expand Down
84 changes: 78 additions & 6 deletions src/utils/admin-peering.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { PeeringPayment, PeeringPeerSyncState } from '../@types/peering'
import { PeeringPayment, PeeringPaymentStatus, PeeringPeerSyncState } from '../@types/peering'
import { Settings } from '../@types/settings'
import { parsePeeringPeerPubkey } from './peering-auth'
import { isPeeringAccessActive, resolvePaidPeeringTerm } from './peering-billing'
import { PeeringRequestStats } from './peering-request-stats'
import { isPeeringSyncStateStale, PEERING_SYNC_STATE_STALE_AFTER_SECONDS } from './peering-sync-state'

Expand All @@ -17,12 +18,21 @@ export interface AdminPeeringBilling {
lastError?: string | null
}

export type AdminPeeringRelationship = 'active' | 'suspended' | 'lapsed' | 'unpaid' | 'free' | 'removed'

export interface AdminPeeringTerms {
amountMsats: string
periodSeconds: number
}

export interface AdminPeeringRow {
pubkey: string
relayUrl: string
configured: boolean
enabled: boolean
stale: boolean
relationship: AdminPeeringRelationship
terms?: AdminPeeringTerms
state?: PeeringPeerSyncState
requests?: PeeringRequestStats
billing?: AdminPeeringBilling
Expand All @@ -41,16 +51,59 @@ const toAdminBilling = (payment: PeeringPayment): AdminPeeringBilling => ({
lastError: payment.lastError,
})

const relationshipFor = (
configured: boolean,
enabled: boolean,
billing: AdminPeeringBilling | undefined,
now: Date,
): AdminPeeringRelationship => {
if (billing?.status === PeeringPaymentStatus.LAPSED) {
return 'lapsed'
}
if (!configured) {
return 'removed'
}
if (!enabled) {
return 'suspended'
}
if (
billing?.status === PeeringPaymentStatus.ACTIVE ||
billing?.status === PeeringPaymentStatus.RENEWAL_PENDING
) {
// The billing sweep can lag the access check. Do not call a peer active
// once its saved period has already ended.
return isPeeringAccessActive(billing.status, billing.periodEnd, now) ? 'active' : 'lapsed'
}
if (
billing?.status === PeeringPaymentStatus.UNPAID ||
billing?.status === PeeringPaymentStatus.INVOICED
) {
return 'unpaid'
}

return 'free'
}

const termsFor = (billing: AdminPeeringBilling | undefined): AdminPeeringTerms | undefined =>
billing?.termAmountMsats && billing.termPeriodSeconds
? { amountMsats: billing.termAmountMsats, periodSeconds: billing.termPeriodSeconds }
Comment thread
Ferryx349 marked this conversation as resolved.
Resolved
: undefined

export const mergePeeringRows = (
settings: Settings,
states: PeeringPeerSyncState[],
staleAfterSeconds = PEERING_SYNC_STATE_STALE_AFTER_SECONDS,
requestStats: PeeringRequestStats[] = [],
billing: PeeringPayment[] = [],
now = new Date(),
): AdminPeeringRow[] => {
const statesByPubkey = new Map(states.map((state) => [state.pubkey.toLowerCase(), state]))
const requestsByPubkey = new Map(requestStats.map((stats) => [stats.pubkey.toLowerCase(), stats]))
const billingByPubkey = new Map(billing.map((payment) => [payment.peerPubkey.toLowerCase(), payment]))
const paidTerm = resolvePaidPeeringTerm(settings)
const configuredTerms: AdminPeeringTerms | undefined = paidTerm
? { amountMsats: paidTerm.amountMsats.toString(), periodSeconds: paidTerm.periodSeconds }
: undefined
const rows: AdminPeeringRow[] = []
const matched = new Set<string>()

Expand All @@ -62,15 +115,28 @@ export const mergePeeringRows = (
const enabled = peer.enabled !== false

matched.add(normalized)
const billing = billingByPubkey.get(normalized)
? toAdminBilling(billingByPubkey.get(normalized)!)
: undefined
const paidConfiguration = configuredTerms !== undefined
const relationship = !paidConfiguration
? enabled
? 'free'
: 'suspended'
: enabled && !billing
? 'unpaid'
: relationshipFor(true, enabled, billing, now)
rows.push({
pubkey,
relayUrl: peer.relayUrl,
configured: true,
enabled,
stale: enabled && (!state || isPeeringSyncStateStale(state.updatedAt, staleAfterSeconds)),
relationship,
terms: paidConfiguration ? (termsFor(billing) ?? configuredTerms) : undefined,
state,
requests: requestsByPubkey.get(normalized),
billing: billingByPubkey.get(normalized) ? toAdminBilling(billingByPubkey.get(normalized)!) : undefined,
billing,
})
}

Expand All @@ -81,17 +147,20 @@ export const mergePeeringRows = (
continue
}

const billing = billingByPubkey.get(state.pubkey.toLowerCase())
? toAdminBilling(billingByPubkey.get(state.pubkey.toLowerCase())!)
: undefined
rows.push({
pubkey: state.pubkey,
relayUrl: state.relayUrl,
configured: false,
enabled: false,
stale: isPeeringSyncStateStale(state.updatedAt, staleAfterSeconds),
relationship: relationshipFor(false, false, billing, now),
terms: termsFor(billing),
state,
requests: requestsByPubkey.get(state.pubkey.toLowerCase()),
billing: billingByPubkey.get(state.pubkey.toLowerCase())
? toAdminBilling(billingByPubkey.get(state.pubkey.toLowerCase())!)
: undefined,
billing,
})
}

Expand All @@ -105,13 +174,16 @@ export const mergePeeringRows = (
continue
}

const billing = toAdminBilling(payment)
rows.push({
pubkey: payment.peerPubkey,
relayUrl: '',
configured: false,
enabled: false,
stale: true,
billing: toAdminBilling(payment),
relationship: relationshipFor(false, false, billing, now),
terms: termsFor(billing),
billing,
})
}

Expand Down
1 change: 1 addition & 0 deletions test/integration/features/peering/peering-admin.feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,5 @@ Then('it contains the held invoice and the current budget', function (this: Worl
const payload = this.parameters.adminResponse.send.firstCall.args[0]
expect(payload.invoices.some((invoice: any) => invoice.paymentHash === this.parameters.adminPayHash)).to.equal(true)
expect(payload.budgets.some((budget: any) => budget.scope === 'peer')).to.equal(true)
expect(payload.peers[0].relationship).to.equal('free')
})
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ describe('GetAdminPeeringController', () => {
status: 'held',
reason: 'amount_mismatch',
})
expect(peeringBuyerService.list).to.have.been.calledWith(['held', 'failed'], 500)
expect(payload.budgets[0]).to.deep.include({
scope: 'peer',
limitMsats: '10000000',
Expand Down
Loading
Loading