Skip to content

Commit 5f1ed2c

Browse files
committed
fix(node/http2): detect client disconnects before a body read
1 parent 3a5187e commit 5f1ed2c

3 files changed

Lines changed: 306 additions & 17 deletions

File tree

‎src/adapters/_node/request.ts‎

Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,30 @@ function erroredStream(error: unknown): ReadableStream {
4747
});
4848
}
4949

50+
/**
51+
* Whether the client hung up before the request body finished arriving.
52+
*
53+
* The two Node request types report this very differently, and neither one flag
54+
* covers both:
55+
*
56+
* - HTTP/1 `IncomingMessage` is `autoDestroy`, so `destroyed` on its own is *not*
57+
* a disconnect: a fully read body leaves a perfectly healthy request destroyed.
58+
* Only an errored stream, or one destroyed while `complete` is still false, is.
59+
* - HTTP/2 `Http2ServerRequest` is constructed with `autoDestroy: false` and never
60+
* destroys itself, so `destroyed` stays false; `complete` is *true* for an
61+
* aborted (truncated) body because its getter ORs in the abort flag; and its
62+
* `onStreamError` is deliberately a no-op, so `errored` stays null. Every
63+
* HTTP/1 condition above is therefore permanently false there.
64+
*
65+
* `aborted` is what closes the gap. Node's `closeStream()` raises it only when the
66+
* stream closed while the server's writable side was still open — the same "client
67+
* left before we finished responding" test the `res` close handler applies below,
68+
* so it cannot fire on a request that completed normally.
69+
*/
70+
function isClientGone(req: NodeServerRequest): boolean {
71+
return req.aborted || !!req.errored || (req.destroyed && !req.complete);
72+
}
73+
5074
export const NodeRequest: {
5175
new (nodeCtx: NodeRequestContext): ServerRequest;
5276
} = /* @__PURE__ */ (() => {
@@ -198,18 +222,20 @@ export const NodeRequest: {
198222
// destroyed on a perfectly healthy request, while the response is
199223
// still open (`writableEnded === false`) — replaying on that would
200224
// abort every handler that reads the body before touching `signal`.
201-
// Only an errored or *incomplete* request stream is a disconnect.
202-
if (res.destroyed || req.errored || (req.destroyed && !req.complete)) {
225+
// `isClientGone()` is the predicate that holds for both protocols.
226+
// (`res.destroyed` is HTTP/1-only; `Http2ServerResponse` has no such
227+
// property, which is why the request-side check has to carry HTTP/2.)
228+
if (res.destroyed || isClientGone(req)) {
203229
onClose();
204230
}
205231
} else {
206232
const onClose = () => {
207-
if (!req.complete) {
233+
if (!req.complete || req.aborted) {
208234
abort(); // client disconnected
209235
}
210236
};
211237
req.once("close", onClose);
212-
if (req.destroyed) {
238+
if (isClientGone(req)) {
213239
onClose();
214240
}
215241
}
@@ -238,11 +264,13 @@ export const NodeRequest: {
238264
// fresh `Readable.toWeb` would produce a stream whose `end` never fires).
239265
let stream: ReadableStream | null = null;
240266
if (this.#hasBody() && !this.#bodyUsed) {
241-
// TODO: HTTP2ServerRequest
242267
stream = Readable.toWeb(this.#req as NodeJS.ReadableStream) as unknown as ReadableStream;
243268
// `toWeb()` hands back an already-cancelled (and therefore disturbed)
244-
// stream when the source is destroyed — a client that hung up before
245-
// the handler read the body. Passing that to `new Request()` throws
269+
// stream when the source can no longer be read — a client that hung up
270+
// before the handler read the body. (HTTP/1 reaches that via
271+
// `isDestroyed()`; `Http2ServerRequest`, which never destroys itself,
272+
// via `!isReadable()` once the compat layer has pushed EOF on close.)
273+
// Passing that to `new Request()` throws
246274
// undici's "Response body object should not be disturbed or locked"
247275
// TypeError out of `_request`, which tells the handler nothing about
248276
// what happened. Serve a stream carrying the abort reason instead, so
@@ -303,22 +331,25 @@ export const NodeRequest: {
303331
if (signal.aborted) {
304332
return signal.reason;
305333
}
306-
// A destroyed-but-`complete` stream delivered its whole body and was then
307-
// auto-destroyed: it was consumed out of band (e.g. directly off
308-
// `runtime.node.req`), which is an unusable body rather than an abort.
309-
return (
310-
this.#req.errored ||
311-
(this.#req.destroyed && !this.#req.complete ? abortError() : bodyUnusable())
312-
);
334+
// A stream that ended without srvx reading it delivered its whole body and
335+
// was consumed out of band (e.g. directly off `runtime.node.req`), which is
336+
// an unusable body rather than an abort.
337+
return this.#req.errored || (isClientGone(this.#req) ? abortError() : bodyUnusable());
313338
}
314339

315340
// Buffer the raw request body once; consumers add their own single
316341
// continuation (`.toString()` / `JSON.parse`) so no extra promise or
317342
// microtask hop is introduced vs. inlining the read.
318343
#readBuffered() {
319-
// A destroyed source emits no further `data` / `end` / `error`, so
320-
// `readBody()` would wait forever on a body that can no longer arrive.
321-
if (this.#req.destroyed || this.#req.errored) {
344+
// A source that is already finished emits no further `data` / `end` /
345+
// `error`, so `readBody()` would wait forever on a body that can no longer
346+
// arrive. Beyond a disconnect that means a stream someone else consumed:
347+
// HTTP/1 leaves it `destroyed` (autoDestroy), while `Http2ServerRequest`
348+
// never destroys itself — on close the compat layer pushes EOF and dumps
349+
// whatever it buffered, leaving a live-looking stream with nothing left to
350+
// give, so `readableEnded` is what catches it. `#bodyError()` picks the
351+
// right rejection for each.
352+
if (isClientGone(this.#req) || this.#req.destroyed || this.#req.readableEnded) {
322353
return Promise.reject(this.#bodyError());
323354
}
324355
return readBody(this.#req, this.#maxRequestBodySize);
@@ -533,6 +564,16 @@ function readBody(req: NodeServerRequest, maxRequestBodySize?: number): Promise<
533564
};
534565
const onEnd = () => {
535566
cleanup();
567+
// HTTP/2 signals a client that hung up mid-body by pushing EOF onto the
568+
// request (`onStreamCloseRequest`), and it does so *before* the `close`
569+
// below — so `end` here can mean "that is the whole body" or "the rest of
570+
// the body will never arrive", and resolving blindly hands the handler a
571+
// silently truncated body it cannot tell from a complete one. The abort
572+
// flag is already set by then, so it separates the two.
573+
if (isClientGone(req)) {
574+
reject(req.errored || abortError());
575+
return;
576+
}
536577
// Single-chunk bodies (the common case) skip Buffer.concat's alloc+copy
537578
resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
538579
};

‎test/node-adapters.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { createServer } from "node:http";
22
import { Readable } from "node:stream";
33
import { connect, type AddressInfo } from "node:net";
4+
import http2 from "node:http2";
45
import { describe, expect, test, vi } from "vitest";
6+
import { getTLSCert } from "./_utils.ts";
57

68
import type { NodeHttp1Handler, NodeServerRequest, NodeServerResponse } from "../src/types.ts";
79
import {
@@ -21,6 +23,10 @@ import fastify from "fastify";
2123
// upstream stabilises. Tracked against the `tests_deno_node_adapters` CI job.
2224
const isDeno = !!(globalThis as any).Deno;
2325

26+
// HTTP/2 is not implemented in the Deno/Bun node-compat layers.
27+
// https://github.com/h3js/srvx/issues/237
28+
const skipHttp2 = isDeno || !!(globalThis as any).Bun;
29+
2430
const fetchCallers = [
2531
{
2632
name: "direct fetch",
@@ -770,6 +776,89 @@ describe("request signal", () => {
770776
expect(aborted).toBe(false);
771777
});
772778

779+
// The HTTP/2 half of the two guards above. `Http2ServerRequest` reports
780+
// `complete === true` for an *aborted* body and never destroys itself, so the
781+
// HTTP/1 disconnect conditions are inert there and the predicate has to lean on
782+
// `req.aborted` instead -- which must stay false for a request that finished
783+
// normally, or `fetch(upstream, { signal: request.signal })` breaks for every
784+
// handler that reads its body before touching `signal`.
785+
describe.skipIf(skipHttp2)("http2", () => {
786+
async function serveAndPost(fetchHandler: (request: any) => Promise<Response>) {
787+
const tls = await getTLSCert();
788+
const server = serve({
789+
hostname: "127.0.0.1",
790+
port: 0,
791+
silent: true,
792+
tls,
793+
node: { http2: true, allowHTTP1: false } as any,
794+
fetch: fetchHandler,
795+
});
796+
await server.ready();
797+
const client = http2.connect(server.url!, { ca: tls.ca, servername: "localhost" });
798+
client.on("error", () => {});
799+
try {
800+
const stream = client.request({ ":method": "POST", ":path": "/", "content-length": 9 });
801+
stream.end("test body");
802+
const chunks: Buffer[] = [];
803+
stream.on("data", (chunk: Buffer) => chunks.push(chunk));
804+
await new Promise((resolve, reject) => {
805+
stream.once("end", resolve);
806+
stream.once("error", reject);
807+
});
808+
return Buffer.concat(chunks).toString();
809+
} finally {
810+
client.destroy();
811+
await server.close(true);
812+
}
813+
}
814+
815+
test("should not abort when the signal is first read after the body", async () => {
816+
let aborted: boolean | undefined;
817+
let receivedBody: string | undefined;
818+
819+
const body = await serveAndPost(async (request) => {
820+
receivedBody = await request.text();
821+
aborted = request.signal.aborted;
822+
return new Response(`Received: ${receivedBody}`);
823+
});
824+
825+
expect(body).toBe("Received: test body");
826+
expect(receivedBody).toBe("test body");
827+
expect(aborted).toBe(false);
828+
});
829+
830+
test("should not abort when the signal is first read after a streamed body", async () => {
831+
let aborted: boolean | undefined;
832+
let receivedBody: string | undefined;
833+
834+
const body = await serveAndPost(async (request) => {
835+
receivedBody = await new Response(request.body).text();
836+
aborted = request.signal.aborted;
837+
return new Response("ok");
838+
});
839+
840+
expect(body).toBe("ok");
841+
expect(receivedBody).toBe("test body");
842+
expect(aborted).toBe(false);
843+
});
844+
845+
// Responding without reading closes the stream while the promised body is
846+
// still outstanding, which leaves `complete`/`readableEnded` true on an
847+
// untouched request -- neither can stand in for the disconnect check.
848+
test("should not abort when the body is never read", async () => {
849+
let aborted: boolean | undefined;
850+
851+
const body = await serveAndPost(async (request) => {
852+
await new Promise((resolve) => setTimeout(resolve, 20));
853+
aborted = request.signal.aborted;
854+
return new Response("ok");
855+
});
856+
857+
expect(body).toBe("ok");
858+
expect(aborted).toBe(false);
859+
});
860+
});
861+
773862
test("should fire abort signal when client disconnects", async () => {
774863
let abortFired: () => void;
775864
const abortFiredPromise = new Promise<void>((resolve) => {

0 commit comments

Comments
 (0)