diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 552c5e614382..1170c111c9c5 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -68,6 +68,14 @@ const ObjectAssign = Object.assign; const RegExpPrototypeExec = RegExp.prototype.exec; const StringPrototypeToUpperCase = String.prototype.toUpperCase; +// Installed as an 'error' listener on ClientRequest when `options.signal` is +// passed so that the synthesised AbortError has somewhere to land when the +// user hasn't attached their own 'error' handler. Node's ClientRequest ends +// up in the same state (listenerCount('error') === 1) via its internal +// `addAbortSignal` / `eos()` wiring. See the comment on the `this.on("error", +// noop)` call below for the full rationale. +function noop() {} + function emitErrorEventNT(self, err) { if (self.destroyed) return; if (self.listenerCount("error") > 0) { @@ -210,9 +218,24 @@ function ClientRequest(input, options, cb) { } }; + // When `options.signal` is provided this is overwritten below to tear down + // the abort listener on settle; default is a no-op so the destroy/close + // paths can call it unconditionally. + let removeSignalListener: () => void = () => {}; + + // Latches true once the request has emitted a terminal `'error'` (or is + // about to, via a scheduled nextTick). Every error-emission path checks + // this so that a single request only ever surfaces one terminal error to + // the user — any subsequent source (late signal abort, happy-eyeballs + // `fail()`, dual-catch on the fetch rejection, async lookup error that + // races the signal, …) is silently dropped once someone else has claimed + // the terminal event. + let errorEmitted = false; + this.destroy = function (err?: Error) { if (this.destroyed) return this; this.destroyed = true; + removeSignalListener(); const res = this.res; @@ -241,6 +264,7 @@ function ClientRequest(input, options, cb) { const socketCloseListener = () => { this.destroyed = true; + removeSignalListener(); const res = this.res; if (res) { @@ -265,8 +289,51 @@ function ClientRequest(input, options, cb) { } }; + // Once the signal-abort path has been kicked off we ignore subsequent + // `onAbort` calls — the underlying `kAbortController` fires its listener + // once, but `abortHandler` also invokes `onAbort()` directly as a fallback + // for the pre-`startFetch` case, and we don't want the two to double-emit + // error/close/abort events. + let signalAbortHandled = false; + + const emitSignalAbortNT = (err: Error) => { + // Emit 'error' before 'close' (matching Node.js). `socketCloseListener` + // synchronously emits 'close' and marks the request destroyed; we + // therefore emit the error first, then close, then the legacy 'abort'. + // + // NB: when the signal fires AFTER response headers arrive (body still + // streaming), Bun's pre-existing early-`'close'` divergence means the + // request's terminal `'close'` has already fired via `maybeEmitClose()` + // by the time we get here. In that window this `emit('error', err)` + // lands after `'close'` — a stream-contract violation inherited from + // the early-close behaviour, not from this abort path. User code using + // `req.on('error', …)` still observes the abort; only + // `stream.finished(req)` / `pipeline` consumers (which settle on + // `'close'`) will miss it. + if (!errorEmitted) { + errorEmitted = true; + this.emit("error", err); + } + socketCloseListener(); + this.emit("abort"); + }; + const onAbort = (_err?: Error) => { + if (signalAbortHandled) return; this[kClearTimeout]?.(); + // If the abort was initiated by `options.signal` and the response has + // not already completed, emit an AbortError on 'error' (matching + // Node.js). Running this on nextTick lets listeners attached + // synchronously after `http.request(...)` bind first. Once the response + // has completed, a late-firing signal is a no-op — matching Node's + // behaviour of removing the signal listener on settle. + const signal = this[kSignal]; + if (signal?.aborted && !this[abortedSymbol] && !this?.res?.complete) { + signalAbortHandled = true; + this[abortedSymbol] = true; + process.nextTick(emitSignalAbortNT, $makeAbortError(undefined, { cause: signal.reason })); + return; + } socketCloseListener(); if (!this[abortedSymbol] && !this?.res?.complete) { process.nextTick(emitAbortNextTick, this); @@ -431,6 +498,11 @@ function ClientRequest(input, options, cb) { setIsNextIncomingMessageHTTPS(prevIsHTTPS); res.req = this; res.setTimeout = clientResponseSetTimeout; + // Release the options.signal listener once the response body + // finishes — otherwise a long-lived shared signal (e.g. a + // process-wide shutdown AbortController) would retain every + // successful request's closure for the rest of the signal's life. + res.once("end", removeSignalListener); process.nextTick( (self, res) => { // If the user did not listen for the 'response' event, then they @@ -497,6 +569,14 @@ function ClientRequest(input, options, cb) { if (!!$debug) globalReportError(err); + // The request is settling with a non-abort error (ECONNREFUSED, + // DNS failure, TLS error, …). Drop the options.signal listener so + // a later signal firing doesn't schedule a second 'error' event + // (an AbortError) on top of this one. + removeSignalListener(); + + if (errorEmitted) return; + errorEmitted = true; try { this.emit("error", err); } catch (_err) { @@ -526,6 +606,14 @@ function ClientRequest(input, options, cb) { options.lookup(host, { all: true }, (err, results) => { if (err) { if (!!$debug) globalReportError(err); + // Mirror fail()'s guard: skip if the request has already been + // torn down (user-driven destroy()/abort() or a prior terminal + // error) so late-arriving lookup errors don't emit on a closed + // request. + if (this[abortedSymbol] || this.destroyed || errorEmitted) return; + errorEmitted = true; + // Drop the signal listener so a later abort doesn't double-emit. + removeSignalListener(); process.nextTick((self, err) => self.emit("error", err), this, err); return; } @@ -533,11 +621,19 @@ function ClientRequest(input, options, cb) { let candidates = results.sort((a, b) => b.family - a.family); // prefer IPv6 const fail = (message, name, code, syscall) => { + // If the request has already been aborted or destroyed (e.g. the + // user's signal fired mid-connect during happy-eyeballs + // iteration, or req.abort() was called), swallow this error + // rather than firing a second 'error' event on top of the + // AbortError that `emitSignalAbortNT` has already scheduled. + if (this[abortedSymbol] || this.destroyed || errorEmitted) return; + errorEmitted = true; const error = new Error(message); error.name = name; error.code = code; error.syscall = syscall; if (!!$debug) globalReportError(error); + removeSignalListener(); process.nextTick((self, err) => self.emit("error", err), this, error); }; @@ -578,7 +674,11 @@ function ClientRequest(input, options, cb) { return true; } catch (err) { if (!!$debug) globalReportError(err); - process.nextTick((self, err) => self.emit("error", err), this, err); + if (!errorEmitted) { + errorEmitted = true; + removeSignalListener(); + process.nextTick((self, err) => self.emit("error", err), this, err); + } return false; } }; @@ -610,7 +710,11 @@ function ClientRequest(input, options, cb) { }; } catch (err) { if (!!$debug) globalReportError(err); - this.emit("error", err); + if (!errorEmitted) { + errorEmitted = true; + removeSignalListener(); + this.emit("error", err); + } } finally { process.nextTick(emitFinishAndDeferredCloseNT); } @@ -645,6 +749,14 @@ function ClientRequest(input, options, cb) { const maybeEmitClose = () => { maybeEmitPrefinish(); + // NB: we intentionally do NOT call `removeSignalListener()` here — this + // runs on the nextTick after response headers arrive (while the body is + // still streaming), so detaching the listener early would make + // `options.signal` a no-op for the remainder of the response. Successful + // completion detaches the listener on `res`'s `'end'` event (wired up in + // `handleResponse` when the response is created); the `!res.complete` + // guard in `onAbort` covers the narrow window between close-on-headers + // and end-of-body. if (!this._closed) { process.nextTick(emitCloseNTAndComplete, this); @@ -729,14 +841,32 @@ function ClientRequest(input, options, cb) { const signal = options.signal; if (signal) { //We still want to control abort function and timeout so signal call our AbortController - signal.addEventListener( - "abort", - () => { - this[kAbortController]?.abort(); - }, - { once: true }, - ); + const abortHandler = () => { + this[kAbortController]?.abort?.(); + onAbort(); + }; + if (signal.aborted) { + process.nextTick(abortHandler); + } else { + signal.addEventListener("abort", abortHandler, { once: true }); + // Mirror Node's `eos()`-based cleanup: drop the abort listener once the + // request settles so a late-firing signal (e.g. a long-lived + // AbortSignal.timeout() used as a request deadline) doesn't fire + // `'error'` on a request that already finished or was destroyed by + // the caller. Call this from every settle/teardown path where the + // request will not do any more I/O (normal close, manual destroy, and + // every terminal-error branch). + removeSignalListener = () => signal.removeEventListener("abort", abortHandler); + } this[kSignal] = signal; + // Install a dummy 'error' listener so the synthesised AbortError doesn't + // become an uncaught exception when the user hasn't attached their own + // handler. Node's http.ClientRequest has the same listenerCount('error') + // === 1 when a signal is passed, installed via its `eos()`-based cleanup + // in `addAbortSignal`; this is the Bun equivalent. A user-provided + // `'error'` listener still fires alongside this one, so user code is + // unaffected. + this.on("error", noop); } let method = options.method; const methodIsString = typeof method === "string"; diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts new file mode 100644 index 000000000000..6dfd79ea7761 --- /dev/null +++ b/test/js/node/http/client-signal-abort.test.ts @@ -0,0 +1,448 @@ +import { describe, expect, it } from "bun:test"; +import { once } from "node:events"; +import { createServer, request } from "node:http"; +import type { AddressInfo } from "node:net"; + +// `options.signal` aborting an in-flight `http.request` must emit 'error' +// with an AbortError matching Node.js (`name: 'AbortError'`, `code: +// 'ABORT_ERR'`, `cause: signal.reason`). Without this, callers awaiting +// `req.on('error', reject)` hang until the underlying socket times out. +// +// Regression for #31167. +describe("http.request options.signal", () => { + it("emits 'error' with AbortError when the signal fires mid-request", async () => { + const server = createServer(() => { + // Never respond, so the abort is what settles the request. + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as AddressInfo; + + try { + const signal = AbortSignal.timeout(20); + const { promise, resolve, reject } = Promise.withResolvers(); + + const req = request(`http://127.0.0.1:${port}`, { signal }, () => { + reject(new Error("unexpected response")); + }); + req.on("error", resolve); + req.end(); + + const err = await promise; + expect(err.name).toBe("AbortError"); + expect((err as any).code).toBe("ABORT_ERR"); + // `cause` should be the signal's reason — a DOMException of type + // 'TimeoutError' for `AbortSignal.timeout()`. + expect((err as any).cause).toBeDefined(); + expect((err as any).cause.name).toBe("TimeoutError"); + } finally { + server.close(); + } + }); + + it("emits 'error' when the signal was already aborted before the request ran", async () => { + const { promise, resolve, reject } = Promise.withResolvers(); + const server = createServer(() => { + reject(new Error("server should not be contacted")); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as AddressInfo; + + try { + const controller = new AbortController(); + const reason = new Error("already aborted"); + controller.abort(reason); + + const req = request(`http://127.0.0.1:${port}`, { signal: controller.signal }, () => { + reject(new Error("unexpected response")); + }); + req.on("error", resolve); + req.end(); + + const err = await promise; + expect(err.name).toBe("AbortError"); + expect((err as any).code).toBe("ABORT_ERR"); + expect((err as any).cause).toBe(reason); + } finally { + server.close(); + } + }); + + it("does not emit 'error' when the signal fires after the response completes", async () => { + // A long-lived signal (AbortSignal.timeout(N) used as a request deadline) + // must not emit AbortError on a request whose response has already come + // back successfully. Prior iterations of the fix for #31167 double-emitted + // here and could crash the process when no 'error' listener was attached. + const server = createServer((_req, res) => { + res.end("ok"); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as AddressInfo; + + try { + const controller = new AbortController(); + const errors: Error[] = []; + const { promise, resolve } = Promise.withResolvers(); + + const req = request(`http://127.0.0.1:${port}`, { signal: controller.signal }, res => { + res.resume(); + res.on("end", resolve); + }); + req.on("error", err => errors.push(err)); + req.end(); + + // Wait for the response to fully complete first, then fire the signal. + // Using an explicit controller (not `AbortSignal.timeout`) avoids racing + // the response against a timer, which flakes badly under debug builds. + await promise; + controller.abort(); + // Drain the nextTick queue — the error path (if any) runs on nextTick, + // so yielding once is enough to observe a spurious emission. + await Bun.sleep(0); + + expect(errors).toEqual([]); + } finally { + server.close(); + } + }); + + it("emits 'error' before 'close' when the signal fires", async () => { + // Node.js emits 'error' before the terminal 'close' event so that stream + // consumers (stream.finished(), pipeline) observe the error. The 'abort' + // event is legacy and trails both. + const server = createServer(() => { + // Never respond. + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as AddressInfo; + + try { + const events: string[] = []; + const { promise, resolve } = Promise.withResolvers(); + + const req = request(`http://127.0.0.1:${port}`, { signal: AbortSignal.timeout(20) }); + req.on("error", () => events.push("error")); + req.on("abort", () => events.push("abort")); + req.on("close", () => { + events.push("close"); + resolve(); + }); + req.end(); + + await promise; + // Assert both fired first — `indexOf` returns -1 for a missing entry + // and -1 < anything, so the ordering check alone could green-light a + // missing 'error' emission. + expect(events).toContain("error"); + expect(events).toContain("close"); + expect(events.indexOf("error")).toBeLessThan(events.indexOf("close")); + } finally { + server.close(); + } + }); + + it("does not emit 'error' when the signal fires after req.destroy() with no end()", async () => { + // Destroy-before-end with a still-pending signal is a real-world pattern + // (external cancellation / retry logic that gives up before flushing). + // The signal listener must be removed on `destroy()` so a late-firing + // timeout doesn't resurface as a spurious AbortError on a request the + // caller already tore down. + const server = createServer(() => { + // Never gets hit — request is destroyed before any I/O starts. + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as AddressInfo; + + try { + const signal = AbortSignal.timeout(20); + // Block until the signal has definitely fired so the assertion can + // only run after the late-abort path has had its chance to (wrongly) + // re-enter `onAbort`. + const signalFired = new Promise(resolve => { + signal.addEventListener("abort", () => resolve(), { once: true }); + }); + + const errors: Error[] = []; + const req = request(`http://127.0.0.1:${port}`, { signal }); + req.on("error", err => errors.push(err)); + req.destroy(); + + await signalFired; + // Drain the nextTick queue where a stray `emitSignalAbortNT` would + // run if the listener-removal regressed. + await Bun.sleep(0); + + expect(errors).toEqual([]); + } finally { + server.close(); + } + }); + + it("does not re-emit 'error' after a connection failure when the signal fires later", async () => { + // A request that fails with a network error (ECONNREFUSED, DNS failure, + // TLS error, …) must not emit a second AbortError when a long-lived + // options.signal fires afterwards. Without listener cleanup on the + // fetch-rejection path, a deadline signal would settle the user's + // 'error' handler twice for one request. + // + // Deterministically sequence "network error first, then abort" with an + // explicit AbortController rather than racing an AbortSignal.timeout() + // against the connect error — see the comment on the sibling test above. + const controller = new AbortController(); + const errors: Error[] = []; + // Port 1 is reliably refused on POSIX. + const req = request({ hostname: "127.0.0.1", port: 1, signal: controller.signal }); + const firstError = new Promise(resolve => { + req.on("error", err => { + errors.push(err); + resolve(); + }); + }); + req.end(); + + await firstError; + controller.abort(); + // Drain the nextTick queue where a stray `emitSignalAbortNT` would run + // if the fetch-rejection path had forgotten to detach the listener. + await Bun.sleep(0); + + expect(errors.length).toBe(1); + expect((errors[0] as any).code).toBe("ECONNREFUSED"); + }); + + it("aborts a streaming response when the signal fires after headers but before end", async () => { + // `options.signal` used as a total deadline must still cancel a server + // that sends headers and then stalls / trickles the body. An earlier + // iteration of the fix detached the signal listener in + // `maybeEmitClose()` — which runs on the nextTick after response + // headers arrive — making the signal a no-op for the rest of the + // response. + const server = createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/plain" }); + res.write("chunk1\n"); + // Never call res.end() — force the client to cancel. + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as AddressInfo; + + try { + const controller = new AbortController(); + const { promise: errorFired, resolve: onError } = Promise.withResolvers(); + const { promise: gotData, resolve: onData } = Promise.withResolvers(); + + const req = request(`http://127.0.0.1:${port}`, { signal: controller.signal }, res => { + res.on("data", () => onData()); + }); + req.on("error", onError); + req.end(); + + // Wait for data to arrive (response headers have been received and the + // body is actively streaming). Then fire the signal — this is the + // window where the previous fix regressed: if the listener got + // detached in `maybeEmitClose` on the headers-arrived tick, this + // `abort()` would be a no-op and `errorFired` would hang. + await gotData; + controller.abort(); + + const err = await errorFired; + expect(err.name).toBe("AbortError"); + expect((err as any).code).toBe("ABORT_ERR"); + } finally { + server.close(); + } + }); + + it("does not re-emit 'error' after a synchronous options.lookup throw when the signal fires later", async () => { + // A user-provided `options.lookup` that throws synchronously hits the + // outer try/catch in `startFetch`, which emits the throw as 'error' + // but (without the fix) leaves the options.signal abort listener + // attached. A later signal firing would then emit a second 'error' + // (an AbortError) on a request that already terminally failed. + const controller = new AbortController(); + const errors: Error[] = []; + const lookupErr = new Error("sync lookup boom"); + + const req = request({ + hostname: "example-regression-test.invalid", + port: 80, + signal: controller.signal, + lookup: () => { + throw lookupErr; + }, + }); + const firstError = new Promise(resolve => { + req.on("error", err => { + errors.push(err); + resolve(); + }); + }); + req.end(); + + await firstError; + controller.abort(); + await Bun.sleep(0); + + expect(errors.length).toBe(1); + expect(errors[0]).toBe(lookupErr); + }); + + it("does not double-emit when signal aborts during happy-eyeballs lookup iteration", async () => { + // When a pre-aborted signal meets a multi-candidate `options.lookup` + // result, `emitSignalAbortNT` schedules the AbortError and the + // happy-eyeballs `iterate()` → `fail()` path also schedules an + // ECONNREFUSED — firing 'error' twice on the same request. Guard + // `fail()` on `this[abortedSymbol] || this.destroyed` so only the + // AbortError reaches the user. + const controller = new AbortController(); + controller.abort(); + + const errors: Error[] = []; + const req = request({ + hostname: "test.invalid", + port: 1, + signal: controller.signal, + lookup: (_host, _opts, cb) => { + cb(null, [ + { address: "127.0.0.1", family: 4 }, + { address: "127.0.0.1", family: 4 }, + ]); + }, + }); + const firstError = new Promise(resolve => { + req.on("error", err => { + errors.push(err); + resolve(); + }); + }); + req.end(); + + await firstError; + await Bun.sleep(0); + + expect(errors.length).toBe(1); + expect(errors[0].name).toBe("AbortError"); + expect((errors[0] as any).code).toBe("ABORT_ERR"); + }); + + it("does not double-emit when a pre-aborted signal races a synchronous options.lookup throw", async () => { + // Pre-aborted signal + sync-throwing lookup: the constructor queues + // `abortHandler` on nextTick, and `startFetch` later catches the sync + // throw and queues its own 'error'. The `errorEmitted` latch suppresses + // whichever loses the race so the user only sees one terminal error. + const controller = new AbortController(); + controller.abort(); + const lookupErr = new Error("sync boom"); + const errors: Error[] = []; + + const req = request({ + hostname: "x.invalid", + port: 80, + signal: controller.signal, + lookup: () => { + throw lookupErr; + }, + }); + const firstError = new Promise(resolve => { + req.on("error", err => { + errors.push(err); + resolve(); + }); + }); + req.end(); + + await firstError; + await Bun.sleep(0); + + expect(errors.length).toBe(1); + }); + + it("does not double-emit when signal aborts while an async options.lookup is pending", async () => { + // Signal fires while a genuinely async `options.lookup` is still + // pending, and the lookup then calls back with an error. Without the + // `errorEmitted` latch, the lookup error landed as a second 'error' + // on top of the AbortError already claimed by `emitSignalAbortNT`. + const controller = new AbortController(); + const errors: Error[] = []; + + const req = request("http://example.invalid/", { + signal: controller.signal, + lookup: (_host, _opts, cb) => setImmediate(() => cb(new Error("resolver down"))), + }); + const firstError = new Promise(resolve => { + req.on("error", err => { + errors.push(err); + resolve(); + }); + }); + req.end(); + queueMicrotask(() => controller.abort()); + + await firstError; + await Bun.sleep(0); + + expect(errors.length).toBe(1); + expect(errors[0].name).toBe("AbortError"); + expect((errors[0] as any).code).toBe("ABORT_ERR"); + }); + + it("does not emit 'error' on a destroyed request when a late async options.lookup errors", async () => { + // User calls req.destroy() while an async `options.lookup` is still + // pending, and the lookup then calls back with an error. Emitting + // 'error' on a request the user already tore down contradicts the + // ClientRequest lifecycle; the sibling `fail()` path already guards + // against this, the err-first callback should too. + const errors: Error[] = []; + const closed = Promise.withResolvers(); + const lookupFired = Promise.withResolvers(); + + const req = request("http://example.invalid/", { + lookup: (_host, _opts, cb) => + setImmediate(() => { + cb(new Error("resolver down")); + lookupFired.resolve(); + }), + }); + req.on("error", err => errors.push(err)); + req.on("close", () => closed.resolve()); + req.end(); + req.destroy(); + + await closed.promise; + await lookupFired.promise; + await Bun.sleep(0); + + expect(errors.length).toBe(0); + }); + + it("does not double-emit when the last happy-eyeballs candidate fails (no signal)", async () => { + // Pre-existing: `go()` returns the raw fetch promise (not the + // `.catch`-chained one) and the `!softFail` branch attaches its own + // `.catch` as a side branch. When the last candidate's fetch rejects, + // both consumers see it and without the `errorEmitted` latch the user + // gets two ECONNREFUSEDs for one request. + const errors: Error[] = []; + const req = request({ + hostname: "x", + port: 1, + lookup: (_h, _o, cb) => cb(null, [{ address: "127.0.0.1", family: 4 }]), + }); + const firstError = new Promise(resolve => { + req.on("error", err => { + errors.push(err); + resolve(); + }); + }); + req.end(); + + await firstError; + await Bun.sleep(0); + + expect(errors.length).toBe(1); + expect((errors[0] as any).code).toBe("ECONNREFUSED"); + }); +});