From 3188bbc87d1c4eb07e49206057f6c80f02038ad3 Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Sat, 24 Oct 2026 16:43:36 -0400 Subject: [PATCH] fix(download): close downloads whose client stopped reading Node's HTTP server has no idle timeout for a response in progress and the download route set none. A client that stays connected but stops reading parks the pipe forever: the backend read keeps its storage socket, the Storage Reader Lease keeps renewing, and on the first restore of an unmerged entry the Merge it paces never finishes and keeps its Merge Lease. Each such client permanently removes one socket from the storage pool. Destroy the download when no bytes have moved for DOWNLOAD_IDLE_TIMEOUT_MS (default 300000, 0 disables). The timer is refreshed on every chunk, so slow but progressing clients are unaffected. It covers whole and Range responses and the first restore of an unmerged entry, whose Merge keeps going after the client's side of the tee is closed. tests/proxy-backpressure.test.ts parks a client after the first chunk of a 200, a 206 and an unmerged first restore, and checks that the storage read is released, the response closed, and the Merge completed. Signed-off-by: Rui Chen --- README.md | 8 +++ lib/schemas.ts | 1 + routes/download/[locationId].ts | 27 +++++++- tests/proxy-backpressure.test.ts | 110 +++++++++++++++++++++++++++++++ tests/setup.ts | 1 + 5 files changed, 146 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 90307017..9f6ee6d1 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,14 @@ volumes: cache-data: ``` +## Resource limits + +All optional. + +| Variable | Default | Effect | +| -------------------------- | -------- | ------------------------------------------------------------------------------- | +| `DOWNLOAD_IDLE_TIMEOUT_MS` | `300000` | Closes a download whose client has not read a byte for this long; `0` disables. | + ## Documentation 👉 👈 diff --git a/lib/schemas.ts b/lib/schemas.ts index bbae5f53..0fd3457d 100644 --- a/lib/schemas.ts +++ b/lib/schemas.ts @@ -84,6 +84,7 @@ export const envBaseSchema = type({ 'DEBUG?': 'unknown', 'ENABLE_DIRECT_DOWNLOADS': 'boolean = false', 'EAGER_MERGE': 'boolean = false', + 'DOWNLOAD_IDLE_TIMEOUT_MS': 'number.integer >= 0 = 300000', 'BENCHMARK': 'boolean = false', 'SKIP_TOKEN_VALIDATION': 'boolean = false', 'MANAGEMENT_API_KEY?': 'string', diff --git a/routes/download/[locationId].ts b/routes/download/[locationId].ts index c31513c5..a9d4335d 100644 --- a/routes/download/[locationId].ts +++ b/routes/download/[locationId].ts @@ -1,6 +1,7 @@ import type { RangeRequest } from '~/lib/storage' import { pipeline } from 'node:stream/promises' import { z } from 'zod' +import { env } from '~/lib/env' import { logger } from '~/lib/logger' import { getStorage, RangeNotSatisfiableError } from '~/lib/storage' @@ -77,11 +78,33 @@ 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 HTTP server has no idle timeout, so a client that stops reading but keeps + // the connection open would hold the backend read, its reader lease and, on a + // first restore, the Merge it paces forever. Bytes moving at any rate keep the + // download alive. + let idleTimer: NodeJS.Timeout | undefined + if (env.DOWNLOAD_IDLE_TIMEOUT_MS > 0) { + const body = download.stream + idleTimer = setTimeout(() => { + body.destroy( + Object.assign(new Error(`No bytes sent for ${env.DOWNLOAD_IDLE_TIMEOUT_MS} ms`), { + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }), + ) + }, env.DOWNLOAD_IDLE_TIMEOUT_MS) + idleTimer.unref() + body.on('data', () => idleTimer?.refresh()) + } try { await pipeline(download.stream, event.node.res) } catch (err) { + const { code } = err as NodeJS.ErrnoException + if (code === 'ERR_DOWNLOAD_IDLE_TIMEOUT') { + logger.warn(`Download /download/${locationId} closed: ${(err as Error).message}`) + return + } // 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') { logger.debug(`Client aborted /download/${locationId}: ${(err as Error).message}`) return } @@ -91,5 +114,7 @@ export default defineEventHandler(async (event) => { return } throw err + } finally { + clearTimeout(idleTimer) } }) diff --git a/tests/proxy-backpressure.test.ts b/tests/proxy-backpressure.test.ts index 9a7ff4fa..72cff490 100644 --- a/tests/proxy-backpressure.test.ts +++ b/tests/proxy-backpressure.test.ts @@ -9,6 +9,8 @@ import { setTimeout as sleep } from 'node:timers/promises' import * as h3 from 'h3' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' +import { env } from '~/lib/env' import { getStorage } from '~/lib/storage' const MiB = 1024 * 1024 @@ -167,4 +169,112 @@ describe('proxy routes apply backpressure', () => { await vi.waitFor(() => expect(source.destroyed).toBe(true), { timeout: 5000, interval: 50 }) }, 20_000) + + describe('download idle timeout', () => { + const originalIdleTimeout = env.DOWNLOAD_IDLE_TIMEOUT_MS + beforeAll(() => { + env.DOWNLOAD_IDLE_TIMEOUT_MS = 500 + }) + afterAll(() => { + env.DOWNLOAD_IDLE_TIMEOUT_MS = originalIdleTimeout + }) + + test.each([ + { response: 'a whole entry', status: 200, range: undefined }, + { response: 'a Range', status: 206, range: { start: 0, end: ENTRY_BYTES - 1 } }, + ])( + 'releases the storage read of a client that stopped reading $response', + async ({ status, range }) => { + // Real timers and sockets on purpose: the stall comes from TCP flow control, + // which fake timers cannot drive. + let pulled = 0 + function* entry() { + while (pulled < ENTRY_BYTES) { + pulled += CHUNK_BYTES + yield Buffer.alloc(CHUNK_BYTES) + } + } + const source = Readable.from(entry(), { objectMode: false, highWaterMark: CHUNK_BYTES }) + const storage = await getStorage() + vi.spyOn(storage, 'download').mockResolvedValue({ + stream: source, + size: ENTRY_BYTES, + range, + }) + + const { port } = server.address() as AddressInfo + const serverSide = once(server, 'request') as Promise<[IncomingMessage, ServerResponse]> + const req = http.get(`http://localhost:${port}/download/${randomUUID()}`, { + headers: range ? { range: `bytes=${range.start}-${range.end}` } : {}, + }) + req.on('error', () => undefined) + const [res] = (await once(req, 'response')) as [IncomingMessage] + expect(res.statusCode).toBe(status) + res.once('data', () => res.pause()) // stops reading, keeps the connection open + const [, serverRes] = await serverSide + const serverClosed = once(serverRes, 'close') + + // Without an idle timeout neither ever happens: the pipe just stays parked. + await expect(once(source, 'close')).rejects.toMatchObject({ + code: 'ERR_DOWNLOAD_IDLE_TIMEOUT', + }) + await serverClosed + expect(pulled).toBeLessThan(ENTRY_BYTES) + req.destroy() + }, + 20_000, + ) + + test('a stalled first restore is closed and its Merge still completes', async () => { + const storage = await getStorage() + const db = await getDatabase() + const reservation = { + key: `idle-unmerged-${randomUUID()}`, + version: 'v1', + scope: 'refs/heads/main', + repoId: '123', + } + const upload = await storage.createUpload(reservation) + // Far more than loopback socket buffers hold, so the stalled client really blocks the tee. + for (let i = 0; i < 4; i++) + await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(8 * MiB, i)])) + await storage.completeUpload(reservation) + const { locationId } = await db + .selectFrom('cache_entries') + .where('key', '=', reservation.key) + .select('locationId') + .executeTakeFirstOrThrow() + + 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', () => undefined) + const [res] = (await once(req, 'response')) as [IncomingMessage] + expect(res.statusCode).toBe(200) + res.once('data', () => res.pause()) + const [, serverRes] = await serverSide + await once(serverRes, 'close') + req.destroy() + + // The pump keeps feeding the merge once the client's side of the tee is gone. + await storage.waitForOngoingMerges() + const location = await db + .selectFrom('storage_locations') + .where('id', '=', locationId) + .select('mergedAt') + .executeTakeFirstOrThrow() + expect(location.mergedAt).not.toBeNull() + 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: 50 }, + ) + }, 30_000) + }) }) diff --git a/tests/setup.ts b/tests/setup.ts index 5ca471ec..abf55e74 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -44,6 +44,7 @@ const TESTING_ENV_BASE = { | 'ORPHANED_STORAGE_GRACE_PERIOD_HOURS' | 'ENABLE_DIRECT_DOWNLOADS' | 'EAGER_MERGE' + | 'DOWNLOAD_IDLE_TIMEOUT_MS' | 'BENCHMARK' | 'SKIP_TOKEN_VALIDATION' | 'ACTIONS_TOKEN_ISSUER'