|
1 | 1 | // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
2 | 2 |
|
| 3 | +import { connect, type Socket } from 'node:net'; |
| 4 | +import type { ServerResponse } from 'node:http'; |
3 | 5 | import { describe, it, expect } from 'vitest'; |
4 | 6 | import { HonoHttpServer } from './adapter'; |
5 | 7 |
|
6 | 8 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); |
7 | 9 |
|
| 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 | + |
8 | 53 | /** |
9 | 54 | * P1-3 regression: `close()` must DRAIN in-flight requests (let them finish) |
10 | 55 | * 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)', ( |
62 | 107 | expect(Date.now() - bodyEnded).toBeLessThan(1000); |
63 | 108 | }); |
64 | 109 |
|
| 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 | + |
65 | 213 | it('force-closes after the drain window so shutdown cannot hang', async () => { |
66 | 214 | const server = new HonoHttpServer(0, undefined, 100); // tiny drain window |
67 | 215 | server.getRawApp().get('/hang', async (c) => { |
|
0 commit comments