From 29b44119d7440fea496ce895d481ed599a8aa670 Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Sat, 24 Oct 2026 16:47:08 -0400 Subject: [PATCH] fix(download): release the backend read when the client leaves before storage answers A client can give up on /download while its storage read is still waiting, for example a GetObject queued behind a saturated socket pool. The body then arrives for a response that is already closed. `pipeline` rejects a closed destination with ERR_STREAM_UNABLE_TO_PIPE before it takes ownership of the source, and the route rethrew without destroying it, so the body pinned its backend socket and the Storage Reader Lease for the life of the process. Enough of them fill the pool and every storage call queues. Check the response before piping and destroy the body if the client is gone, and destroy it on every error exit of the pipe as well. #282 and #291 already cover a client leaving mid-body. tests/download-client-gone.test.ts holds the storage read until the client has hung up, then checks that the backend socket and the reader lease are released; on Node 26.12.1 the socket stayed held before this change. Signed-off-by: Rui Chen --- routes/download/[locationId].ts | 20 +++- tests/download-client-gone.test.ts | 158 +++++++++++++++++++++++++++++ 2 files changed, 175 insertions(+), 3 deletions(-) create mode 100644 tests/download-client-gone.test.ts diff --git a/routes/download/[locationId].ts b/routes/download/[locationId].ts index c31513c..5454060 100644 --- a/routes/download/[locationId].ts +++ b/routes/download/[locationId].ts @@ -77,16 +77,30 @@ export default defineEventHandler(async (event) => { // `sendStream` neither waits for `drain` nor notices client aborts; `pipeline` does both // and destroys the source, which releases its reader lease. `_handled` is an h3 v1 internal. event._handled = true + // The client can hang up while storage is still answering (a read queued behind + // a full socket pool). `pipeline` refuses an already-closed destination with + // ERR_STREAM_UNABLE_TO_PIPE without taking ownership of the source, so release + // the backend read here instead of leaving its socket and reader lease pinned. + const { res } = event.node + if (res.destroyed || res.closed) { + download.stream.destroy() + logger.debug(`Client aborted /download/${locationId} before storage answered`) + return + } try { - await pipeline(download.stream, event.node.res) + await pipeline(download.stream, res) } catch (err) { + // Every exit that did not finish the pipe must release the backend read: an + // unread body pins its storage connection and the reader lease it carries. + download.stream.destroy() + const { code } = err as NodeJS.ErrnoException // Client went away mid-body. Expected on cancelled jobs and parallel runners. - if ((err as NodeJS.ErrnoException).code === 'ERR_STREAM_PREMATURE_CLOSE') { + if (code === 'ERR_STREAM_PREMATURE_CLOSE' || code === 'ERR_STREAM_UNABLE_TO_PIPE') { logger.debug(`Client aborted /download/${locationId}: ${(err as Error).message}`) return } // Headers are out, so Nitro's error handler would crash with ERR_HTTP_HEADERS_SENT. - if (event.node.res.headersSent) { + if (res.headersSent) { logger.error(`Download stream failed for ${locationId}`, { error: err }) return } diff --git a/tests/download-client-gone.test.ts b/tests/download-client-gone.test.ts new file mode 100644 index 0000000..90d8aeb --- /dev/null +++ b/tests/download-client-gone.test.ts @@ -0,0 +1,158 @@ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { AddressInfo } from 'node:net' +import { Buffer } from 'node:buffer' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import http from 'node:http' +import { Readable } from 'node:stream' + +import * as h3 from 'h3' +import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' +import { getStorage } from '~/lib/storage' + +/** + * A stand-in for the object store: answers every GET with an unending body, so + * a response only gives its socket back by being read to the end or destroyed. + */ +async function startOrigin() { + const server = http.createServer((_req, res) => { + res.writeHead(200, { 'content-type': 'application/octet-stream' }) + const chunk = Buffer.alloc(64 * 1024) + const pump = () => { + while (!res.destroyed && res.write(chunk)); + } + res.on('drain', pump) + pump() + }) + server.listen(0) + await once(server, 'listening') + const { port } = server.address() as AddressInfo + return { + url: `http://localhost:${port}`, + close: async () => { + server.closeAllConnections() + server.close() + await once(server, 'close') + }, + } +} + +// The real route on an in-process h3 app, as in proxy-backpressure.test.ts, so +// the storage it calls and the sockets it holds are observable here. +const router = h3.createRouter({ preemptive: true }) +const server = http.createServer(h3.toNodeListener(h3.createApp().use(router))) + +beforeAll(async () => { + for (const [name, value] of Object.entries(h3)) vi.stubGlobal(name, value) + // Not a static import: the route calls Nitro auto-imports at evaluation time, + // so it can only load after the stubs above. + const { default: download } = await import('~/routes/download/[locationId]') + router.get('/download/:locationId', download) + server.listen(0) + await once(server, 'listening') +}) + +afterEach(() => { + vi.restoreAllMocks() + server.closeAllConnections() +}) + +afterAll(async () => { + vi.unstubAllGlobals() + server.close() + await once(server, 'close') +}) + +async function createMergedEntry() { + const storage = await getStorage() + const db = await getDatabase() + const key = `client-gone-${randomUUID()}` + const entry = { key, version: 'v1', scope: 'refs/heads/main', repoId: '123' } + const upload = await storage.createUpload(entry) + await storage.uploadPart(upload.id, 0, Readable.from('payload')) + await storage.completeUpload(entry) + const { locationId } = await db + .selectFrom('cache_entries') + .where('key', '=', key) + .select('locationId') + .executeTakeFirstOrThrow() + // Merged, so download() goes straight to one read of the merged object. + await db + .updateTable('storage_locations') + .set({ mergedAt: Date.now() }) + .where('id', '=', locationId) + .execute() + return locationId +} + +/** + * A client can give up on /download while the storage read is still waiting + * for a socket in a saturated pool. The body then arrives for a response that + * is already closed, and `pipeline` rejects a closed destination + * (ERR_STREAM_UNABLE_TO_PIPE) before it takes ownership of the source. Unless + * the route destroys it, the body pins its backend socket and reader lease for + * the life of the process. + */ +describe('download for a client that left before storage answered', () => { + test('releases the backend socket and the reader lease', async () => { + const origin = await startOrigin() + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }) + const storage = await getStorage() + const db = await getDatabase() + const locationId = await createMergedEntry() + + const { promise: clientGone, resolve: markClientGone } = Promise.withResolvers() + const { promise: adapterSettled, resolve: markAdapterSettled } = Promise.withResolvers() + let body: IncomingMessage | undefined + vi.spyOn(storage.adapter, 'createDownloadStream').mockImplementation(async () => { + try { + await clientGone + const req = http.get(origin.url, { agent }) + const [res] = (await once(req, 'response')) as [IncomingMessage] + body = res + return { stream: res } + } finally { + markAdapterSettled() + } + }) + + try { + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${locationId}`) + req.on('error', () => {}) + const [, serverRes] = await serverSide + req.destroy() + await once(serverRes, 'close') + markClientGone() + await adapterSettled + + expect(body).toBeDefined() + await vi.waitFor( + () => { + expect( + Object.values(agent.sockets).flat(), + 'sockets held for the gone client', + ).toHaveLength(0) + expect(body!.destroyed, 'backend body destroyed').toBe(true) + }, + { timeout: 5000, interval: 25 }, + ) + await vi.waitFor( + async () => { + const leases = await db + .selectFrom('storage_reader_leases') + .where('storageLocationId', '=', locationId) + .select('id') + .execute() + expect(leases, 'reader leases left behind').toHaveLength(0) + }, + { timeout: 5000, interval: 25 }, + ) + } finally { + agent.destroy() + await origin.close() + } + }, 20_000) +})