From 8ee49744ad992e83d1ae794e721432b7f38bac9d Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Sat, 28 Nov 2026 21:52:47 +0530 Subject: [PATCH 1/3] fix(peering): bound the buyer invoice queue - cap queued kind-402 invoice events at 100 and 2 MiB\n- close and reconnect when either limit is exceeded instead of growing the promise chain\n- reset the invoice chain on stop/reconnect and stop waiting for it once the socket closes\n- cover count and byte overflow in worker tests --- .changeset/peering-invoice-queue-limit.md | 10 +++++ docs/PEERING.md | 6 +++ src/app/peering-sync-worker.ts | 36 ++++++++++++++++- test/unit/app/peering-sync-worker.spec.ts | 48 ++++++++++++++++++++++- 4 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 .changeset/peering-invoice-queue-limit.md diff --git a/.changeset/peering-invoice-queue-limit.md b/.changeset/peering-invoice-queue-limit.md new file mode 100644 index 000000000..50ac21aff --- /dev/null +++ b/.changeset/peering-invoice-queue-limit.md @@ -0,0 +1,10 @@ +--- +"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. 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 977817ea9..2b52d36fb 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -300,6 +300,12 @@ 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. 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..8b683dad6 100644 --- a/src/app/peering-sync-worker.ts +++ b/src/app/peering-sync-worker.ts @@ -54,6 +54,9 @@ 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 const eventShapeSchema = z @@ -129,6 +132,8 @@ class PeeringPeerSession { private stateDirty = false private readonly pendingEvents: Event[] = [] private pendingEventBytes = 0 + private invoiceQueueSize = 0 + private invoiceQueueBytes = 0 private drainingEvents = false private readonly persistEvents: (events: Event[]) => Promise private stateHeartbeatTimer: NodeJS.Timeout | undefined @@ -197,6 +202,7 @@ class PeeringPeerSession { this.connection = undefined this.pendingEvents.length = 0 this.pendingEventBytes = 0 + this.resetInvoiceQueue() this.queueState({ status: 'stopped' }) void this.flushState() } @@ -224,6 +230,7 @@ class PeeringPeerSession { } finally { this.connection?.close() this.connection = undefined + this.resetInvoiceQueue() clearInterval(this.reconcileTimer) this.reconcileTimer = undefined } @@ -312,6 +319,13 @@ class PeeringPeerSession { } } + /** Reconnect recovery starts a fresh chain instead of inheriting old backlog. */ + private resetInvoiceQueue(): void { + this.invoiceQueueSize = 0 + this.invoiceQueueBytes = 0 + this.invoiceHandling = Promise.resolve() + } + /** * 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 +350,34 @@ class PeeringPeerSession { } await connection.subscribe([filter], (event) => { + const size = Buffer.byteLength(JSON.stringify(event)) + if ( + this.invoiceQueueSize >= PEERING_INVOICE_MAX_PENDING_EVENTS || + this.invoiceQueueBytes + 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.invoiceQueueSize += 1 + this.invoiceQueueBytes += size // 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) }) + .finally(() => { + this.invoiceQueueSize = Math.max(0, this.invoiceQueueSize - 1) + this.invoiceQueueBytes = Math.max(0, this.invoiceQueueBytes - size) + }) }) - // Let the invoice reach the buyer service before opening a paid feed. - await this.invoiceHandling + // Let the invoice reach the buyer service before opening a paid feed, but + // do not wait forever if the invoice queue overflow closed the connection. + await Promise.race([this.invoiceHandling, connection.waitForClose()]) } 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..72c32ef80 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' @@ -560,6 +564,48 @@ describe('PeeringSyncWorker', () => { expect(calls[0][2].id).to.equal(invoiceEvent.id) }) + 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 buyerService = { + handleInvoice: async () => gate, + } + const invoiceEvent = await makePaidInvoiceEvent() + + startWorker([], { terms, buyerService }) + await waitFor(() => typeof connection.invoiceOnEvent === 'function') + + for (let index = 0; index <= PEERING_INVOICE_MAX_PENDING_EVENTS; index += 1) { + connection.invoiceOnEvent?.(invoiceEvent) + } + + await waitFor(() => connection.closeCalls > 0) + release?.() + }) + + 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 }] From 9608b54449a989e3cade1135bbea78e91893e847 Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Sat, 28 Nov 2026 23:30:00 +0530 Subject: [PATCH 2/3] fix(peering): discard the invoice backlog on reconnect - replace the promise chain with an explicit per-queue event array\n- reset drops waiting events and starts a fresh queue\n- keep one dispatcher across generations so only one wallet call is in flight\n- decrement counters on dequeue so old completions cannot change a new queue's accounting --- .changeset/peering-invoice-queue-limit.md | 5 +- docs/PEERING.md | 8 +- src/app/peering-sync-worker.ts | 101 +++++++++++++++++----- test/unit/app/peering-sync-worker.spec.ts | 12 ++- 4 files changed, 97 insertions(+), 29 deletions(-) diff --git a/.changeset/peering-invoice-queue-limit.md b/.changeset/peering-invoice-queue-limit.md index 50ac21aff..75cfa8ce7 100644 --- a/.changeset/peering-invoice-queue-limit.md +++ b/.changeset/peering-invoice-queue-limit.md @@ -6,5 +6,6 @@ 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. Invoice dedupe and the -seller's re-issued open invoice make the reconnect safe. +either closes the peering connection and reconnects. Pending events are +discarded on reconnect and only one wallet call can remain in flight. 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 b37c7e719..3df7c3a5b 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -304,9 +304,11 @@ 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. The seller exposes -its current open invoice again on reconnect, and payment-hash dedupe prevents -a second payment. +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 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: diff --git a/src/app/peering-sync-worker.ts b/src/app/peering-sync-worker.ts index 8b683dad6..8be1b3955 100644 --- a/src/app/peering-sync-worker.ts +++ b/src/app/peering-sync-worker.ts @@ -59,6 +59,16 @@ 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 +} + +interface InvoiceEventQueue { + events: QueuedInvoiceEvent[] + bytes: number +} + const eventShapeSchema = z .object({ id: idSchema, @@ -132,13 +142,13 @@ class PeeringPeerSession { private stateDirty = false private readonly pendingEvents: Event[] = [] private pendingEventBytes = 0 - private invoiceQueueSize = 0 - private invoiceQueueBytes = 0 + private invoiceQueue: InvoiceEventQueue = { events: [], bytes: 0 } + private invoiceDraining = false + private invoiceIdleResolvers: Array<() => void> = [] 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, @@ -319,11 +329,66 @@ class PeeringPeerSession { } } - /** Reconnect recovery starts a fresh chain instead of inheriting old backlog. */ + /** + * 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. + */ private resetInvoiceQueue(): void { - this.invoiceQueueSize = 0 - this.invoiceQueueBytes = 0 - this.invoiceHandling = Promise.resolve() + this.invoiceQueue = { events: [], bytes: 0 } + this.notifyInvoiceIdle() + } + + private waitForInvoiceQueueIdle(): Promise { + if (!this.invoiceDraining && this.invoiceQueue.events.length === 0) { + return Promise.resolve() + } + + return new Promise((resolve) => this.invoiceIdleResolvers.push(resolve)) + } + + private notifyInvoiceIdle(): void { + if (this.invoiceDraining || this.invoiceQueue.events.length > 0) { + return + } + + const waiters = this.invoiceIdleResolvers + this.invoiceIdleResolvers = [] + for (const resolve of waiters) { + 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.notifyInvoiceIdle() + 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) + } + } + } finally { + this.invoiceDraining = false + this.notifyInvoiceIdle() + } } /** @@ -351,9 +416,10 @@ class PeeringPeerSession { await connection.subscribe([filter], (event) => { const size = Buffer.byteLength(JSON.stringify(event)) + const queue = this.invoiceQueue if ( - this.invoiceQueueSize >= PEERING_INVOICE_MAX_PENDING_EVENTS || - this.invoiceQueueBytes + size > PEERING_INVOICE_MAX_PENDING_EVENT_BYTES + 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() @@ -361,23 +427,14 @@ class PeeringPeerSession { return } - this.invoiceQueueSize += 1 - this.invoiceQueueBytes += size - // 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) - }) - .finally(() => { - this.invoiceQueueSize = Math.max(0, this.invoiceQueueSize - 1) - this.invoiceQueueBytes = Math.max(0, this.invoiceQueueBytes - size) - }) + queue.events.push({ event, size }) + queue.bytes += size + void this.drainInvoiceQueue() }) // Let the invoice reach the buyer service before opening a paid feed, but // do not wait forever if the invoice queue overflow closed the connection. - await Promise.race([this.invoiceHandling, connection.waitForClose()]) + await Promise.race([this.waitForInvoiceQueueIdle(), connection.waitForClose()]) } 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 72c32ef80..57cedc872 100644 --- a/test/unit/app/peering-sync-worker.spec.ts +++ b/test/unit/app/peering-sync-worker.spec.ts @@ -570,20 +570,28 @@ describe('PeeringSyncWorker', () => { const gate = new Promise((resolve) => { release = resolve }) + const calls: any[][] = [] const buyerService = { - handleInvoice: async () => gate, + 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; index += 1) { + 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 () => { From 49cc822b78f3eb549b320a98926ac35c21cbffc2 Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Sun, 29 Nov 2026 09:09:30 +0530 Subject: [PATCH 3/3] fix(peering): scope the invoice barrier to one connection - capture the handshake barrier as an admission sequence instead of global queue idleness\n- release barrier waiters when their connection closes so reconnects cannot accumulate resolvers\n- keep later invoices from postponing the live feed\n- cover the barrier boundary and waiter cleanup in worker tests --- .changeset/peering-invoice-queue-limit.md | 4 +- docs/PEERING.md | 7 +- src/app/peering-sync-worker.ts | 87 +++++++++++++++++----- test/unit/app/peering-sync-worker.spec.ts | 90 +++++++++++++++++++++++ 4 files changed, 167 insertions(+), 21 deletions(-) diff --git a/.changeset/peering-invoice-queue-limit.md b/.changeset/peering-invoice-queue-limit.md index 75cfa8ce7..8d35e1dda 100644 --- a/.changeset/peering-invoice-queue-limit.md +++ b/.changeset/peering-invoice-queue-limit.md @@ -7,5 +7,7 @@ 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. Invoice +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 3df7c3a5b..200754391 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -306,9 +306,10 @@ 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 seller exposes its current -open invoice again on reconnect, and payment-hash dedupe prevents a second -payment. +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: diff --git a/src/app/peering-sync-worker.ts b/src/app/peering-sync-worker.ts index 8be1b3955..86b8ce200 100644 --- a/src/app/peering-sync-worker.ts +++ b/src/app/peering-sync-worker.ts @@ -62,6 +62,7 @@ export const PEERING_SYNC_MAX_SCOPE_SPLIT_DEPTH = 20 interface QueuedInvoiceEvent { event: Event size: number + seq: number } interface InvoiceEventQueue { @@ -69,6 +70,11 @@ interface InvoiceEventQueue { bytes: number } +interface InvoiceQueueWaiter { + seq: number + resolve: () => void +} + const eventShapeSchema = z .object({ id: idSchema, @@ -144,7 +150,9 @@ class PeeringPeerSession { private pendingEventBytes = 0 private invoiceQueue: InvoiceEventQueue = { events: [], bytes: 0 } private invoiceDraining = false - private invoiceIdleResolvers: Array<() => void> = [] + private invoiceSequence = 0 + private invoiceProcessedSequence = 0 + private invoiceWaiters: InvoiceQueueWaiter[] = [] private drainingEvents = false private readonly persistEvents: (events: Event[]) => Promise private stateHeartbeatTimer: NodeJS.Timeout | undefined @@ -333,29 +341,67 @@ 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.notifyInvoiceIdle() + this.invoiceProcessedSequence = this.invoiceSequence + this.releaseInvoiceWaiters() } - private waitForInvoiceQueueIdle(): Promise { - if (!this.invoiceDraining && this.invoiceQueue.events.length === 0) { + /** + * 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) => this.invoiceIdleResolvers.push(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 notifyInvoiceIdle(): void { - if (this.invoiceDraining || this.invoiceQueue.events.length > 0) { + private resolveInvoiceWaiters(): void { + if (this.invoiceWaiters.length === 0) { return } - const waiters = this.invoiceIdleResolvers - this.invoiceIdleResolvers = [] - for (const resolve of waiters) { - resolve() + 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() } } @@ -373,7 +419,7 @@ class PeeringPeerSession { if (queue !== this.invoiceQueue) { continue } - this.notifyInvoiceIdle() + this.resolveInvoiceWaiters() return } @@ -384,10 +430,12 @@ class PeeringPeerSession { } 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.notifyInvoiceIdle() + this.resolveInvoiceWaiters() } } @@ -427,14 +475,19 @@ class PeeringPeerSession { return } - queue.events.push({ event, size }) + 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, but - // do not wait forever if the invoice queue overflow closed the connection. - await Promise.race([this.waitForInvoiceQueueIdle(), connection.waitForClose()]) + // 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 57cedc872..455d5ef5c 100644 --- a/test/unit/app/peering-sync-worker.spec.ts +++ b/test/unit/app/peering-sync-worker.spec.ts @@ -255,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) @@ -564,6 +592,68 @@ 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