Skip to content

Commit 3a5187e

Browse files
committed
fix(node): reject body reads with the abort reason after a client disconnect
resolves #293
1 parent d946356 commit 3a5187e

3 files changed

Lines changed: 302 additions & 10 deletions

File tree

‎src/adapters/_node/request.ts‎

Lines changed: 91 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,24 @@ function bodyUnusable(): TypeError {
2929
return new TypeError("Body is unusable: Body has already been read");
3030
}
3131

32+
/**
33+
* Rejection for a body that can no longer be read because the client hung up
34+
* without the socket surfacing an error of its own. Shaped like the reason an
35+
* `AbortController` produces so handlers can branch on `err.name === "AbortError"`.
36+
*/
37+
function abortError(): DOMException {
38+
return new DOMException("The request was aborted.", "AbortError");
39+
}
40+
41+
/** A `ReadableStream` that errors immediately with `error`, without producing any bytes. */
42+
function erroredStream(error: unknown): ReadableStream {
43+
return new ReadableStream({
44+
start(controller) {
45+
controller.error(error);
46+
},
47+
});
48+
}
49+
3250
export const NodeRequest: {
3351
new (nodeCtx: NodeRequestContext): ServerRequest;
3452
} = /* @__PURE__ */ (() => {
@@ -160,21 +178,40 @@ export const NodeRequest: {
160178
const { req, res } = this.runtime!.node!;
161179
const abortController = this.#abortController;
162180
const abort = (err?: Error) => abortController.abort?.(err);
181+
// The controller is created lazily, so `close` may already have fired
182+
// before this listener existed (a handler that only touches `signal`
183+
// after awaiting, or not at all until a body read fails). Replaying the
184+
// handler against the current state is what keeps `signal.aborted` from
185+
// reporting `false` for a client that is long gone.
163186
if (res) {
164-
res.once("close", () => {
187+
const onClose = () => {
165188
const reqError = req.errored;
166189
if (reqError) {
167190
abort(reqError); // request error
168191
} else if (!res.writableEnded) {
169192
abort(); // server closed before finishing response
170193
}
171-
});
194+
};
195+
res.once("close", onClose);
196+
// `req.destroyed` alone does *not* mean the client hung up:
197+
// `IncomingMessage` is `autoDestroy`, so a fully read body leaves it
198+
// destroyed on a perfectly healthy request, while the response is
199+
// still open (`writableEnded === false`) — replaying on that would
200+
// 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)) {
203+
onClose();
204+
}
172205
} else {
173-
req.once("close", () => {
206+
const onClose = () => {
174207
if (!req.complete) {
175208
abort(); // client disconnected
176209
}
177-
});
210+
};
211+
req.once("close", onClose);
212+
if (req.destroyed) {
213+
onClose();
214+
}
178215
}
179216
}
180217
return this.#abortController;
@@ -199,11 +236,21 @@ export const NodeRequest: {
199236
// No stream for a null-body (GET/HEAD) request, and never re-wrap an
200237
// already-consumed IncomingMessage (the fast path leaves it ended, so a
201238
// fresh `Readable.toWeb` would produce a stream whose `end` never fires).
202-
let stream =
203-
this.#hasBody() && !this.#bodyUsed
204-
? // TODO: HTTP2ServerRequest
205-
(Readable.toWeb(this.#req as NodeJS.ReadableStream) as unknown as ReadableStream)
206-
: null;
239+
let stream: ReadableStream | null = null;
240+
if (this.#hasBody() && !this.#bodyUsed) {
241+
// TODO: HTTP2ServerRequest
242+
stream = Readable.toWeb(this.#req as NodeJS.ReadableStream) as unknown as ReadableStream;
243+
// `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
246+
// undici's "Response body object should not be disturbed or locked"
247+
// TypeError out of `_request`, which tells the handler nothing about
248+
// what happened. Serve a stream carrying the abort reason instead, so
249+
// every read (including through the native Request) rejects with it.
250+
if (Readable.isDisturbed(stream as unknown as NodeJS.ReadableStream)) {
251+
stream = erroredStream(this.#bodyError());
252+
}
253+
}
207254
// Enforce `maxRequestBodySize` at the single choke point every consumer funnels
208255
// through (`request.body`, and therefore the native `Request` methods
209256
// `arrayBuffer()` / `blob()` / `bytes()` / `formData()` and streaming).
@@ -245,10 +292,35 @@ export const NodeRequest: {
245292
return this.#bodyUsed;
246293
}
247294

295+
// Why a body read cannot proceed once the underlying Node stream is gone.
296+
// The abort reason comes first (the socket error, or the controller's
297+
// `AbortError`) so a handler can tell "client hung up" — the case worth a
298+
// 499 rather than a 5xx — from a malformed request. A stream that ended
299+
// without srvx reading it was consumed elsewhere: an unusable body, not an
300+
// abort.
301+
#bodyError(): unknown {
302+
const signal = this._abortController.signal;
303+
if (signal.aborted) {
304+
return signal.reason;
305+
}
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+
);
313+
}
314+
248315
// Buffer the raw request body once; consumers add their own single
249316
// continuation (`.toString()` / `JSON.parse`) so no extra promise or
250317
// microtask hop is introduced vs. inlining the read.
251318
#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) {
322+
return Promise.reject(this.#bodyError());
323+
}
252324
return readBody(this.#req, this.#maxRequestBodySize);
253325
}
254326

@@ -439,6 +511,7 @@ function readBody(req: NodeServerRequest, maxRequestBodySize?: number): Promise<
439511
req.off("data", onData);
440512
req.off("end", onEnd);
441513
req.off("error", onError);
514+
req.off("close", onClose);
442515
};
443516
const onData = (chunk: any) => {
444517
if (maxRequestBodySize !== undefined) {
@@ -463,7 +536,15 @@ function readBody(req: NodeServerRequest, maxRequestBodySize?: number): Promise<
463536
// Single-chunk bodies (the common case) skip Buffer.concat's alloc+copy
464537
resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks));
465538
};
466-
req.on("data", onData).once("end", onEnd).once("error", onError);
539+
// A destroy that surfaces no `error` (`req.destroy()`, or a reset that only
540+
// shows up as a close) would otherwise leave this promise — and the handler
541+
// awaiting it — pending forever. `end` always precedes `close` and cleans
542+
// this listener up first, so it only fires on an incomplete body.
543+
const onClose = () => {
544+
cleanup();
545+
reject(req.errored || abortError());
546+
};
547+
req.on("data", onData).once("end", onEnd).once("error", onError).once("close", onClose);
467548
});
468549
}
469550

‎test/node-adapters.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,59 @@ describe("request signal", () => {
717717
expect(abortFired).toBe(false);
718718
});
719719

720+
// `IncomingMessage` is `autoDestroy`, so a fully read body leaves `req`
721+
// destroyed while the response is still open. Touching `signal` only *after*
722+
// the read is the order that catches a disconnect check keying off
723+
// `req.destroyed` alone -- it would abort every healthy handler that reads its
724+
// body first, breaking the common `fetch(upstream, { signal: request.signal })`
725+
// proxy shape.
726+
test("should not abort when the signal is first read after the body", async () => {
727+
let aborted: boolean | undefined;
728+
let receivedBody: string | undefined;
729+
730+
const server = serve({
731+
port: 0,
732+
async fetch(request) {
733+
receivedBody = await request.text();
734+
aborted = request.signal.aborted;
735+
return new Response(`Received: ${receivedBody}`);
736+
},
737+
});
738+
739+
await server.ready();
740+
741+
const res = await fetch(server.url!, { method: "POST", body: "test body" });
742+
expect(res.status).toBe(200);
743+
expect(await res.text()).toBe("Received: test body");
744+
745+
await server.close();
746+
747+
expect(receivedBody).toBe("test body");
748+
expect(aborted).toBe(false);
749+
});
750+
751+
test("should not abort when the signal is first read after a streamed body", async () => {
752+
let aborted: boolean | undefined;
753+
754+
const server = serve({
755+
port: 0,
756+
async fetch(request) {
757+
await new Response(request.body).text();
758+
aborted = request.signal.aborted;
759+
return new Response("ok");
760+
},
761+
});
762+
763+
await server.ready();
764+
765+
const res = await fetch(server.url!, { method: "POST", body: "test body" });
766+
expect(await res.text()).toBe("ok");
767+
768+
await server.close();
769+
770+
expect(aborted).toBe(false);
771+
});
772+
720773
test("should fire abort signal when client disconnects", async () => {
721774
let abortFired: () => void;
722775
const abortFiredPromise = new Promise<void>((resolve) => {
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import net from "node:net";
2+
import { describe, expect, test } from "vitest";
3+
import { serve } from "../src/adapters/node.ts";
4+
import type { ServerRequest } from "../src/types.ts";
5+
6+
type ReadOutcome = {
7+
/** Rejection from the body read, if any. */
8+
error?: any;
9+
/** `request.signal.aborted`, sampled *after* the read (see below). */
10+
aborted?: boolean;
11+
/** Set when the read never settled. */
12+
timedOut?: true;
13+
};
14+
15+
/**
16+
* Serves one request whose client promises more body than it delivers and then
17+
* destroys the socket, and reports what `read()` did once the request stream is
18+
* gone.
19+
*
20+
* `signal` is deliberately untouched until after the read: srvx creates the
21+
* `AbortController` lazily, so this is also the case where the `close` that
22+
* carries the disconnect fires before any listener exists.
23+
*/
24+
async function readAfterDisconnect(
25+
read: (request: ServerRequest) => Promise<unknown>,
26+
): Promise<ReadOutcome> {
27+
let settle!: (outcome: ReadOutcome) => void;
28+
const outcome = new Promise<ReadOutcome>((resolve) => (settle = resolve));
29+
30+
const server = serve({
31+
hostname: "127.0.0.1",
32+
port: 0,
33+
silent: true,
34+
async fetch(request) {
35+
const req = request.runtime!.node!.req;
36+
// Read only once the client is really gone -- the state the handler sees
37+
// when a disconnect lands while it is awaiting something else.
38+
for (let i = 0; i < 200 && !req.destroyed; i++) {
39+
await new Promise((resolve) => setTimeout(resolve, 5));
40+
}
41+
try {
42+
await read(request);
43+
settle({ aborted: request.signal.aborted });
44+
} catch (error) {
45+
settle({ error, aborted: request.signal.aborted });
46+
}
47+
return new Response("ok");
48+
},
49+
});
50+
await server.ready();
51+
52+
try {
53+
const { port } = server.node!.server!.address() as net.AddressInfo;
54+
const socket = net.connect(port, "127.0.0.1", () => {
55+
socket.write("POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 100\r\n\r\npartial");
56+
setTimeout(() => socket.destroy(), 20);
57+
});
58+
socket.on("error", () => {});
59+
// A read that hangs must fail as an assertion, not as a suite timeout.
60+
return await Promise.race([
61+
outcome,
62+
new Promise<ReadOutcome>((resolve) => setTimeout(() => resolve({ timedOut: true }), 3000)),
63+
]);
64+
} finally {
65+
await server.close(true);
66+
}
67+
}
68+
69+
// https://github.com/h3js/srvx/issues/293
70+
//
71+
// `Readable.toWeb()` hands back an already-cancelled (and therefore disturbed)
72+
// stream once the source is destroyed, so materializing the native Request over
73+
// it threw undici's bare `TypeError: Response body object should not be
74+
// disturbed or locked` -- indistinguishable from a malformed request, so callers
75+
// answered 5xx for every cancelled request. The buffered `text()`/`json()` path
76+
// was worse: it re-listened to a stream that would never emit again and the
77+
// handler hung forever.
78+
describe("node client disconnect before a body read (#293)", () => {
79+
for (const method of ["arrayBuffer", "bytes", "blob", "formData", "text", "json"] as const) {
80+
test(`${method}() rejects with the abort reason`, async () => {
81+
const { error, aborted, timedOut } = await readAfterDisconnect((request) =>
82+
request[method](),
83+
);
84+
expect(timedOut).toBeUndefined();
85+
expect(error).toBeInstanceOf(Error);
86+
expect(error.message).not.toMatch(/disturbed or locked/);
87+
// The socket error srvx also aborts the signal with, so `err ===
88+
// request.signal.reason` identifies a client disconnect.
89+
expect(error.code).toBe("ECONNRESET");
90+
expect(aborted).toBe(true);
91+
});
92+
}
93+
94+
test("body stream errors with the abort reason", async () => {
95+
const { error, aborted, timedOut } = await readAfterDisconnect(async (request) => {
96+
const reader = request.body!.getReader();
97+
return reader.read();
98+
});
99+
expect(timedOut).toBeUndefined();
100+
// Previously the pre-cancelled stream read as a clean `{ done: true }`: a
101+
// truncated body indistinguishable from an empty one.
102+
expect(error).toBeInstanceOf(Error);
103+
expect(error.code).toBe("ECONNRESET");
104+
expect(aborted).toBe(true);
105+
});
106+
107+
test("the rejection is the abort reason", async () => {
108+
let reason: unknown;
109+
const { error, timedOut } = await readAfterDisconnect((request) => {
110+
reason = request.signal.reason;
111+
return request.text();
112+
});
113+
expect(timedOut).toBeUndefined();
114+
expect(error).toBeInstanceOf(Error);
115+
expect(error).toBe(reason);
116+
});
117+
118+
test("a destroy without an error during a buffered read still settles", async () => {
119+
let settle!: (outcome: ReadOutcome) => void;
120+
const outcome = new Promise<ReadOutcome>((resolve) => (settle = resolve));
121+
const server = serve({
122+
hostname: "127.0.0.1",
123+
port: 0,
124+
silent: true,
125+
async fetch(request) {
126+
const req = request.runtime!.node!.req;
127+
// A bare `destroy()` emits no `error`, so only `close` can settle the
128+
// read that is already in flight. The response never reaches the client
129+
// (the socket goes with it), hence the in-process handshake.
130+
setTimeout(() => req.destroy(), 20);
131+
try {
132+
await request.text();
133+
settle({});
134+
} catch (error) {
135+
settle({ error });
136+
}
137+
return new Response("ok");
138+
},
139+
});
140+
await server.ready();
141+
try {
142+
const { port } = server.node!.server!.address() as net.AddressInfo;
143+
const socket = net.connect(port, "127.0.0.1", () => {
144+
socket.write("POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 100\r\n\r\npartial");
145+
});
146+
socket.on("error", () => {});
147+
const { error, timedOut } = await Promise.race([
148+
outcome,
149+
new Promise<ReadOutcome>((resolve) => setTimeout(() => resolve({ timedOut: true }), 3000)),
150+
]);
151+
socket.destroy();
152+
expect(timedOut).toBeUndefined();
153+
expect(error.name).toBe("AbortError");
154+
} finally {
155+
await server.close(true);
156+
}
157+
});
158+
});

0 commit comments

Comments
 (0)