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
7 changes: 7 additions & 0 deletions .changeset/req-cursor-release-on-abort.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 6 additions & 3 deletions src/handlers/subscribe-message-handler.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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(
Expand All @@ -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)
}
Expand Down
103 changes: 103 additions & 0 deletions src/utils/query-stream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
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
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, () => {
// 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) {
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)
}
13 changes: 13 additions & 0 deletions test/integration/features/subscriptions/req-abort.feature
Original file line number Diff line number Diff line change
@@ -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
63 changes: 63 additions & 0 deletions test/integration/features/subscriptions/req-abort.feature.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, any>>, 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<Record<string, any>>) {
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<Record<string, any>>) {
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)
})
55 changes: 37 additions & 18 deletions test/unit/handlers/subscribe-message-handler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
})

Expand Down
Loading
Loading