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
13 changes: 13 additions & 0 deletions .changeset/peering-invoice-queue-limit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"nostream": patch
---

fix(peering): bound the buyer invoice queue

A slow wallet can no longer let a peer grow the queued kind-402 invoice promise
chain without limit. The queue is capped at 100 events or 2 MiB; exceeding
either closes the peering connection and reconnects. Pending events are
discarded on reconnect and only one wallet call can remain in flight. The
handshake barrier is a fixed sequence, so later invoices cannot postpone the
live feed, and its waiter is released when the connection closes. Invoice
dedupe and the seller's re-issued open invoice make the reconnect safe.
9 changes: 9 additions & 0 deletions docs/PEERING.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,15 @@ of every enabled peer that advertises a paid term, over the same authenticated
peering connection it uses for the feed. Invoices are deduplicated by BOLT11
payment hash, so a redelivered event or a reconnect never pays twice.

Invoice events queue behind the wallet call. The buyer bounds that queue at
100 events or 2 MiB; exceeding either closes the peering connection so the
worker reconnects instead of growing memory without limit. Pending events are
discarded on reconnect and the new queue starts fresh; at most one
uncancellable wallet call remains in flight. The handshake barrier waits only
for invoices admitted before it, so a busy invoice stream cannot postpone the
live feed. The seller exposes its current open invoice again on reconnect, and
payment-hash dedupe prevents a second payment.

Auto-pay is opt-in and requires a per-peer budget:

```yaml
Expand Down
160 changes: 151 additions & 9 deletions src/app/peering-sync-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,27 @@ export const PEERING_SYNC_STATE_HEARTBEAT_MS = 60_000
export const PEERING_BUYER_RECOVERY_INTERVAL_MS = 60_000
export const PEERING_SYNC_MAX_PENDING_EVENTS = 500
export const PEERING_SYNC_MAX_PENDING_EVENT_BYTES = 8 * 1024 * 1024
/** A slow wallet must not let a peer grow the invoice promise chain without bound. */
export const PEERING_INVOICE_MAX_PENDING_EVENTS = 100
export const PEERING_INVOICE_MAX_PENDING_EVENT_BYTES = 2 * 1024 * 1024
export const PEERING_SYNC_MAX_SCOPE_SPLIT_DEPTH = 20

interface QueuedInvoiceEvent {
event: Event
size: number
seq: number
}

interface InvoiceEventQueue {
events: QueuedInvoiceEvent[]
bytes: number
}

interface InvoiceQueueWaiter {
seq: number
resolve: () => void
}

const eventShapeSchema = z
.object({
id: idSchema,
Expand Down Expand Up @@ -129,11 +148,15 @@ class PeeringPeerSession {
private stateDirty = false
private readonly pendingEvents: Event[] = []
private pendingEventBytes = 0
private invoiceQueue: InvoiceEventQueue = { events: [], bytes: 0 }
private invoiceDraining = false
private invoiceSequence = 0
private invoiceProcessedSequence = 0
private invoiceWaiters: InvoiceQueueWaiter[] = []
private drainingEvents = false
private readonly persistEvents: (events: Event[]) => Promise<number>
private stateHeartbeatTimer: NodeJS.Timeout | undefined
private advertisement: PeeringAdvertisement | undefined
private invoiceHandling: Promise<void> = Promise.resolve()

public constructor(
private readonly peer: PeeringPeer,
Expand Down Expand Up @@ -197,6 +220,7 @@ class PeeringPeerSession {
this.connection = undefined
this.pendingEvents.length = 0
this.pendingEventBytes = 0
this.resetInvoiceQueue()
this.queueState({ status: 'stopped' })
void this.flushState()
}
Expand Down Expand Up @@ -224,6 +248,7 @@ class PeeringPeerSession {
} finally {
this.connection?.close()
this.connection = undefined
this.resetInvoiceQueue()
clearInterval(this.reconcileTimer)
this.reconcileTimer = undefined
}
Expand Down Expand Up @@ -312,6 +337,108 @@ class PeeringPeerSession {
}
}

/**
* Drop every waiting event and switch to a fresh queue. A wallet call that is
* already running is left alone; the single dispatcher will pick up the new
* queue when it returns.
*
* Discarded admissions count as settled: a later barrier belongs to a new
* connection and must never wait for work this connection dropped.
*/
private resetInvoiceQueue(): void {
this.invoiceQueue = { events: [], bytes: 0 }
this.invoiceProcessedSequence = this.invoiceSequence
this.releaseInvoiceWaiters()
}

/**
* Wait until every invoice admitted up to `seq` has been handled. Waiters are
* tied to one connection: if that connection closes first, its waiter is
* removed so reconnects cannot accumulate abandoned resolvers.
*/
private waitForInvoicesProcessedThrough(seq: number, connection: PeeringSyncConnection): Promise<void> {
if (this.invoiceProcessedSequence >= seq) {
return Promise.resolve()
}

return new Promise((resolve) => {
const waiter: InvoiceQueueWaiter = { seq, resolve }
this.invoiceWaiters.push(waiter)
void connection
.waitForClose()
.then(() => this.settleInvoiceWaiter(waiter))
.catch(() => this.settleInvoiceWaiter(waiter))
})
}

private settleInvoiceWaiter(waiter: InvoiceQueueWaiter): void {
const index = this.invoiceWaiters.indexOf(waiter)
if (index === -1) {
return
}

this.invoiceWaiters.splice(index, 1)
waiter.resolve()
}

private resolveInvoiceWaiters(): void {
if (this.invoiceWaiters.length === 0) {
return
}

const pending: InvoiceQueueWaiter[] = []
for (const waiter of this.invoiceWaiters) {
if (this.invoiceProcessedSequence >= waiter.seq) {
waiter.resolve()
} else {
pending.push(waiter)
}
}
this.invoiceWaiters = pending
}

private releaseInvoiceWaiters(): void {
const waiters = this.invoiceWaiters
this.invoiceWaiters = []
for (const waiter of waiters) {
waiter.resolve()
}
}

private async drainInvoiceQueue(): Promise<void> {
if (this.invoiceDraining) {
return
}

this.invoiceDraining = true
try {
while (!this.stopped) {
const queue = this.invoiceQueue
const item = queue.events.shift()
if (!item) {
if (queue !== this.invoiceQueue) {
continue
}
this.resolveInvoiceWaiters()
return
}

// Count only waiting work, not the single uncancellable wallet call.
queue.bytes = Math.max(0, queue.bytes - item.size)
try {
await this.handleInvoiceEvent(item.event)
} catch (error) {
logger.error('unable to handle a queued peering invoice from %s: %o', this.peer.relayUrl, error)
}
this.invoiceProcessedSequence = Math.max(this.invoiceProcessedSequence, item.seq)
this.resolveInvoiceWaiters()
}
} finally {
this.invoiceDraining = false
this.resolveInvoiceWaiters()
}
}

/**
* The seller publishes its kind 402 invoice on the same authenticated
* connection. Asking for it in its own short subscription keeps invoices out
Expand All @@ -336,16 +463,31 @@ class PeeringPeerSession {
}

await connection.subscribe([filter], (event) => {
// Keep the queue alive after a malformed event or a rejected handler.
this.invoiceHandling = this.invoiceHandling
.then(() => this.handleInvoiceEvent(event))
.catch((error) => {
logger.error('unable to queue a peering invoice from %s: %o', this.peer.relayUrl, error)
})
const size = Buffer.byteLength(JSON.stringify(event))
const queue = this.invoiceQueue
if (
queue.events.length >= PEERING_INVOICE_MAX_PENDING_EVENTS ||
queue.bytes + size > PEERING_INVOICE_MAX_PENDING_EVENT_BYTES
) {
logger.warn('peer %s invoice backlog exceeded; reconnecting', this.peer.relayUrl)
this.connection?.close()
this.resetInvoiceQueue()
return
}

this.invoiceSequence += 1
queue.events.push({ event, size, seq: this.invoiceSequence })
queue.bytes += size
void this.drainInvoiceQueue()
})

// Let the invoice reach the buyer service before opening a paid feed.
await this.invoiceHandling
// Let the invoices admitted during the handshake reach the buyer service
// before opening a paid feed. The barrier is a sequence number, not queue
// idleness: a busy stream must not postpone the live feed forever. It also
// ends when the connection closes, so an overflow cannot hang the worker.
const barrier = this.invoiceSequence
void this.drainInvoiceQueue()
await this.waitForInvoicesProcessedThrough(barrier, connection)
}

private async handleInvoiceEvent(event: Event): Promise<void> {
Expand Down
Loading
Loading