From f87856c6c82624ff72442ca5b947d4f8466766a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 14:37:27 +0000 Subject: [PATCH 1/4] fix(plugin-hono-server): close each in-flight connection when its response ends during a drain close() released idle keep-alive sockets only at the start of the drain, so a connection whose request was still running became an idle keep-alive socket afterwards and server.close() waited for the client to drop it (3 s for fetch, 4 s for the node:http(s) agent). During a drain a response whose headers are not yet written now goes out with Connection: close, and one that already sent keep-alive headers releases its socket through closeIdleConnections() once it ends. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2ebbZkr2QAEG1x7UC8 --- .../30920-hono-drain-closes-connections.md | 10 ++++ .../src/adapter-drain.test.ts | 32 +++++++++++ .../plugins/plugin-hono-server/src/adapter.ts | 56 ++++++++++++++++++- 3 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 .changeset/30920-hono-drain-closes-connections.md diff --git a/.changeset/30920-hono-drain-closes-connections.md b/.changeset/30920-hono-drain-closes-connections.md new file mode 100644 index 00000000000..7cfc4f1e255 --- /dev/null +++ b/.changeset/30920-hono-drain-closes-connections.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-hono-server': patch +--- + +fix(plugin-hono-server): a graceful `close()` now finishes when the last in-flight request ends, not a keep-alive window later + +Clause-②: no +Metadata-protocol: none + +`HonoHttpServer.close()` released idle keep-alive sockets only once, at the start of the drain. A connection whose request was still running at that moment became an idle keep-alive socket after its response ended, and `close()` then waited for the client to drop it: about 3 s with `fetch` and 4 s with the `node:http` / `node:https` agent, or the server's own keep-alive timeout. During a drain, a response that has not written its headers yet now goes out with `Connection: close`, and a response that had already sent keep-alive headers releases its connection as soon as it ends. In-flight requests still complete and are never cut short, and the drain window still force-closes whatever outlasts it. diff --git a/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts b/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts index 1bae90b70cc..c7b6e6845c0 100644 --- a/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts +++ b/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts @@ -27,9 +27,41 @@ describe('HonoHttpServer — graceful close drains in-flight requests (P1-3)', ( const res = await reqP; expect(res.status).toBe(200); expect(await res.text()).toBe('drained-ok'); // completed, not reset + // Written after the drain began, so it closes its connection rather than + // leaving an idle keep-alive socket for `close()` to wait out. + expect(res.headers.get('connection')).toBe('close'); await closeP; }); + it('a response whose keep-alive headers went out before close() releases its connection when it ends', async () => { + // The arm `Connection: close` cannot reach: the headers are already on the + // wire. Before the fix `close()` resolved only when the client dropped the + // idle socket — about 3 s later for `fetch`, its keep-alive margin under + // the server's `timeout=5` hint. + const server = new HonoHttpServer(0, undefined, 5000); + server.getRawApp().get('/stream', (c) => c.body(new ReadableStream({ + async start(controller) { + controller.enqueue(new TextEncoder().encode('head-')); + await sleep(200); // still streaming when close() is called + controller.enqueue(new TextEncoder().encode('tail')); + controller.close(); + }, + }))); + await server.listen(0); + const port = server.getPort(); + + const res = await fetch(`http://127.0.0.1:${port}/stream`); + expect(res.headers.get('connection')).toBe('keep-alive'); // sent before the drain + const closeP = server.close(); + + expect(await res.text()).toBe('head-tail'); // completed, not reset + const bodyEnded = Date.now(); + await closeP; + // 1000 ms is a third of the defect's 3 s wait and far above the few + // milliseconds the release takes, so neither load nor a slow box decides it. + expect(Date.now() - bodyEnded).toBeLessThan(1000); + }); + it('force-closes after the drain window so shutdown cannot hang', async () => { const server = new HonoHttpServer(0, undefined, 100); // tiny drain window server.getRawApp().get('/hang', async (c) => { diff --git a/packages/plugins/plugin-hono-server/src/adapter.ts b/packages/plugins/plugin-hono-server/src/adapter.ts index 69a105b36c2..76b35dbe4a2 100644 --- a/packages/plugins/plugin-hono-server/src/adapter.ts +++ b/packages/plugins/plugin-hono-server/src/adapter.ts @@ -32,6 +32,7 @@ import { serveStatic } from '@hono/node-server/serve-static'; // — so terminating TLS needs no bridging code here: the same `fetch` handler, // the same drain, one different server factory. See {@link HttpsListenerMaterial}. import { createServer as createHttpsServer } from 'node:https'; +import type { IncomingMessage, ServerResponse } from 'node:http'; import { matchesRoutePattern } from './route-pattern'; import { readRequestBody, type RequestBodyReading, type RequestBodyRefusal } from './request-body'; // The ADR-0112 wire vocabulary, read as DATA rather than restated: `ErrorCode` @@ -577,6 +578,14 @@ export class HonoHttpServer implements IHttpServer { private app: Hono; private server: any; private listeningPort: number | undefined; + /** + * Set while {@link close} drains. Every response written from then on + * closes its connection when it ends instead of keeping it alive — see + * {@link trackForDrain}. + */ + private draining = false; + /** Responses the listener is still writing, so {@link close} can reach the in-flight ones. */ + private inFlightResponses = new Set(); /** * Every `(method, pattern)` pair registered through this server, kept so * the `notFound` handler can answer "the path exists but the method is @@ -1831,12 +1840,49 @@ export class HonoHttpServer implements IHttpServer { resolve(); }); this.server = server; + // Prepended so it runs before the Hono listener can write a + // synchronous response's headers. + server.prependListener('request', (_req: IncomingMessage, res: ServerResponse) => { + this.trackForDrain(server, res); + }); server.on('error', (err: any) => { reject(err); }); }); } + /** + * Keep the drain in {@link close} from waiting on a connection that has + * nothing left to send. + * + * `closeIdleConnections()` at the start of a drain cannot release a + * connection whose request is still running, and Node never runs it again. + * Left alone, that connection outlives its response as an idle keep-alive + * socket, and `server.close()` waits until the CLIENT drops it — measured + * at 3 s for `fetch` and 4 s for the `node:http(s)` agent, the server's + * `Keep-Alive: timeout=5` hint less each client's margin — or until the + * server's own keep-alive timer fires. So during a drain: + * + * - a response whose headers are not yet written goes out with + * `Connection: close`, and Node ends the socket once it is sent. The + * client is told, so it never reuses a socket that is about to close; + * - a response that had already written its keep-alive headers when the + * drain began releases its socket through `closeIdleConnections()` once + * it has ended. That call skips any socket still writing a response. + * + * Neither arm cuts a response short: both act only once it has ended. + */ + private trackForDrain(server: any, res: ServerResponse) { + if (this.draining) res.shouldKeepAlive = false; + this.inFlightResponses.add(res); + const socket = res.socket; + res.once('close', () => { + this.inFlightResponses.delete(res); + if (!this.draining || !socket || socket.destroyed || socket.writableEnded) return; + if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections(); + }); + } + getPort() { return this.listeningPort || this.port; } @@ -1853,7 +1899,13 @@ export class HonoHttpServer implements IHttpServer { // requests finish rather than force-killing them mid-response. // `closeIdleConnections()` releases idle keep-alive sockets so the process // can exit promptly; active requests keep running until they complete or - // the drain window elapses. + // the drain window elapses, and each one's connection closes as soon as + // its response ends (`trackForDrain`), so the drain finishes with the + // last in-flight request rather than a keep-alive window after it. + this.draining = true; + for (const res of this.inFlightResponses) { + if (!res.headersSent) res.shouldKeepAlive = false; + } await new Promise((resolve) => { let settled = false; const finish = () => { if (!settled) { settled = true; resolve(); } }; @@ -1875,5 +1927,7 @@ export class HonoHttpServer implements IHttpServer { if (typeof timer.unref === 'function') timer.unref(); }); this.server = undefined; + this.draining = false; + this.inFlightResponses.clear(); } } From 1f14604b4f3d44a5a1d4b59b079f0f13ff440f6f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 15:36:31 +0000 Subject: [PATCH 2/4] test: cut or budget the Test Core cases that sit near the 5 s default - metadata-protocol: the purity case derives once and compares it with the module-load singleton instead of deriving twice. - client: the shared auth server and its better-auth instance are built at module scope, out of the first case's clock. - driver-sql, plugin-security, plugin-sharing, cli census: an explicit per-case budget of 3x the slowest Test Core reading, rounded up to the next second, with the readings and the arithmetic beside it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2ebbZkr2QAEG1x7UC8 --- ...released-port-production-spawn.pin.test.ts | 18 +++++++++++++++- .../src/auth-rotated-session-token.test.ts | 10 +++++++-- .../src/logger-receiver-detach.test.ts | 19 ++++++++++++++++- .../src/reference-sites.derivation.test.ts | 8 +++++-- ...-admin-assignment-boundary.posture.test.ts | 21 ++++++++++++++++++- .../src/share-link-password.test.ts | 11 +++++++++- 6 files changed, 79 insertions(+), 8 deletions(-) diff --git a/packages/cli/test/released-port-production-spawn.pin.test.ts b/packages/cli/test/released-port-production-spawn.pin.test.ts index 76bdbfb716c..954bc7031e9 100644 --- a/packages/cli/test/released-port-production-spawn.pin.test.ts +++ b/packages/cli/test/released-port-production-spawn.pin.test.ts @@ -338,6 +338,22 @@ describe('#24295 / #24342: no file that spawns the CLI draws a released port', ( } }); + /** + * An explicit budget, sized to the measured work. The case reads and parses + * every `.ts` file under `test/` (`liveTree()`). Reaching the whole live + * tree is what the case claims, so the walk is not cut. The case is + * synchronous, so vitest judges it after the body returns. + * + * Readings: the slowest `Test Core` reading is 2629 ms (`main` push and merge + * group runs, 2026-11-03..06, n=6); local idle, 1102-1291 ms. + * + * The rule is 3x the slowest reading, rounded up to the next second (the rule + * and why 3x: plugin-sharing's `share-link-password-webcontainer.test.ts`): + * 3 x 2629 = 7887, so the budget is 8000. If `test/` grows much, re-measure + * and re-size. + */ + const LIVE_TREE_BUDGET_MS = 8_000; + it('the census reaches the live tree: every way of spawning the CLI, and the draw, are found', () => { const tree = liveTree(); const population = cliSpawners(tree); @@ -359,7 +375,7 @@ describe('#24295 / #24342: no file that spawns the CLI draws a released port', ( const instrument = tree.get('serve-port-bind-probe.test.ts'); expect(instrument?.drawLines.length ?? 0, 'the draw census finds no draw in the bind-probe instrument').toBeGreaterThan(0); expect(instrument?.spawnsCli).toBe(false); - }); + }, LIVE_TREE_BUDGET_MS); it('every file that spawns the CLI draws exactly what its ledger entry allows — zero without one', () => { const offenders: string[] = []; diff --git a/packages/client/src/auth-rotated-session-token.test.ts b/packages/client/src/auth-rotated-session-token.test.ts index 640fe6d0e4b..01b1ccd917e 100644 --- a/packages/client/src/auth-rotated-session-token.test.ts +++ b/packages/client/src/auth-rotated-session-token.test.ts @@ -214,8 +214,10 @@ const arrangeServer = async () => { }; /** - * [#23181] The file's ONE server, built by the first case that signs in and - * shared by every later one. Each case still signs a user of its own up on it, + * [#23181] The file's ONE server, shared by every case. It is built at module + * scope right after the warm-up (below), so no case's clock carries its + * engine, schema sync and better-auth instance: before, the first case to + * sign in built it inside its own window. Each case still signs a user of its own up on it, * through a client of its own, and every assertion here is about that user's * credential: a rotation revokes only the rotating user's sessions, and a * case reads its own user by address. So no case reads another case's writes, @@ -357,6 +359,10 @@ const closeEngines = async (): Promise => { // and `④` below pins that. await signedIn(); await closeEngines(); +// The cases' shared server, built here for the same reason: it is +// arrangement, not behaviour, and the first case used to pay it. Its +// better-auth instance is built on first use, so that is asked for here too. +await (await fileServer()).manager.getAuthInstance(); beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}); diff --git a/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts b/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts index 82355619676..146b0803502 100644 --- a/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts +++ b/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts @@ -512,6 +512,23 @@ describe('[#12792] ③ no detach-then-call shape survives in sql-driver.ts', () expect(SCANNED.length).toBeGreaterThan(1); }); + /** + * An explicit budget, sized to the measured work. The case parses every + * module in SCANNED with the TypeScript compiler and walks each tree twice + * (37 files, about 1.5 MB of source, at this commit). That work is the claim, + * so it is not cut. The case is synchronous, so vitest judges it after the + * body returns. + * + * Readings: the slowest `Test Core` reading is 2499 ms (`main` push and merge + * group runs, 2026-11-03..06, n=2); local idle, 442 and 469 ms. + * + * The rule is 3x the slowest reading, rounded up to the next second (the rule + * and why 3x: plugin-sharing's `share-link-password-webcontainer.test.ts`): + * 3 x 2499 = 7497, so the budget is 8000. If the split adds modules, + * re-measure and re-size. + */ + const SCAN_BUDGET_MS = 8_000; + it('sql-driver.ts and the modules split out of it contain none of them', () => { const found = SCANNED.flatMap((name) => scan(readFileSync(new URL(`./${name}`, import.meta.url), 'utf8'), name).map( @@ -519,5 +536,5 @@ describe('[#12792] ③ no detach-then-call shape survives in sql-driver.ts', () ), ); expect(found, 'every log call must go through a property access so the receiver stays bound').toEqual([]); - }); + }, SCAN_BUDGET_MS); }); diff --git a/packages/metadata-protocol/src/reference-sites.derivation.test.ts b/packages/metadata-protocol/src/reference-sites.derivation.test.ts index 6674a36dbba..4d1e7e93971 100644 --- a/packages/metadata-protocol/src/reference-sites.derivation.test.ts +++ b/packages/metadata-protocol/src/reference-sites.derivation.test.ts @@ -226,13 +226,17 @@ describe('[#9190] derived reference sites — derivation is a pure function of t // The module-load singleton must not be doing anything a caller cannot // reproduce; a derived registry that depends on WHEN it ran is a // curated one wearing a function. + // + // The two derivations are the module-load singleton and one call made + // now, at a different time and in a different state of the process. + // A third call would only repeat the second at the cost of another + // full schema walk, so the case derives once. const a = deriveReferenceSites(); - const b = deriveReferenceSites(); + expect(a).not.toBe(REFERENCE_SITES); // a second derivation, not the singleton handed back const flatten = (index: ReturnType) => [...index.byTarget.entries()] .map(([target, sites]) => `${target}=${sites.map((s) => `${s.fromType}.${s.property}`).join(',')}`) .sort(); - expect(flatten(a)).toEqual(flatten(b)); expect(flatten(a)).toEqual(flatten(REFERENCE_SITES)); expect([...a.compositeKeyByTarget]).toEqual([...REFERENCE_SITES.compositeKeyByTarget]); }); diff --git a/packages/plugins/plugin-security/src/org-admin-assignment-boundary.posture.test.ts b/packages/plugins/plugin-security/src/org-admin-assignment-boundary.posture.test.ts index 2f3ca240d9c..f1458b77504 100644 --- a/packages/plugins/plugin-security/src/org-admin-assignment-boundary.posture.test.ts +++ b/packages/plugins/plugin-security/src/org-admin-assignment-boundary.posture.test.ts @@ -743,6 +743,25 @@ describe('[ADR-0090 D12; ruling of record 6649064874] an administrator\'s refuse row: { user_id: 'u_in_2', permission_set: 'admin_full_access' } }, ] as const; + /** + * An explicit budget, sized to the measured work. Each posture boots a fresh + * real engine and SecurityPlugin. It then seeds four hidden-column rows and + * sends each an update and a delete from two delegates, rewrites one, and + * sends the organization branch six removals over two tables, reading the + * stored row back after each verdict. Every write is part of what the case + * claims, so none is cut. + * + * Readings: the slowest `Test Core` reading across the three postures is + * 2949 ms (`main` push and merge group runs, 2026-11-03..06, n=3 per + * posture); local idle, 624-694 ms. + * + * The rule is 3x the slowest reading, rounded up to the next second (the rule + * and why 3x: plugin-sharing's `share-link-password-webcontainer.test.ts`): + * 3 x 2949 = 8847, so the budget is 9000. If the rows or the postures grow, + * re-measure and re-size. + */ + const HIDDEN_COLUMN_BUDGET_MS = 9_000; + for (const posture of POSTURES) { it(`posture '${posture}': a column the caller's field rules hide is never named in the refusal, and a delegate is still judged on its stored value; an administrator who reads it is told the value`, async () => { const h = await boot(posture); @@ -800,7 +819,7 @@ describe('[ADR-0090 D12; ruling of record 6649064874] an administrator\'s refuse expect(admitted, `${table}, inside the boundary: ${admitted.message}`).toEqual({ status: 200 }); expect(await stored(h, table, { id: inId }), `${table}: the removal landed`).toHaveLength(0); } - }); + }, HIDDEN_COLUMN_BUDGET_MS); } it("a partially masked column is never named either — neither its masked nor its stored value — and the delegate is still judged on the stored value", async () => { diff --git a/packages/plugins/plugin-sharing/src/share-link-password.test.ts b/packages/plugins/plugin-sharing/src/share-link-password.test.ts index 294377712d6..95193208c3b 100644 --- a/packages/plugins/plugin-sharing/src/share-link-password.test.ts +++ b/packages/plugins/plugin-sharing/src/share-link-password.test.ts @@ -504,6 +504,15 @@ describe.concurrent('[#21839] the legacy upgrade', () => { expect(await storedHash(engine, link.id), 'no write on a refused redemption').toBe(legacyHash); }); + // [#30920] An explicit budget, sized to the measured work. Each of the two + // redemptions re-hashes the legacy password under a fresh salt before the + // write is refused, so the case pays two native scrypt derivations the memo + // cannot answer, beside the cases running concurrently with it. The second + // redemption is the one "reported once" is judged on, so neither is cut. + // Its slowest `Test Core` reading was 2605 ms (`main` push and merge group + // runs, 2026-11-03..06, n=4); local idle, 458-689 ms. 3x the slowest reading, + // rounded up to the next second (the rule and why 3x are in + // share-link-password-webcontainer.test.ts): 3 x 2605 = 7815, so 8000. it('a refused upgrade write does not block the read, leaves the legacy form verifying, and is reported once without the password', async () => { const { engine, service, logger } = await boot({ refuseHashWrites: true }); const link = await service.createLink({ object: 'pin_doc', recordId: 'doc_1' }, CREATOR); @@ -519,7 +528,7 @@ describe.concurrent('[#21839] the legacy upgrade', () => { expect(reports[0]![1]).toMatchObject({ link: link.id, reason: 'STORAGE_REFUSED' }); expect(loggedText(logger)).not.toContain(PASSWORD); expect(loggedText(logger)).not.toContain(legacyHash.split('$')[2]); - }); + }, 8_000); it('is not attempted when the deployment injects its own hasher pair', async () => { const { engine, service } = await boot({ From e0d0358b3fd94ecd3faedc613f68df1a4c8515fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 17:02:11 +0000 Subject: [PATCH 3/4] fix(plugin-hono-server): release only the ending response's own connection, and track drain state per connection The round-1 drain called the server-wide closeIdleConnections() whenever a keep-alive response ended. Node treats a response as done once it has called end(), before its bytes are flushed, so that sweep destroyed any other connection whose response was ended but still flushing. The ending response now destroySoon()s its own socket, once it has finished and no other response on that connection is pending. The tracked responses are now keyed by connection and dropped when the connection closes: a response pipelined behind another never gets a socket if the connection dies, never emits 'close', and was held until close(). Pins: a slow reader's 32 MiB body arrives whole while another stream ends during the drain; pipelined responses on a destroyed connection are forgotten; a request whose headers finish after close() began is answered Connection: close. The driver-sql budget comment states the rule's over-half threshold and why a reading 1 ms under it takes a budget. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2ebbZkr2QAEG1x7UC8 --- .../30920-hono-drain-closes-connections.md | 2 +- .../src/logger-receiver-detach.test.ts | 11 +- .../src/adapter-drain.test.ts | 148 ++++++++++++++++++ .../plugins/plugin-hono-server/src/adapter.ts | 61 ++++++-- 4 files changed, 201 insertions(+), 21 deletions(-) diff --git a/.changeset/30920-hono-drain-closes-connections.md b/.changeset/30920-hono-drain-closes-connections.md index 7cfc4f1e255..a9d2a98bb33 100644 --- a/.changeset/30920-hono-drain-closes-connections.md +++ b/.changeset/30920-hono-drain-closes-connections.md @@ -7,4 +7,4 @@ fix(plugin-hono-server): a graceful `close()` now finishes when the last in-flig Clause-②: no Metadata-protocol: none -`HonoHttpServer.close()` released idle keep-alive sockets only once, at the start of the drain. A connection whose request was still running at that moment became an idle keep-alive socket after its response ended, and `close()` then waited for the client to drop it: about 3 s with `fetch` and 4 s with the `node:http` / `node:https` agent, or the server's own keep-alive timeout. During a drain, a response that has not written its headers yet now goes out with `Connection: close`, and a response that had already sent keep-alive headers releases its connection as soon as it ends. In-flight requests still complete and are never cut short, and the drain window still force-closes whatever outlasts it. +`HonoHttpServer.close()` released idle keep-alive sockets only once, at the start of the drain. A connection whose request was still running at that moment became an idle keep-alive socket after its response ended, and `close()` then waited for the client to drop it: about 3 s with `fetch` and 4 s with the `node:http` / `node:https` agent, or the server's own keep-alive timeout. During a drain, a response that has not written its headers yet now goes out with `Connection: close`, and a response that had already sent keep-alive headers closes its own connection once every byte of it has been flushed. Other connections are not touched when one response ends. The drain window still force-closes whatever outlasts it. diff --git a/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts b/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts index 146b0803502..d196c2a17a4 100644 --- a/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts +++ b/packages/drivers/driver-sql/src/logger-receiver-detach.test.ts @@ -522,10 +522,13 @@ describe('[#12792] ③ no detach-then-call shape survives in sql-driver.ts', () * Readings: the slowest `Test Core` reading is 2499 ms (`main` push and merge * group runs, 2026-11-03..06, n=2); local idle, 442 and 469 ms. * - * The rule is 3x the slowest reading, rounded up to the next second (the rule - * and why 3x: plugin-sharing's `share-link-password-webcontainer.test.ts`): - * 3 x 2499 = 7497, so the budget is 8000. If the split adds modules, - * re-measure and re-size. + * The rule (plugin-sharing's `share-link-password-webcontainer.test.ts`): + * a case whose slowest reading is over half the default gets 3x that + * reading, rounded up to the next second. 2499 ms is 1 ms under that line, + * and it takes the budget anyway: the default leaves it 2.0x, barely above + * the 1.88x spread between two CI runs that the rule's 3x was sized on, from + * only two readings. 3 x 2499 = 7497, so the budget is 8000. If the split + * adds modules, re-measure and re-size. */ const SCAN_BUDGET_MS = 8_000; diff --git a/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts b/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts index c7b6e6845c0..88e4ab64577 100644 --- a/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts +++ b/packages/plugins/plugin-hono-server/src/adapter-drain.test.ts @@ -1,10 +1,55 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +import { connect, type Socket } from 'node:net'; +import type { ServerResponse } from 'node:http'; import { describe, it, expect } from 'vitest'; import { HonoHttpServer } from './adapter'; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +/** + * A raw HTTP/1.1 connection: what it writes is exactly what the server parses, + * so a test can split one request's headers across a `close()`, pipeline + * several requests in one write, or stop reading a response part-way. + */ +async function rawConnection(port: number) { + const socket: Socket = connect(port, '127.0.0.1'); + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('error', reject); + }); + const chunks: Buffer[] = []; + socket.on('data', (chunk: Buffer) => chunks.push(chunk)); + socket.on('error', () => { /* a destroyed connection is part of some cases */ }); + const ended = new Promise((resolve) => socket.once('close', () => resolve())); + return { + socket, + ended, + received: () => Buffer.concat(chunks), + }; +} + +/** The head of the first response in `bytes`, its header map, and the body bytes after it. */ +function splitResponse(bytes: Buffer) { + const at = bytes.indexOf('\r\n\r\n'); + if (at < 0) return { head: '', headers: {} as Record, body: Buffer.alloc(0) }; + const head = bytes.subarray(0, at).toString('latin1'); + const headers: Record = {}; + for (const line of head.split('\r\n').slice(1)) { + const colon = line.indexOf(':'); + headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim(); + } + return { head, headers, body: bytes.subarray(at + 4) }; +} + +/** Every response the adapter is still holding for its drain bookkeeping. */ +function retainedResponses(server: HonoHttpServer): number { + const tracked = (server as unknown as { inFlightResponses: Map> }).inFlightResponses; + let n = 0; + for (const pending of tracked.values()) n += pending.size; + return n; +} + /** * P1-3 regression: `close()` must DRAIN in-flight requests (let them finish) * rather than force-killing them, and must force-close only after the drain @@ -62,6 +107,109 @@ describe('HonoHttpServer — graceful close drains in-flight requests (P1-3)', ( expect(Date.now() - bodyEnded).toBeLessThan(1000); }); + it('a request whose headers finish arriving after close() began is answered Connection: close', async () => { + // A connection mid-headers when the drain starts is active, so + // `closeIdleConnections()` leaves it alone, and its response is created + // only after `close()` has run its loop over the in-flight ones. The + // request-time branch is what keeps that response from going out + // keep-alive. + const server = new HonoHttpServer(0, undefined, 5000); + server.getRawApp().get('/probe', (c) => c.text('late-arrival')); + await server.listen(0); + const conn = await rawConnection(server.getPort()); + + conn.socket.write('GET /probe HTTP/1.1\r\nHost: 127.0.0.1\r\n'); + await sleep(50); // the first half has been read: the connection is active + const closeP = server.close(); + await sleep(20); + conn.socket.write('Accept: */*\r\n\r\n'); + + await conn.ended; // the server ended the connection after the response + const { head, headers, body } = splitResponse(conn.received()); + expect(head).toMatch(/^HTTP\/1\.1 200/); + expect(body.toString('utf8')).toBe('late-arrival'); + expect(headers.connection).toBe('close'); + await closeP; + }); + + it('a stream ending during the drain does not cut short another connection\'s response that is still flushing', async () => { + // Connection B's response calls `end()` during the drain with a body larger + // than the socket buffers, to a client that is not reading, so it is ended + // but still flushing. Connection A's stream, whose keep-alive headers went + // out before `close()`, then ends. Releasing A's connection must not touch + // B's: Node counts a response as done once it has called `end()`, before + // its bytes are flushed, so a server-wide `closeIdleConnections()` at that + // moment destroys B mid-body. + const BIG = new Uint8Array(32 * 1024 * 1024).fill(0x61); + let bigResponse: ServerResponse | undefined; + let releaseBig: () => void = () => {}; + const bigReleased = new Promise((resolve) => { releaseBig = resolve; }); + const server = new HonoHttpServer(0, undefined, 10_000); + server.getRawApp().get('/big', async (c) => { + bigResponse = (c.env as { outgoing: ServerResponse }).outgoing; + await bigReleased; // in flight, not ended, when the drain starts + return c.body(BIG); + }); + server.getRawApp().get('/stream', (c) => c.body(new ReadableStream({ + async start(controller) { + controller.enqueue(new TextEncoder().encode('head-')); + await sleep(200); + controller.enqueue(new TextEncoder().encode('tail')); + controller.close(); + }, + }))); + await server.listen(0); + const port = server.getPort(); + + const slowReader = await rawConnection(port); + slowReader.socket.pause(); // reads nothing until resumed below + slowReader.socket.write('GET /big HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n'); + const stream = await fetch(`http://127.0.0.1:${port}/stream`); + expect(stream.headers.get('connection')).toBe('keep-alive'); // sent before the drain + + const closeP = server.close(); + releaseBig(); + await sleep(50); + // The premise: B's response has called end() and is still flushing. + expect(bigResponse?.writableEnded, 'the big response has called end()').toBe(true); + expect(bigResponse?.writableFinished, 'the big response is still flushing').toBe(false); + + expect(await stream.text()).toBe('head-tail'); // A ends during the drain + await sleep(50); + slowReader.socket.resume(); + await slowReader.ended; + const { head, headers, body } = splitResponse(slowReader.received()); + expect(head).toMatch(/^HTTP\/1\.1 200/); + expect(Number(headers['content-length'])).toBe(BIG.length); + expect(body.length, 'every byte of the body arrived').toBe(BIG.length); + await closeP; + }); + + it('forgets a pipelined response whose connection died before it was written', async () => { + // Pipelined requests queue behind the first one's response; the queued + // responses have no socket of their own, so if the connection dies they + // never emit 'close'. The drain bookkeeping must still let them go, or + // any client can grow the server's memory by pipelining and hanging up. + const server = new HonoHttpServer(0, undefined, 5000); + server.getRawApp().get('/slow', async (c) => { + await sleep(150); + return c.text('first'); + }); + server.getRawApp().get('/probe', (c) => c.text('queued')); + await server.listen(0); + const conn = await rawConnection(server.getPort()); + + const get = (path: string) => `GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`; + conn.socket.write(get('/slow') + get('/probe') + get('/probe') + get('/probe')); + await sleep(60); + expect(retainedResponses(server), 'all four responses are tracked while their connection lives').toBe(4); + + conn.socket.destroy(); + await sleep(300); // past the first response's 150 ms, and the server has seen the connection close + expect(retainedResponses(server)).toBe(0); + await server.close(); + }); + it('force-closes after the drain window so shutdown cannot hang', async () => { const server = new HonoHttpServer(0, undefined, 100); // tiny drain window server.getRawApp().get('/hang', async (c) => { diff --git a/packages/plugins/plugin-hono-server/src/adapter.ts b/packages/plugins/plugin-hono-server/src/adapter.ts index 76b35dbe4a2..3af27a4ad63 100644 --- a/packages/plugins/plugin-hono-server/src/adapter.ts +++ b/packages/plugins/plugin-hono-server/src/adapter.ts @@ -33,6 +33,7 @@ import { serveStatic } from '@hono/node-server/serve-static'; // the same drain, one different server factory. See {@link HttpsListenerMaterial}. import { createServer as createHttpsServer } from 'node:https'; import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Socket } from 'node:net'; import { matchesRoutePattern } from './route-pattern'; import { readRequestBody, type RequestBodyReading, type RequestBodyRefusal } from './request-body'; // The ADR-0112 wire vocabulary, read as DATA rather than restated: `ErrorCode` @@ -584,8 +585,13 @@ export class HonoHttpServer implements IHttpServer { * {@link trackForDrain}. */ private draining = false; - /** Responses the listener is still writing, so {@link close} can reach the in-flight ones. */ - private inFlightResponses = new Set(); + /** + * The responses each open connection still owes, so {@link close} can reach + * the in-flight ones. Keyed by connection and dropped when the connection + * closes, so a response that will never be written (one pipelined behind + * another on a connection that died) is not held past its connection. + */ + private inFlightResponses = new Map>(); /** * Every `(method, pattern)` pair registered through this server, kept so * the `notFound` handler can answer "the path exists but the method is @@ -1842,8 +1848,8 @@ export class HonoHttpServer implements IHttpServer { this.server = server; // Prepended so it runs before the Hono listener can write a // synchronous response's headers. - server.prependListener('request', (_req: IncomingMessage, res: ServerResponse) => { - this.trackForDrain(server, res); + server.prependListener('request', (req: IncomingMessage, res: ServerResponse) => { + this.trackForDrain(req, res); }); server.on('error', (err: any) => { reject(err); @@ -1867,19 +1873,40 @@ export class HonoHttpServer implements IHttpServer { * `Connection: close`, and Node ends the socket once it is sent. The * client is told, so it never reuses a socket that is about to close; * - a response that had already written its keep-alive headers when the - * drain began releases its socket through `closeIdleConnections()` once - * it has ended. That call skips any socket still writing a response. - * - * Neither arm cuts a response short: both act only once it has ended. + * drain began ends its OWN connection once it has finished — every byte + * handed to the socket — and no other response on that connection is + * pending. `destroySoon()` flushes what is queued before it closes. + * + * ⛔ Never the server-wide `closeIdleConnections()` from here: Node counts + * a response as done once it has called `end()`, before its bytes are + * flushed, so a sweep when one response ends destroys any other connection + * whose response is ended but still flushing to a slow reader. + * + * A connection's entry is dropped when the connection closes, not only + * when each response does: a response pipelined behind another never gets + * a socket if the connection dies first, and never emits `'close'`. */ - private trackForDrain(server: any, res: ServerResponse) { + private trackForDrain(req: IncomingMessage, res: ServerResponse) { if (this.draining) res.shouldKeepAlive = false; - this.inFlightResponses.add(res); - const socket = res.socket; + // `req.socket`, not `res.socket`: a pipelined response waiting its turn + // has no socket yet. + const socket = req.socket; + let pending = this.inFlightResponses.get(socket); + if (!pending) { + const owed = new Set(); + pending = owed; + this.inFlightResponses.set(socket, owed); + socket.once('close', () => { + if (this.inFlightResponses.get(socket) === owed) this.inFlightResponses.delete(socket); + }); + } + const owed = pending; + owed.add(res); res.once('close', () => { - this.inFlightResponses.delete(res); - if (!this.draining || !socket || socket.destroyed || socket.writableEnded) return; - if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections(); + owed.delete(res); + if (!this.draining || owed.size > 0 || !res.writableFinished) return; + if (socket.destroyed || socket.writableEnded) return; + socket.destroySoon(); }); } @@ -1903,8 +1930,10 @@ export class HonoHttpServer implements IHttpServer { // its response ends (`trackForDrain`), so the drain finishes with the // last in-flight request rather than a keep-alive window after it. this.draining = true; - for (const res of this.inFlightResponses) { - if (!res.headersSent) res.shouldKeepAlive = false; + for (const owed of this.inFlightResponses.values()) { + for (const res of owed) { + if (!res.headersSent) res.shouldKeepAlive = false; + } } await new Promise((resolve) => { let settled = false; From 586338ffbdd25e1fa9c86965dcfa3534e8993ad0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 17:16:35 +0000 Subject: [PATCH 4/4] refactor(plugin-hono-server): name the per-connection response set so the tenant-audit census can place its receiver Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2ebbZkr2QAEG1x7UC8 --- .../plugins/plugin-hono-server/src/adapter.ts | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-hono-server/src/adapter.ts b/packages/plugins/plugin-hono-server/src/adapter.ts index 3af27a4ad63..152bbe58b1d 100644 --- a/packages/plugins/plugin-hono-server/src/adapter.ts +++ b/packages/plugins/plugin-hono-server/src/adapter.ts @@ -34,6 +34,9 @@ import { serveStatic } from '@hono/node-server/serve-static'; import { createServer as createHttpsServer } from 'node:https'; import type { IncomingMessage, ServerResponse } from 'node:http'; import type { Socket } from 'node:net'; + +/** The responses one open connection still owes, for the drain in {@link HonoHttpServer.close}. */ +type OwedResponses = Set; import { matchesRoutePattern } from './route-pattern'; import { readRequestBody, type RequestBodyReading, type RequestBodyRefusal } from './request-body'; // The ADR-0112 wire vocabulary, read as DATA rather than restated: `ErrorCode` @@ -591,7 +594,7 @@ export class HonoHttpServer implements IHttpServer { * closes, so a response that will never be written (one pipelined behind * another on a connection that died) is not held past its connection. */ - private inFlightResponses = new Map>(); + private inFlightResponses = new Map(); /** * Every `(method, pattern)` pair registered through this server, kept so * the `notFound` handler can answer "the path exists but the method is @@ -1891,16 +1894,7 @@ export class HonoHttpServer implements IHttpServer { // `req.socket`, not `res.socket`: a pipelined response waiting its turn // has no socket yet. const socket = req.socket; - let pending = this.inFlightResponses.get(socket); - if (!pending) { - const owed = new Set(); - pending = owed; - this.inFlightResponses.set(socket, owed); - socket.once('close', () => { - if (this.inFlightResponses.get(socket) === owed) this.inFlightResponses.delete(socket); - }); - } - const owed = pending; + const owed: OwedResponses = this.responsesOwedOn(socket); owed.add(res); res.once('close', () => { owed.delete(res); @@ -1910,6 +1904,18 @@ export class HonoHttpServer implements IHttpServer { }); } + /** The {@link inFlightResponses} entry for one connection, made on its first request and dropped when it closes. */ + private responsesOwedOn(socket: Socket): OwedResponses { + const known: OwedResponses | undefined = this.inFlightResponses.get(socket); + if (known) return known; + const created: OwedResponses = new Set(); + this.inFlightResponses.set(socket, created); + socket.once('close', () => { + if (this.inFlightResponses.get(socket) === created) this.inFlightResponses.delete(socket); + }); + return created; + } + getPort() { return this.listeningPort || this.port; }