Skip to content

Commit e0d0358

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2ebbZkr2QAEG1x7UC8
1 parent 2ff6bb0 commit e0d0358

4 files changed

Lines changed: 201 additions & 21 deletions

File tree

‎.changeset/30920-hono-drain-closes-connections.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@ fix(plugin-hono-server): a graceful `close()` now finishes when the last in-flig
77
Clause-②: no
88
Metadata-protocol: none
99

10-
`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.
10+
`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.

‎packages/drivers/driver-sql/src/logger-receiver-detach.test.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -522,10 +522,13 @@ describe('[#12792] ③ no detach-then-call shape survives in sql-driver.ts', ()
522522
* Readings: the slowest `Test Core` reading is 2499 ms (`main` push and merge
523523
* group runs, 2026-11-03..06, n=2); local idle, 442 and 469 ms.
524524
*
525-
* The rule is 3x the slowest reading, rounded up to the next second (the rule
526-
* and why 3x: plugin-sharing's `share-link-password-webcontainer.test.ts`):
527-
* 3 x 2499 = 7497, so the budget is 8000. If the split adds modules,
528-
* re-measure and re-size.
525+
* The rule (plugin-sharing's `share-link-password-webcontainer.test.ts`):
526+
* a case whose slowest reading is over half the default gets 3x that
527+
* reading, rounded up to the next second. 2499 ms is 1 ms under that line,
528+
* and it takes the budget anyway: the default leaves it 2.0x, barely above
529+
* the 1.88x spread between two CI runs that the rule's 3x was sized on, from
530+
* only two readings. 3 x 2499 = 7497, so the budget is 8000. If the split
531+
* adds modules, re-measure and re-size.
529532
*/
530533
const SCAN_BUDGET_MS = 8_000;
531534

‎packages/plugins/plugin-hono-server/src/adapter-drain.test.ts‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,55 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

3+
import { connect, type Socket } from 'node:net';
4+
import type { ServerResponse } from 'node:http';
35
import { describe, it, expect } from 'vitest';
46
import { HonoHttpServer } from './adapter';
57

68
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
79

10+
/**
11+
* A raw HTTP/1.1 connection: what it writes is exactly what the server parses,
12+
* so a test can split one request's headers across a `close()`, pipeline
13+
* several requests in one write, or stop reading a response part-way.
14+
*/
15+
async function rawConnection(port: number) {
16+
const socket: Socket = connect(port, '127.0.0.1');
17+
await new Promise<void>((resolve, reject) => {
18+
socket.once('connect', resolve);
19+
socket.once('error', reject);
20+
});
21+
const chunks: Buffer[] = [];
22+
socket.on('data', (chunk: Buffer) => chunks.push(chunk));
23+
socket.on('error', () => { /* a destroyed connection is part of some cases */ });
24+
const ended = new Promise<void>((resolve) => socket.once('close', () => resolve()));
25+
return {
26+
socket,
27+
ended,
28+
received: () => Buffer.concat(chunks),
29+
};
30+
}
31+
32+
/** The head of the first response in `bytes`, its header map, and the body bytes after it. */
33+
function splitResponse(bytes: Buffer) {
34+
const at = bytes.indexOf('\r\n\r\n');
35+
if (at < 0) return { head: '', headers: {} as Record<string, string>, body: Buffer.alloc(0) };
36+
const head = bytes.subarray(0, at).toString('latin1');
37+
const headers: Record<string, string> = {};
38+
for (const line of head.split('\r\n').slice(1)) {
39+
const colon = line.indexOf(':');
40+
headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
41+
}
42+
return { head, headers, body: bytes.subarray(at + 4) };
43+
}
44+
45+
/** Every response the adapter is still holding for its drain bookkeeping. */
46+
function retainedResponses(server: HonoHttpServer): number {
47+
const tracked = (server as unknown as { inFlightResponses: Map<unknown, Set<unknown>> }).inFlightResponses;
48+
let n = 0;
49+
for (const pending of tracked.values()) n += pending.size;
50+
return n;
51+
}
52+
853
/**
954
* P1-3 regression: `close()` must DRAIN in-flight requests (let them finish)
1055
* 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)', (
62107
expect(Date.now() - bodyEnded).toBeLessThan(1000);
63108
});
64109

110+
it('a request whose headers finish arriving after close() began is answered Connection: close', async () => {
111+
// A connection mid-headers when the drain starts is active, so
112+
// `closeIdleConnections()` leaves it alone, and its response is created
113+
// only after `close()` has run its loop over the in-flight ones. The
114+
// request-time branch is what keeps that response from going out
115+
// keep-alive.
116+
const server = new HonoHttpServer(0, undefined, 5000);
117+
server.getRawApp().get('/probe', (c) => c.text('late-arrival'));
118+
await server.listen(0);
119+
const conn = await rawConnection(server.getPort());
120+
121+
conn.socket.write('GET /probe HTTP/1.1\r\nHost: 127.0.0.1\r\n');
122+
await sleep(50); // the first half has been read: the connection is active
123+
const closeP = server.close();
124+
await sleep(20);
125+
conn.socket.write('Accept: */*\r\n\r\n');
126+
127+
await conn.ended; // the server ended the connection after the response
128+
const { head, headers, body } = splitResponse(conn.received());
129+
expect(head).toMatch(/^HTTP\/1\.1 200/);
130+
expect(body.toString('utf8')).toBe('late-arrival');
131+
expect(headers.connection).toBe('close');
132+
await closeP;
133+
});
134+
135+
it('a stream ending during the drain does not cut short another connection\'s response that is still flushing', async () => {
136+
// Connection B's response calls `end()` during the drain with a body larger
137+
// than the socket buffers, to a client that is not reading, so it is ended
138+
// but still flushing. Connection A's stream, whose keep-alive headers went
139+
// out before `close()`, then ends. Releasing A's connection must not touch
140+
// B's: Node counts a response as done once it has called `end()`, before
141+
// its bytes are flushed, so a server-wide `closeIdleConnections()` at that
142+
// moment destroys B mid-body.
143+
const BIG = new Uint8Array(32 * 1024 * 1024).fill(0x61);
144+
let bigResponse: ServerResponse | undefined;
145+
let releaseBig: () => void = () => {};
146+
const bigReleased = new Promise<void>((resolve) => { releaseBig = resolve; });
147+
const server = new HonoHttpServer(0, undefined, 10_000);
148+
server.getRawApp().get('/big', async (c) => {
149+
bigResponse = (c.env as { outgoing: ServerResponse }).outgoing;
150+
await bigReleased; // in flight, not ended, when the drain starts
151+
return c.body(BIG);
152+
});
153+
server.getRawApp().get('/stream', (c) => c.body(new ReadableStream({
154+
async start(controller) {
155+
controller.enqueue(new TextEncoder().encode('head-'));
156+
await sleep(200);
157+
controller.enqueue(new TextEncoder().encode('tail'));
158+
controller.close();
159+
},
160+
})));
161+
await server.listen(0);
162+
const port = server.getPort();
163+
164+
const slowReader = await rawConnection(port);
165+
slowReader.socket.pause(); // reads nothing until resumed below
166+
slowReader.socket.write('GET /big HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n');
167+
const stream = await fetch(`http://127.0.0.1:${port}/stream`);
168+
expect(stream.headers.get('connection')).toBe('keep-alive'); // sent before the drain
169+
170+
const closeP = server.close();
171+
releaseBig();
172+
await sleep(50);
173+
// The premise: B's response has called end() and is still flushing.
174+
expect(bigResponse?.writableEnded, 'the big response has called end()').toBe(true);
175+
expect(bigResponse?.writableFinished, 'the big response is still flushing').toBe(false);
176+
177+
expect(await stream.text()).toBe('head-tail'); // A ends during the drain
178+
await sleep(50);
179+
slowReader.socket.resume();
180+
await slowReader.ended;
181+
const { head, headers, body } = splitResponse(slowReader.received());
182+
expect(head).toMatch(/^HTTP\/1\.1 200/);
183+
expect(Number(headers['content-length'])).toBe(BIG.length);
184+
expect(body.length, 'every byte of the body arrived').toBe(BIG.length);
185+
await closeP;
186+
});
187+
188+
it('forgets a pipelined response whose connection died before it was written', async () => {
189+
// Pipelined requests queue behind the first one's response; the queued
190+
// responses have no socket of their own, so if the connection dies they
191+
// never emit 'close'. The drain bookkeeping must still let them go, or
192+
// any client can grow the server's memory by pipelining and hanging up.
193+
const server = new HonoHttpServer(0, undefined, 5000);
194+
server.getRawApp().get('/slow', async (c) => {
195+
await sleep(150);
196+
return c.text('first');
197+
});
198+
server.getRawApp().get('/probe', (c) => c.text('queued'));
199+
await server.listen(0);
200+
const conn = await rawConnection(server.getPort());
201+
202+
const get = (path: string) => `GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`;
203+
conn.socket.write(get('/slow') + get('/probe') + get('/probe') + get('/probe'));
204+
await sleep(60);
205+
expect(retainedResponses(server), 'all four responses are tracked while their connection lives').toBe(4);
206+
207+
conn.socket.destroy();
208+
await sleep(300); // past the first response's 150 ms, and the server has seen the connection close
209+
expect(retainedResponses(server)).toBe(0);
210+
await server.close();
211+
});
212+
65213
it('force-closes after the drain window so shutdown cannot hang', async () => {
66214
const server = new HonoHttpServer(0, undefined, 100); // tiny drain window
67215
server.getRawApp().get('/hang', async (c) => {

‎packages/plugins/plugin-hono-server/src/adapter.ts‎

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { serveStatic } from '@hono/node-server/serve-static';
3333
// the same drain, one different server factory. See {@link HttpsListenerMaterial}.
3434
import { createServer as createHttpsServer } from 'node:https';
3535
import type { IncomingMessage, ServerResponse } from 'node:http';
36+
import type { Socket } from 'node:net';
3637
import { matchesRoutePattern } from './route-pattern';
3738
import { readRequestBody, type RequestBodyReading, type RequestBodyRefusal } from './request-body';
3839
// The ADR-0112 wire vocabulary, read as DATA rather than restated: `ErrorCode`
@@ -584,8 +585,13 @@ export class HonoHttpServer implements IHttpServer {
584585
* {@link trackForDrain}.
585586
*/
586587
private draining = false;
587-
/** Responses the listener is still writing, so {@link close} can reach the in-flight ones. */
588-
private inFlightResponses = new Set<ServerResponse>();
588+
/**
589+
* The responses each open connection still owes, so {@link close} can reach
590+
* the in-flight ones. Keyed by connection and dropped when the connection
591+
* closes, so a response that will never be written (one pipelined behind
592+
* another on a connection that died) is not held past its connection.
593+
*/
594+
private inFlightResponses = new Map<Socket, Set<ServerResponse>>();
589595
/**
590596
* Every `(method, pattern)` pair registered through this server, kept so
591597
* the `notFound` handler can answer "the path exists but the method is
@@ -1842,8 +1848,8 @@ export class HonoHttpServer implements IHttpServer {
18421848
this.server = server;
18431849
// Prepended so it runs before the Hono listener can write a
18441850
// synchronous response's headers.
1845-
server.prependListener('request', (_req: IncomingMessage, res: ServerResponse) => {
1846-
this.trackForDrain(server, res);
1851+
server.prependListener('request', (req: IncomingMessage, res: ServerResponse) => {
1852+
this.trackForDrain(req, res);
18471853
});
18481854
server.on('error', (err: any) => {
18491855
reject(err);
@@ -1867,19 +1873,40 @@ export class HonoHttpServer implements IHttpServer {
18671873
* `Connection: close`, and Node ends the socket once it is sent. The
18681874
* client is told, so it never reuses a socket that is about to close;
18691875
* - a response that had already written its keep-alive headers when the
1870-
* drain began releases its socket through `closeIdleConnections()` once
1871-
* it has ended. That call skips any socket still writing a response.
1872-
*
1873-
* Neither arm cuts a response short: both act only once it has ended.
1876+
* drain began ends its OWN connection once it has finished — every byte
1877+
* handed to the socket — and no other response on that connection is
1878+
* pending. `destroySoon()` flushes what is queued before it closes.
1879+
*
1880+
* ⛔ Never the server-wide `closeIdleConnections()` from here: Node counts
1881+
* a response as done once it has called `end()`, before its bytes are
1882+
* flushed, so a sweep when one response ends destroys any other connection
1883+
* whose response is ended but still flushing to a slow reader.
1884+
*
1885+
* A connection's entry is dropped when the connection closes, not only
1886+
* when each response does: a response pipelined behind another never gets
1887+
* a socket if the connection dies first, and never emits `'close'`.
18741888
*/
1875-
private trackForDrain(server: any, res: ServerResponse) {
1889+
private trackForDrain(req: IncomingMessage, res: ServerResponse) {
18761890
if (this.draining) res.shouldKeepAlive = false;
1877-
this.inFlightResponses.add(res);
1878-
const socket = res.socket;
1891+
// `req.socket`, not `res.socket`: a pipelined response waiting its turn
1892+
// has no socket yet.
1893+
const socket = req.socket;
1894+
let pending = this.inFlightResponses.get(socket);
1895+
if (!pending) {
1896+
const owed = new Set<ServerResponse>();
1897+
pending = owed;
1898+
this.inFlightResponses.set(socket, owed);
1899+
socket.once('close', () => {
1900+
if (this.inFlightResponses.get(socket) === owed) this.inFlightResponses.delete(socket);
1901+
});
1902+
}
1903+
const owed = pending;
1904+
owed.add(res);
18791905
res.once('close', () => {
1880-
this.inFlightResponses.delete(res);
1881-
if (!this.draining || !socket || socket.destroyed || socket.writableEnded) return;
1882-
if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections();
1906+
owed.delete(res);
1907+
if (!this.draining || owed.size > 0 || !res.writableFinished) return;
1908+
if (socket.destroyed || socket.writableEnded) return;
1909+
socket.destroySoon();
18831910
});
18841911
}
18851912

@@ -1903,8 +1930,10 @@ export class HonoHttpServer implements IHttpServer {
19031930
// its response ends (`trackForDrain`), so the drain finishes with the
19041931
// last in-flight request rather than a keep-alive window after it.
19051932
this.draining = true;
1906-
for (const res of this.inFlightResponses) {
1907-
if (!res.headersSent) res.shouldKeepAlive = false;
1933+
for (const owed of this.inFlightResponses.values()) {
1934+
for (const res of owed) {
1935+
if (!res.headersSent) res.shouldKeepAlive = false;
1936+
}
19081937
}
19091938
await new Promise<void>((resolve) => {
19101939
let settled = false;

0 commit comments

Comments
 (0)