From f42a762fddf4c43787a80ebaedfd55ecf0941651 Mon Sep 17 00:00:00 2001 From: AgrimTawani Date: Sat, 28 Nov 2026 22:07:52 +0530 Subject: [PATCH 1/3] fix(subscriptions): stop an aborted REQ from stranding its database connection A REQ's stored-events read is a knex stream over a pg cursor. Aborting it (CLOSE, a closed socket, a rate-limit refusal) destroyed that stream at once, which is unsafe in two windows: - before knex holds a connection, its close handler throws the __knexUid TypeError the web worker logs as "Unable to acquire connection", and the connection the pool hands out afterwards runs the query into the closed stream and is never released; - before pg has submitted the query (it queues behind a connection still closing the previous cursor), the cursor close is a no-op, so pg submits it afterwards and the backend sits active in ClientRead for good while the pool hands the connection to queries that queue behind it. Each abort that lands in a window costs a connection, the windows widen as the pool fills, and once it is full every REQ on the worker hangs (#1243). The read now goes through abortableQueryStream: the subscription still ends at once on abort, but knex's stream is destroyed only after knex has piped its query in and the cursor is idle, done or errored. A REQ aborted before its query starts no longer starts one. Checked against Postgres 16 with pool max 4 and 600 REQs aborted at random points: the old path leaves the pool full, the new one leaves it empty with every connection usable. Closes #1243 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9f8c1668f184f6a7dc3e5cfac360c38e74d43220) --- .changeset/req-cursor-release-on-abort.md | 7 + src/handlers/subscribe-message-handler.ts | 9 +- src/utils/query-stream.ts | 84 +++++++ .../subscribe-message-handler.spec.ts | 55 +++-- test/unit/utils/query-stream.spec.ts | 212 ++++++++++++++++++ 5 files changed, 346 insertions(+), 21 deletions(-) create mode 100644 .changeset/req-cursor-release-on-abort.md create mode 100644 src/utils/query-stream.ts create mode 100644 test/unit/utils/query-stream.spec.ts diff --git a/.changeset/req-cursor-release-on-abort.md b/.changeset/req-cursor-release-on-abort.md new file mode 100644 index 000000000..496052930 --- /dev/null +++ b/.changeset/req-cursor-release-on-abort.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(subscriptions): stop an aborted REQ from stranding its database connection + +A REQ aborted before its query was running (a CLOSE, a closed socket or a rate-limit refusal that lands while the read waits for a pooled connection) destroyed knex's stream too early. Before knex held a connection the release threw the `__knexUid` TypeError the web worker logs as "Unable to acquire connection"; before pg had submitted the queued query the cursor close was a no-op, so pg ran it afterwards and the connection sat `active` in `ClientRead` for good. Each one cost a connection until the pool was full and every REQ on that worker hung. The read is now aborted through a wrapper that ends the subscription at once and closes the cursor only when that is safe, and a REQ aborted before its query starts no longer starts one. diff --git a/src/handlers/subscribe-message-handler.ts b/src/handlers/subscribe-message-handler.ts index 0b910e784..ef8ead5da 100644 --- a/src/handlers/subscribe-message-handler.ts +++ b/src/handlers/subscribe-message-handler.ts @@ -1,5 +1,4 @@ import { anyPass, equals, isNil, map, omit, propSatisfies, uniqWith } from 'ramda' -import { addAbortSignal } from 'stream' import { pipeline } from 'stream/promises' import { IWebSocketAdapter } from '../@types/adapters' import { Factory, Pubkey } from '../@types/base' @@ -29,6 +28,7 @@ import { subscriptionLimitsFor } from '../utils/peer-limits' import { getPeerRequestRetryAfterMs } from '../utils/peer-requests' import { isPeeringInvoiceRequest, PeeringInvoiceCooldownError, peeringPaymentRequiredReason } from '../utils/peering-billing' import { PeeringRequestStatsStore } from '../utils/peering-request-stats' +import { abortableQueryStream } from '../utils/query-stream' import { streamEachAsync, streamEnd, streamFilter, streamMap } from '../utils/stream' const logger = createLogger('subscribe-message-handler') @@ -367,11 +367,15 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable { const isPeer = this.webSocket.getPeerPubkey() !== undefined const peerDefaultLimit = isPeer ? (this.settings().limits?.peer?.subscription?.maxLimit ?? 0) : undefined + // CLOSE or a closed socket can abort this handler before it gets here; do not start a query + // only to abandon it. + this.abortController.signal.throwIfAborted() + const findEvents = isPeer ? this.eventRepository.findByFilters(filters, { defaultLimit: peerDefaultLimit, excludeDeleted: true }).stream() : this.eventRepository.findByFilters(filters).stream() - const abortableFindEvents = addAbortSignal(this.abortController.signal, findEvents) + const abortableFindEvents = abortableQueryStream(findEvents, this.abortController.signal) try { await pipeline( @@ -387,7 +391,6 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable { } catch (error) { if (error instanceof Error && error.name === 'AbortError') { logger('subscription %s aborted: %o', subscriptionId, error) - findEvents.destroy() } else { logger('error streaming events: %o', error) } diff --git a/src/utils/query-stream.ts b/src/utils/query-stream.ts new file mode 100644 index 000000000..4e5f174ef --- /dev/null +++ b/src/utils/query-stream.ts @@ -0,0 +1,84 @@ +import { addAbortSignal, PassThrough, Readable } from 'stream' + +/** The part of pg-query-stream's `QueryStream` that says how far its cursor has got. */ +type QuerySource = Readable & { cursor?: { state?: string } } + +/** States in which pg-cursor's `close()` closes the portal cleanly. */ +const CLOSEABLE_CURSOR_STATES = new Set(['idle', 'done', 'error']) + +/** How often a pending close looks at the cursor again. */ +const CURSOR_POLL_MS = 5 + +/** + * Runs `fn` once closing the cursor `source` reads from is safe. + * + * - `initialized`: pg queued the query behind a connection that is still closing the previous + * cursor. Closing now is a no-op and pg submits the query anyway, so its portal stays open and + * the connection never runs another query. + * - `submitted` / `busy`: a fetch is in flight. Closing now lets pg-cursor's own read run after + * the close and desynchronise the connection's protocol state. + * + * pg-cursor emits nothing when it goes idle, and a paused stream emits no 'data', so the state + * is looked at again every few milliseconds; a fetch in flight settles in about one round trip. + */ +const whenCursorCanClose = (source: QuerySource | undefined, fn: () => void): void => { + const check = () => { + const state = source?.cursor?.state + if (!source || source.destroyed || state === undefined || CLOSEABLE_CURSOR_STATES.has(state)) { + fn() + return + } + setTimeout(check, CURSOR_POLL_MS).unref() + } + check() +} + +/** + * Wraps a knex `.stream()` so that aborting the read cannot strand its pooled connection + * (#1243). + * + * knex returns that stream before it holds a connection. When the connection arrives it hands + * pg a query stream and pipes it in; destroying knex's stream releases the connection to the + * pool and destroys that query stream. Two windows make that unsafe: + * + * - before knex holds a connection, the release throws (`releaseConnection(undefined)`) and the + * connection the pool hands out afterwards runs the query into the closed stream for good; + * - before pg has submitted the query (it queues behind a connection that is still closing the + * previous cursor), closing the cursor is a no-op, so pg submits it afterwards and its portal + * sits open, the backend `active` in `ClientRead`, while the pool hands the connection to the + * next query, which queues behind it forever. + * + * The wrapper is what the caller pipes and aborts; it ends or fails with the query as before. + * knex's stream is destroyed only once its query is piped in and its cursor can close. Wrap the stream in + * the same tick as `.stream()`, before knex can have piped into it. + */ +export const abortableQueryStream = (query: Readable, signal: AbortSignal): Readable => { + let attached = false + let source: QuerySource | undefined + query.once('pipe', (piped: QuerySource) => { + attached = true + source = piped + }) + + const output = new PassThrough({ objectMode: true }) + + const destroyQuery = () => whenCursorCanClose(source, () => query.destroy()) + + const release = () => { + if (query.destroyed || query.readableEnded) { + return + } + query.unpipe(output) + if (attached) { + destroyQuery() + } else { + query.once('pipe', () => process.nextTick(destroyQuery)) + } + } + + query.on('error', (error) => output.destroy(error)) + output.once('close', release) + query.pipe(output) + + return addAbortSignal(signal, output) +} diff --git a/test/unit/handlers/subscribe-message-handler.spec.ts b/test/unit/handlers/subscribe-message-handler.spec.ts index 72e320a97..f6364549d 100644 --- a/test/unit/handlers/subscribe-message-handler.spec.ts +++ b/test/unit/handlers/subscribe-message-handler.spec.ts @@ -1005,50 +1005,69 @@ describe('SubscribeMessageHandler', () => { expect(webSocketOnMessageStub).to.have.been.calledWithExactly(['EOSE', subscriptionId]) }) - it('ends event stream if error occurs', async () => { + it('rejects if the event stream errors', async () => { const error = new Error('mistakes were made') isClientSubscribedToEventStub.returns(always(true)) - const fetch = () => (handler as any).fetchAndSend(subscriptionId, filters) - - const promise = fetch() + const promise = (handler as any).fetchAndSend(subscriptionId, filters) stream.emit('error', error) - const closeSpy = sandbox.spy() - stream.once('close', closeSpy) - await expect(promise).to.eventually.be.rejectedWith(error) - expect(closeSpy).to.have.been.called }) - it('destroys event stream if aborted', async () => { + it('rejects with the abort error the event stream raises', async () => { const error = new Error('aborted') error.name = 'AbortError' isClientSubscribedToEventStub.returns(always(true)) - const fetch = () => (handler as any).fetchAndSend(subscriptionId, filters) - const destroySpy = sandbox.spy(stream, 'destroy') - - const promise = fetch() + const promise = (handler as any).fetchAndSend(subscriptionId, filters) stream.emit('error', error) await expect(promise).to.eventually.be.rejectedWith(error) - expect(destroySpy).to.have.been.called }) - it('aborts and destroys the event stream when abort() is called', async () => { + it('destroys the event stream at once when abort() is called mid-stream', async () => { isClientSubscribedToEventStub.returns(always(true)) + const source = new PassThrough({ objectMode: true }) + + const promise = (handler as any).fetchAndSend(subscriptionId, filters) + source.pipe(stream) + source.write(toDbEvent(event)) + + handler.abort() - const destroySpy = sandbox.spy(stream, 'destroy') + await expect(promise).to.eventually.be.rejected.and.have.property('name', 'AbortError') + expect(stream.destroyed).to.equal(true) + }) + + // #1243: knex hands out its stream before it holds a connection. Destroying the stream in + // that window strands the connection it is handed later, so the destroy waits for knex to + // pipe its query in. + it('waits for the query to be piped in before destroying an event stream aborted early', async () => { + isClientSubscribedToEventStub.returns(always(true)) const promise = (handler as any).fetchAndSend(subscriptionId, filters) + handler.abort() + + await expect(promise).to.eventually.be.rejected.and.have.property('name', 'AbortError') + expect(stream.destroyed).to.equal(false) + new PassThrough({ objectMode: true }).pipe(stream) + await new Promise((resolve) => process.nextTick(resolve)) + + expect(stream.destroyed).to.equal(true) + }) + + it('does not start a query when the handler was aborted before it got there', async () => { handler.abort() - await expect(promise).to.eventually.be.rejected - expect(destroySpy).to.have.been.called + await expect((handler as any).fetchAndSend(subscriptionId, filters)).to.eventually.be.rejected.and.have.property( + 'name', + 'AbortError', + ) + expect(eventRepositoryFindByFiltersStub).not.to.have.been.called }) }) diff --git a/test/unit/utils/query-stream.spec.ts b/test/unit/utils/query-stream.spec.ts new file mode 100644 index 000000000..fb70971fc --- /dev/null +++ b/test/unit/utils/query-stream.spec.ts @@ -0,0 +1,212 @@ +import * as chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import { PassThrough, Readable, Transform, Writable } from 'stream' +import { pipeline } from 'stream/promises' + +import { abortableQueryStream } from '../../../src/utils/query-stream' + +chai.use(chaiAsPromised) + +const { expect } = chai + +/** + * The parts of knex 3.2.9's `Runner#stream` (lib/execution/runner.js) this module relies on: + * the stream is returned before the pool hands out a connection, its 'close' handler releases + * `this.connection`, and `releaseConnection(undefined)` throws. When the connection arrives the + * dialect pipes its query stream in, and a destroyed output destroys that source. + */ +const fakeKnexStream = () => { + const state: { connection?: object; released: number; sourceDestroyed: boolean } = { + released: 0, + sourceDestroyed: false, + } + const stream = new Transform({ + objectMode: true, + transform: (chunk, _encoding, callback) => callback(null, chunk), + }) + stream.on('close', () => { + if (!state.connection) { + throw new TypeError("Cannot read properties of undefined (reading '__knexUid')") + } + state.released += 1 + }) + stream.on('pipe', (source: Readable) => { + const clean = () => { + if (!source.closed) { + source.destroy() + } + } + if (stream.closed) { + clean() + } else { + stream.on('close', clean) + } + }) + + const attach = (cursorState?: string) => { + state.connection = {} + const source = new PassThrough({ objectMode: true }) as PassThrough & { cursor?: { state?: string } } + if (cursorState) { + source.cursor = { state: cursorState } + } + source.once('close', () => { + state.sourceDestroyed = true + }) + source.pipe(stream) + return source + } + + return { stream, attach, state } +} + +const drain = () => + new Writable({ + objectMode: true, + write(_chunk, _encoding, callback) { + callback() + }, + }) + +const tick = () => new Promise((resolve) => setImmediate(resolve)) + +describe('abortableQueryStream', () => { + it('does not destroy the query stream before knex has a connection, so the release cannot throw', async () => { + const { stream, attach, state } = fakeKnexStream() + const controller = new AbortController() + + const done = pipeline(abortableQueryStream(stream, controller.signal), drain()) + controller.abort() + + await expect(done).to.eventually.be.rejected.and.have.property('name', 'AbortError') + await tick() + expect(stream.destroyed).to.equal(false) + + attach() + await tick() + + expect(stream.destroyed).to.equal(true) + expect(state.released).to.equal(1) + expect(state.sourceDestroyed).to.equal(true) + }) + + it('destroys the query stream at once when aborted mid-stream', async () => { + const { stream, attach, state } = fakeKnexStream() + const controller = new AbortController() + + const done = pipeline(abortableQueryStream(stream, controller.signal), drain()) + const source = attach() + source.write({ id: 1 }) + await tick() + controller.abort() + + await expect(done).to.eventually.be.rejected.and.have.property('name', 'AbortError') + await tick() + expect(state.released).to.equal(1) + expect(state.sourceDestroyed).to.equal(true) + }) + + it('passes rows through and leaves a finished query alone', async () => { + const { stream, attach, state } = fakeKnexStream() + const rows: unknown[] = [] + + const done = pipeline( + abortableQueryStream(stream, new AbortController().signal), + new Writable({ + objectMode: true, + write(row, _encoding, callback) { + rows.push(row) + callback() + }, + }), + ) + const source = attach() + source.write({ id: 1 }) + source.write({ id: 2 }) + source.end() + + await done + expect(rows).to.deep.equal([{ id: 1 }, { id: 2 }]) + await tick() + expect(state.released).to.equal(1) + }) + + it('fails the pipeline when the query stream errors', async () => { + const { stream } = fakeKnexStream() + const error = new Error('Knex: Timeout acquiring a connection. The pool is probably full.') + + const done = pipeline(abortableQueryStream(stream, new AbortController().signal), drain()) + stream.emit('error', error) + + await expect(done).to.eventually.be.rejectedWith(error) + }) + + it('releases the query stream when a later stage fails', async () => { + const { stream, attach, state } = fakeKnexStream() + + const done = pipeline( + abortableQueryStream(stream, new AbortController().signal), + new Writable({ + objectMode: true, + write(_row, _encoding, callback) { + callback(new Error('send failed')) + }, + }), + ) + const source = attach() + source.write({ id: 1 }) + + await expect(done).to.eventually.be.rejectedWith('send failed') + await tick() + expect(state.released).to.equal(1) + expect(state.sourceDestroyed).to.equal(true) + }) + + it('is already aborted when handed an aborted signal, without touching an unattached query', async () => { + const { stream, attach, state } = fakeKnexStream() + const controller = new AbortController() + controller.abort() + + const done = pipeline(abortableQueryStream(stream, controller.signal), drain()) + + await expect(done).to.eventually.be.rejected.and.have.property('name', 'AbortError') + expect(stream.destroyed).to.equal(false) + attach() + await tick() + expect(state.released).to.equal(1) + }) + + for (const cursorState of ['initialized', 'submitted', 'busy']) { + it(`waits for a cursor that is ${cursorState} to settle before destroying the query stream`, async () => { + const { stream, attach, state } = fakeKnexStream() + const controller = new AbortController() + + const done = pipeline(abortableQueryStream(stream, controller.signal), drain()) + const source = attach(cursorState) + controller.abort() + + await expect(done).to.eventually.be.rejected.and.have.property('name', 'AbortError') + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(stream.destroyed).to.equal(false) + expect(state.released).to.equal(0) + + source.cursor = { state: 'idle' } + await new Promise((resolve) => setTimeout(resolve, 20)) + + expect(state.released).to.equal(1) + expect(state.sourceDestroyed).to.equal(true) + }) + } + + it('destroys the query stream at once when its cursor is idle', async () => { + const { stream, attach, state } = fakeKnexStream() + const controller = new AbortController() + + const done = pipeline(abortableQueryStream(stream, controller.signal), drain()) + attach('idle') + controller.abort() + + await expect(done).to.eventually.be.rejected + await tick() + expect(state.released).to.equal(1) + }) +}) From bc236932ee22137d93e697bcd3aacea54445f9bb Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 12:31:45 -0500 Subject: [PATCH 2/3] fix(subscriptions): do not release the pooled connection a second time on an abort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit knex releases a streamed query's connection twice over: from `ensureConnection`'s finally when the pg query stream ends, and from its own stream's 'close'. The wrapper added for #1243 defers destroying that stream until the cursor can close, so a query that ends inside that window — a small result, which is the common case for a REQ — has already released its connection when the deferred destroy fires 'close' and releases it again. tarn matches a release by resource identity, so the second release frees whatever lease holds that connection by then: the pool can hand one pg client to two requests. Measured on the wrapper's own fake of knex 3.2.9's semantics: one release before the guard, two after a source 'end' inside the poll window, one with the guard. The new case fails on the previous commit (released 2, expected 1) and passes here. The destroy now runs only for a query that is still open and whose source has not ended, so the connection is released by the path that owns it. --- src/utils/query-stream.ts | 21 ++++++++++++++++++++- test/unit/utils/query-stream.spec.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/utils/query-stream.ts b/src/utils/query-stream.ts index 4e5f174ef..6e0c1d3a6 100644 --- a/src/utils/query-stream.ts +++ b/src/utils/query-stream.ts @@ -55,14 +55,33 @@ const whenCursorCanClose = (source: QuerySource | undefined, fn: () => void): vo export const abortableQueryStream = (query: Readable, signal: AbortSignal): Readable => { let attached = false let source: QuerySource | undefined + let sourceEnded = false query.once('pipe', (piped: QuerySource) => { attached = true source = piped + piped.once('end', () => { + sourceEnded = true + }) + piped.once('close', () => { + sourceEnded = true + }) }) const output = new PassThrough({ objectMode: true }) - const destroyQuery = () => whenCursorCanClose(source, () => query.destroy()) + const destroyQuery = () => + whenCursorCanClose(source, () => { + // knex releases the connection twice over a query's life: from `ensureConnection`'s finally + // when the query stream ends, and from its own stream's 'close'. Destroying a stream whose + // query already ended fires that 'close' a second time, and tarn matches a release by + // resource identity, so the connection can be freed again after the pool has handed it to + // another request — two requests then share one client. Only destroy a query that is still + // running, so the connection is released by the path that owns it. + if (query.destroyed || query.readableEnded || sourceEnded) { + return + } + query.destroy() + }) const release = () => { if (query.destroyed || query.readableEnded) { diff --git a/test/unit/utils/query-stream.spec.ts b/test/unit/utils/query-stream.spec.ts index fb70971fc..dfe3aefe4 100644 --- a/test/unit/utils/query-stream.spec.ts +++ b/test/unit/utils/query-stream.spec.ts @@ -161,6 +161,34 @@ describe('abortableQueryStream', () => { expect(state.sourceDestroyed).to.equal(true) }) + it('does not release the connection again when the query ends while the abort waits for its cursor', async () => { + const { stream, attach, state } = fakeKnexStream() + const controller = new AbortController() + + const done = pipeline(abortableQueryStream(stream, controller.signal), drain()) + const source = attach('busy') + // knex releases from `ensureConnection`'s finally too, when the query stream ends. + const releaseFromFinally = () => { + state.released += 1 + } + source.once('end', releaseFromFinally) + + controller.abort() + await expect(done).to.eventually.be.rejected.and.have.property('name', 'AbortError') + await tick() + + // The query ends by itself before the poll that waits for the cursor fires: the connection is + // already back in the pool, so a destroy now would release it a second time, and tarn matches + // a release by identity — a connection it has since handed to another request would be freed + // under that request. + source.cursor = { state: 'done' } + source.emit('end') + await new Promise((resolve) => setTimeout(resolve, 30)) + + expect(state.released).to.equal(1) + expect(stream.destroyed).to.equal(false) + }) + it('is already aborted when handed an aborted signal, without touching an unattached query', async () => { const { stream, attach, state } = fakeKnexStream() const controller = new AbortController() From 835a65fc96d5ed5839c03e63b6ce233b61494d5f Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 28 Nov 2026 12:48:17 -0500 Subject: [PATCH 3/3] test(integration): a REQ abort storm leaves the pool empty The unit tests model knex's stream semantics; this is the property itself, against a real Postgres and a real pool: one client opens and closes 25 subscriptions, half with the CLOSE in the same tick and half a tick later, and then the master pool must report nothing in use and `pg_stat_activity` no backend left active. The integration stack leaves READ_REPLICA_ENABLED unset, so the repository's read client is the master client and that pool is what a REQ's read runs on. Proven able to fail before it was added: on unfixed `main` the same scenario reports `numUsed()` 2 against an expected 0, and its next step cannot get a connection at all. --- .../features/subscriptions/req-abort.feature | 13 ++++ .../subscriptions/req-abort.feature.ts | 63 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 test/integration/features/subscriptions/req-abort.feature create mode 100644 test/integration/features/subscriptions/req-abort.feature.ts diff --git a/test/integration/features/subscriptions/req-abort.feature b/test/integration/features/subscriptions/req-abort.feature new file mode 100644 index 000000000..6b0dcb166 --- /dev/null +++ b/test/integration/features/subscriptions/req-abort.feature @@ -0,0 +1,13 @@ +Feature: Aborting a subscription does not strand a database connection + + A REQ's stored-events read is a knex stream over a pg cursor, so ending it early (CLOSE, or a + socket that goes away mid-read) has to give its pooled connection back. When it did not, each + aborted read cost the worker a connection and the pool filled until every subscription hung + (#1243). Unit tests cover the wrapper's control flow against a fake of knex; this scenario is + the property itself, against a real pool. + + Scenario: Subscriptions closed before their stored events arrive + Given someone called Alice + When Alice opens and closes 25 subscriptions at once + Then no pooled database connection is in use + And no database backend is left active diff --git a/test/integration/features/subscriptions/req-abort.feature.ts b/test/integration/features/subscriptions/req-abort.feature.ts new file mode 100644 index 000000000..e41f9d98d --- /dev/null +++ b/test/integration/features/subscriptions/req-abort.feature.ts @@ -0,0 +1,63 @@ +import { Then, When, World } from '@cucumber/cucumber' +import { expect } from 'chai' +import { WebSocket } from 'ws' + +import { getMasterDbClient } from '../../../../src/database/client' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** + * The abort storm behind #1243: every aborted read used to cost the worker a pooled connection, + * and a pool of 2 (the integration stack's) is full after a couple of them. Aborts are spread + * across two positions — a CLOSE sent straight after the REQ, and one sent a tick later — because + * the connection was lost in different windows depending on how far the read had got. + */ +When( + /^(\w+) opens and closes (\d+) subscriptions at once$/, + async function (this: World>, name: string, count: string) { + const ws = this.parameters.clients[name] as WebSocket + const total = Number(count) + + for (let index = 0; index < total; index += 1) { + const subscription = `abort-${index}` + ws.send(JSON.stringify(['REQ', subscription, { kinds: [1] }])) + if (index % 2 === 0) { + ws.send(JSON.stringify(['CLOSE', subscription])) + } else { + await new Promise((resolve) => setImmediate(resolve)) + ws.send(JSON.stringify(['CLOSE', subscription])) + } + } + + // Give the aborted reads time to finish; a stranded connection stays stranded. + await sleep(250) + }, +) + +Then(/^no pooled database connection is in use$/, async function (this: World>) { + const dbClient = getMasterDbClient() + + // The integration stack leaves READ_REPLICA_ENABLED unset, so the repository's read client + // is this one and its pool is what a REQ's stored-events read runs on. A run that enables a + // replica has to assert on that pool as well. + const pool = (dbClient as any).client.pool + expect(pool.numUsed()).to.equal(0) + + // And the pool still works: a stranded connection showed up as a query that never answered. + const result: any = await dbClient.raw('SELECT 1 AS ok') + expect(result.rows[0].ok).to.equal(1) +}) + +Then(/^no database backend is left active$/, async function (this: World>) { + const dbClient = getMasterDbClient() + + const result: any = await dbClient.raw( + `SELECT count(*)::int AS active + FROM pg_stat_activity + WHERE datname = current_database() + AND pid <> pg_backend_pid() + AND state = 'active'`, + ) + + expect(result.rows[0].active).to.equal(0) +})