diff --git a/.changeset/peering-invoice-queue-limit.md b/.changeset/peering-invoice-queue-limit.md new file mode 100644 index 000000000..8d35e1dda --- /dev/null +++ b/.changeset/peering-invoice-queue-limit.md @@ -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. diff --git a/docs/PEERING.md b/docs/PEERING.md index 6feb580cb..200754391 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -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 diff --git a/src/app/peering-sync-worker.ts b/src/app/peering-sync-worker.ts index 887f5436e..86b8ce200 100644 --- a/src/app/peering-sync-worker.ts +++ b/src/app/peering-sync-worker.ts @@ -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, @@ -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 private stateHeartbeatTimer: NodeJS.Timeout | undefined private advertisement: PeeringAdvertisement | undefined - private invoiceHandling: Promise = Promise.resolve() public constructor( private readonly peer: PeeringPeer, @@ -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() } @@ -224,6 +248,7 @@ class PeeringPeerSession { } finally { this.connection?.close() this.connection = undefined + this.resetInvoiceQueue() clearInterval(this.reconcileTimer) this.reconcileTimer = undefined } @@ -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 { + 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 { + 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 @@ -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 { diff --git a/test/unit/app/peering-sync-worker.spec.ts b/test/unit/app/peering-sync-worker.spec.ts index a536be5ff..455d5ef5c 100644 --- a/test/unit/app/peering-sync-worker.spec.ts +++ b/test/unit/app/peering-sync-worker.spec.ts @@ -4,7 +4,11 @@ import { Event } from '../../../src/@types/event' import { PeeringPeerSyncState } from '../../../src/@types/peering' import { IEventRepository, ReconciliationItem } from '../../../src/@types/repositories' import { Settings } from '../../../src/@types/settings' -import { PeeringSyncWorker } from '../../../src/app/peering-sync-worker' +import { + PEERING_INVOICE_MAX_PENDING_EVENT_BYTES, + PEERING_INVOICE_MAX_PENDING_EVENTS, + PeeringSyncWorker, +} from '../../../src/app/peering-sync-worker' import { getPublicKey, identifyEvent, isEventMatchingFilter, signEvent } from '../../../src/utils/event' import { PeeringFetchOverflowError } from '../../../src/utils/peering-connection' import { PeeringSyncStateStore } from '../../../src/utils/peering-sync-state' @@ -251,6 +255,34 @@ describe('PeeringSyncWorker', () => { worker.run() } + /** + * Simulate the seller re-publishing its open invoice during the subscribe + * handshake, which is when the initial payment barrier is captured. + */ + const injectInvoiceOnSubscribe = (target: FakeConnection, event: Event): void => { + const subscribe = target.subscribe.bind(target) + let injected = false + target.subscribe = async (filters, onEvent) => { + await subscribe(filters, onEvent) + if (injected) { + return + } + + const isInvoice = (filters as any[]).some( + (filter) => Array.isArray(filter?.kinds) && filter.kinds.length === 1 && filter.kinds[0] === 402, + ) + if (isInvoice) { + injected = true + target.invoiceOnEvent?.(event) + } + } + } + + const invoiceWaiters = (): any[] => + [...((worker as any).sessions as Map).values()].flatMap( + (session) => session.invoiceWaiters as any[], + ) + it('converges an empty store from negentropy and then applies live events', async () => { const current = Math.floor(Date.now() / 1000) const historical = await makeEvent('historical', current - 30) @@ -560,6 +592,118 @@ describe('PeeringSyncWorker', () => { expect(calls[0][2].id).to.equal(invoiceEvent.id) }) + it('starts the live feed without waiting for invoices admitted after the handshake', async () => { + const terms = [{ amount: 250_000_000, unit: 'msats', period: 2592000 }] + const invoiceEvent = await makePaidInvoiceEvent() + let calls = 0 + let releaseFirst: (() => void) | undefined + const firstGate = new Promise((resolve) => { + releaseFirst = resolve + }) + const buyerService = { + handleInvoice: async () => { + calls += 1 + if (calls === 1) { + return firstGate + } + + return new Promise(() => undefined) + }, + } + + startWorker([], { + terms, + buyerService, + configureConnection: (target) => injectInvoiceOnSubscribe(target, invoiceEvent), + }) + + // The handshake invoice belongs to the barrier, so the live feed waits. + await waitFor(() => calls === 1) + expect(connection.liveOnEvent).to.equal(undefined) + + // This one arrives after the barrier and must not extend it. + connection.invoiceOnEvent?.(invoiceEvent) + releaseFirst?.() + + // The first invoice settling releases the barrier even though the second is + // still blocked in the wallet. + await waitFor(() => typeof connection.liveOnEvent === 'function') + expect(calls).to.equal(2) + }) + + it('drops the handshake invoice barrier waiter when the connection closes', async () => { + const terms = [{ amount: 250_000_000, unit: 'msats', period: 2592000 }] + const invoiceEvent = await makePaidInvoiceEvent() + const buyerService = { + handleInvoice: async () => new Promise(() => undefined), + } + + startWorker([], { + terms, + buyerService, + configureConnection: (target) => injectInvoiceOnSubscribe(target, invoiceEvent), + }) + + await waitFor(() => invoiceWaiters().length === 1) + const waiter = invoiceWaiters()[0] + + connection.close() + + // The abandoned waiter belongs to the closed connection and must be removed, + // even while the wallet call is still running. + await waitFor(() => !invoiceWaiters().includes(waiter)) + }) + + it('closes the connection when the invoice backlog count is exceeded', async () => { + const terms = [{ amount: 250_000_000, unit: 'msats', period: 2592000 }] + let release: (() => void) | undefined + const gate = new Promise((resolve) => { + release = resolve + }) + const calls: any[][] = [] + const buyerService = { + handleInvoice: async (...args: any[]) => { + calls.push(args) + return gate + }, + } + const invoiceEvent = await makePaidInvoiceEvent() + + startWorker([], { terms, buyerService }) + await waitFor(() => typeof connection.invoiceOnEvent === 'function') + + for (let index = 0; index <= PEERING_INVOICE_MAX_PENDING_EVENTS + 1; index += 1) { + connection.invoiceOnEvent?.(invoiceEvent) + } + + await waitFor(() => connection.closeCalls > 0) + release?.() + await new Promise((resolve) => setTimeout(resolve, 50)) + + // The in-flight call finishes, but the 99 queued events were discarded. + expect(calls).to.have.length(1) + }) + + it('closes the connection when the invoice backlog bytes are exceeded', async () => { + const terms = [{ amount: 250_000_000, unit: 'msats', period: 2592000 }] + const buyerService = { + handleInvoice: async () => new Promise(() => undefined), + } + const invoiceEvent = await makePaidInvoiceEvent() + const hugeEvent = { + ...invoiceEvent, + content: 'x'.repeat(PEERING_INVOICE_MAX_PENDING_EVENT_BYTES), + } + + startWorker([], { terms, buyerService }) + await waitFor(() => typeof connection.invoiceOnEvent === 'function') + + connection.invoiceOnEvent?.(invoiceEvent) + connection.invoiceOnEvent?.(hugeEvent) + + await waitFor(() => connection.closeCalls > 0) + }) + it('keeps processing invoices after a malformed event', async () => { const calls: any[][] = [] const terms = [{ amount: 250_000_000, unit: 'msats', period: 2592000 }]