From 58906bf0310dfcf53cc248fb78e2e6ac25c9f4d0 Mon Sep 17 00:00:00 2001 From: robobun Date: Thu, 21 May 2026 09:29:43 +0000 Subject: [PATCH 01/12] http.request: emit 'error' with AbortError when options.signal aborts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When `options.signal` passed to `http.request()` aborts, Bun previously only emitted 'abort' and 'close' — callers awaiting `req.on('error', reject)` hung until the underlying socket timed out. Now mirrors Node: - Signal fires mid-request: emit 'error' with an AbortError (name 'AbortError', code 'ABORT_ERR', cause = signal.reason), then 'close', then the legacy 'abort' event, all on one nextTick so stream consumers that settle on 'close' see the error first. - Signal already aborted at construction: same sequence, scheduled on nextTick. - Signal fires after the response has completed: no-op (a late-firing `AbortSignal.timeout(N)` used as a request deadline must not spuriously error a request that already succeeded). Matches Node's `addAbortSignal` side effect of installing an internal 'error' listener so the synthesised AbortError doesn't become an uncaught exception when the user hasn't attached their own handler. Fixes #31167 --- src/js/node/_http_client.ts | 58 ++++++- test/js/node/http/client-signal-abort.test.ts | 141 ++++++++++++++++++ 2 files changed, 192 insertions(+), 7 deletions(-) create mode 100644 test/js/node/http/client-signal-abort.test.ts diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 552c5e614382..ea92ca6c9749 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -68,6 +68,12 @@ 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 — matches Node's internal `addAbortSignal` which leaves a listener +// behind so the synthesised AbortError doesn't become an uncaught exception +// when the user has not registered their own handler. +function noop() {} + function emitErrorEventNT(self, err) { if (self.destroyed) return; if (self.listenerCount("error") > 0) { @@ -265,8 +271,38 @@ 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'. + 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); @@ -729,14 +765,22 @@ 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 }); + } this[kSignal] = signal; + // Node's internal `addAbortSignal` installs an 'error' listener on the + // stream as a side effect so that the signal-driven AbortError has + // somewhere to land when the user hasn't attached one themselves. + // Without this, `emit('error', …)` on a request with no listeners + // becomes an uncaught exception. + 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..938e1a357217 --- /dev/null +++ b/test/js/node/http/client-signal-abort.test.ts @@ -0,0 +1,141 @@ +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; + expect(events.indexOf("error")).toBeLessThan(events.indexOf("close")); + } finally { + server.close(); + } + }); +}); From 9e90768e117ecfa20194ecc776810ed902256fec Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 10:06:54 +0000 Subject: [PATCH 02/12] http.request signal: remove abort listener on settle Review follow-up: the signal's `abort` listener was attached with `{ once: true }` but nothing removed it when the request settled, so a long-lived signal could still drive `onAbort()` on a completed or destroyed request. With the `!res.complete` guard added in the previous commit the late signal on a successful response was already a no-op, but a request that the caller destroyed before calling `end()` (common external-cancellation pattern) had neither `res` nor `abortedSymbol` set, so a later signal firing still scheduled a spurious `AbortError`. Mirror Node's `eos()`-based cleanup: stash the `removeEventListener` call on a closure-local `removeSignalListener` and invoke it from `socketCloseListener`, `req.destroy()`, and `maybeEmitClose`. Also addresses a minor review note: the ordering assertion now checks presence of both `error` and `close` before indexOf-comparing. --- src/js/node/_http_client.ts | 18 ++++++++++ test/js/node/http/client-signal-abort.test.ts | 34 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index ea92ca6c9749..6523cb2e2709 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -216,9 +216,15 @@ 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 = () => {}; + this.destroy = function (err?: Error) { if (this.destroyed) return this; this.destroyed = true; + removeSignalListener(); const res = this.res; @@ -247,6 +253,7 @@ function ClientRequest(input, options, cb) { const socketCloseListener = () => { this.destroyed = true; + removeSignalListener(); const res = this.res; if (res) { @@ -681,6 +688,10 @@ function ClientRequest(input, options, cb) { const maybeEmitClose = () => { maybeEmitPrefinish(); + // The request has settled normally — drop the options.signal listener so + // a later timeout-signal firing doesn't resurface as an AbortError on a + // completed request. + removeSignalListener(); if (!this._closed) { process.nextTick(emitCloseNTAndComplete, this); @@ -773,6 +784,13 @@ function ClientRequest(input, options, cb) { 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. `removeSignalListener` is invoked from + // `socketCloseListener` and `req.destroy()`. + removeSignalListener = () => signal.removeEventListener("abort", abortHandler); } this[kSignal] = signal; // Node's internal `addAbortSignal` installs an 'error' listener on the diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index 938e1a357217..5967df2444d1 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -133,9 +133,43 @@ describe("http.request options.signal", () => { 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); + const errors: Error[] = []; + const req = request(`http://127.0.0.1:${port}`, { signal }); + req.on("error", err => errors.push(err)); + req.destroy(); + + // Wait long enough for the signal to fire, plus a tick to drain. + await Bun.sleep(50); + + expect(errors).toEqual([]); + } finally { + server.close(); + } + }); }); From cd271584daeb85b465878c62ab38adf8ad2359b5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 10:38:35 +0000 Subject: [PATCH 03/12] test: await the signal itself in destroy-before-end case MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the wall-clock `Bun.sleep(50)` in the destroy-then-signal test with a direct `signal.addEventListener("abort", …)` await so the assertion only runs after the late-abort path has had its chance to (wrongly) fire. Previously the 50ms wait vs a 20ms timeout relied on a timing race and would trivially pass if the signal hadn't fired yet, letting a regression slip through. `events.once(signal, "abort")` isn't usable here — AbortSignal is an EventTarget, and `once()` from `node:events` hangs on one after every listener has been removed (matches Node's behaviour). Use a dedicated `addEventListener` instead. --- test/js/node/http/client-signal-abort.test.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index 5967df2444d1..e7c4991b38cd 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -159,13 +159,25 @@ describe("http.request options.signal", () => { 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`. We can't use `events.once(signal, "abort")` here + // — `AbortSignal` is an `EventTarget`, not an `EventEmitter`, and + // Node's `once()` hangs on one after destroy has already removed + // every listener. Attach a dedicated listener instead. + 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(); - // Wait long enough for the signal to fire, plus a tick to drain. - await Bun.sleep(50); + 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 { From 73aadbae1cb8f4ec7a70dd4d9dab8eaf4025dbb2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 11:08:57 +0000 Subject: [PATCH 04/12] ci: retrigger From 9901e02e6800b57e248d146ccfdf1441b2971b1a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 11:25:57 +0000 Subject: [PATCH 05/12] http.request signal: detach listener on network-error settle paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up: `removeSignalListener()` was wired into the three happy-path settle points (`socketCloseListener`, `destroy`, `maybeEmitClose`) but the fetch-rejection `.catch` and the `options.lookup` error/fail paths weren't covered. A request that settled with ECONNREFUSED / ENOTFOUND / TLS-handshake-error and carried a long-lived `AbortSignal.timeout(N)` as a deadline would therefore emit a second `'error'` (AbortError) when the signal fired later — user `'error'` handlers saw two different errors for one request. Drop the signal listener on those paths, mirroring the cleanup Node performs via `socket.destroy(err)` → Writable destroy → `eos()`. Also correct the misleading comment on the internal `noop` error listener: Node's `addAbortSignal` itself doesn't install one, but `ClientRequest.listenerCount('error')` still ends up at 1 for a signal-bearing request via Node's `eos()` wiring. Bun mirrors that end state with the `noop`. User-provided `'error'` listeners still fire alongside it, so user code is unaffected. Regression test covers the connection-failure / late-signal case. --- src/js/node/_http_client.ts | 29 ++++++++++++++----- test/js/node/http/client-signal-abort.test.ts | 24 +++++++++++++++ 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 6523cb2e2709..9aa9597e8d2d 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -69,9 +69,11 @@ const RegExpPrototypeExec = RegExp.prototype.exec; const StringPrototypeToUpperCase = String.prototype.toUpperCase; // Installed as an 'error' listener on ClientRequest when `options.signal` is -// passed — matches Node's internal `addAbortSignal` which leaves a listener -// behind so the synthesised AbortError doesn't become an uncaught exception -// when the user has not registered their own handler. +// 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) { @@ -540,6 +542,12 @@ 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(); + try { this.emit("error", err); } catch (_err) { @@ -569,6 +577,8 @@ function ClientRequest(input, options, cb) { options.lookup(host, { all: true }, (err, results) => { if (err) { if (!!$debug) globalReportError(err); + // Drop the signal listener so a later abort doesn't double-emit. + removeSignalListener(); process.nextTick((self, err) => self.emit("error", err), this, err); return; } @@ -581,6 +591,7 @@ function ClientRequest(input, options, cb) { error.code = code; error.syscall = syscall; if (!!$debug) globalReportError(error); + removeSignalListener(); process.nextTick((self, err) => self.emit("error", err), this, error); }; @@ -793,11 +804,13 @@ function ClientRequest(input, options, cb) { removeSignalListener = () => signal.removeEventListener("abort", abortHandler); } this[kSignal] = signal; - // Node's internal `addAbortSignal` installs an 'error' listener on the - // stream as a side effect so that the signal-driven AbortError has - // somewhere to land when the user hasn't attached one themselves. - // Without this, `emit('error', …)` on a request with no listeners - // becomes an uncaught exception. + // 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; diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index e7c4991b38cd..25594bfac116 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -184,4 +184,28 @@ describe("http.request options.signal", () => { 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. + const signal = AbortSignal.timeout(30); + const signalFired = new Promise(resolve => { + signal.addEventListener("abort", () => resolve(), { once: true }); + }); + + const errors: Error[] = []; + // Port 1 is reliably refused on POSIX/Windows. + const req = request({ hostname: "127.0.0.1", port: 1, signal }); + req.on("error", err => errors.push(err)); + req.end(); + + await signalFired; + await Bun.sleep(0); + + expect(errors.length).toBe(1); + expect((errors[0] as any).code).toBe("ECONNREFUSED"); + }); }); From a3843412e9ab908af1df6957b830f59012231cdb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 12:08:10 +0000 Subject: [PATCH 06/12] http.request signal: don't detach listener in maybeEmitClose Review follow-up: `maybeEmitClose()` runs on the nextTick *after the response headers arrive*, while the body is still streaming (`res.complete === false`). The previous commit called `removeSignalListener()` there, which made `options.signal` a no-op for the remainder of the response: a server that sent headers and then stalled or trickled the body could no longer be cancelled via the signal once the first chunk had been dispatched. The `!res.complete` guard in `onAbort` already prevents a spurious AbortError from firing after the response completes, and the listener is still removed on real teardown (`socketCloseListener`, `req.destroy()`, and the network-error settle paths), so the `maybeEmitClose` cleanup was redundant as well as harmful. Drop it and leave a comment so future edits don't re-introduce it. Regression test manually aborts during the body-streaming window (after a first chunk has been received, before `res.end()`). --- src/js/node/_http_client.ts | 11 +++-- test/js/node/http/client-signal-abort.test.ts | 43 +++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 9aa9597e8d2d..2be1b3cacee1 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -699,10 +699,13 @@ function ClientRequest(input, options, cb) { const maybeEmitClose = () => { maybeEmitPrefinish(); - // The request has settled normally — drop the options.signal listener so - // a later timeout-signal firing doesn't resurface as an AbortError on a - // completed request. - removeSignalListener(); + // 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. Late-fire + // protection is instead handled by the `!res.complete` guard in + // `onAbort`, and the listener is cleaned up on real teardown via + // `socketCloseListener()` and `req.destroy()`. if (!this._closed) { process.nextTick(emitCloseNTAndComplete, this); diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index 25594bfac116..a1474095ec69 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -208,4 +208,47 @@ describe("http.request options.signal", () => { 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(); + } + }); }); From 816c2ef09f5e649887955beeaa91c015296ee88a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 12:17:50 +0000 Subject: [PATCH 07/12] http.request signal: cover sync-throw catch blocks + test cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up from claude[bot]: - Add `removeSignalListener()` to the two remaining settle paths that were missed in 9901e02e — the outer `try { options.lookup(...) } catch` in `startFetch()` and `send()`'s `try { startFetch(...) } catch`. Both are synchronous-throw catches that emit 'error' directly; without the listener removal, a later signal firing would double-emit an AbortError on a request that already terminally failed. New regression test covers the `options.lookup` throw case. - Replace the flaky sequencing in the connection-failure test (`does not re-emit 'error' after a connection failure…`) with an explicit `AbortController` so it awaits the ECONNREFUSED first, then fires the abort deterministically — matching the sibling tests and the in-file comment warning against the `AbortSignal.timeout()` race pattern. - Drop the enumeration in the comment next to `removeSignalListener` — it had already rotted from two callers to six across two commits in this PR. Describe the intent instead. --- src/js/node/_http_client.ts | 7 ++- test/js/node/http/client-signal-abort.test.ts | 60 ++++++++++++++++--- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 2be1b3cacee1..11a7f64f8cea 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -632,6 +632,7 @@ function ClientRequest(input, options, cb) { return true; } catch (err) { if (!!$debug) globalReportError(err); + removeSignalListener(); process.nextTick((self, err) => self.emit("error", err), this, err); return false; } @@ -664,6 +665,7 @@ function ClientRequest(input, options, cb) { }; } catch (err) { if (!!$debug) globalReportError(err); + removeSignalListener(); this.emit("error", err); } finally { process.nextTick(emitFinishAndDeferredCloseNT); @@ -802,8 +804,9 @@ function ClientRequest(input, options, cb) { // 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. `removeSignalListener` is invoked from - // `socketCloseListener` and `req.destroy()`. + // 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; diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index a1474095ec69..ba3cd03f28e2 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -191,18 +191,26 @@ describe("http.request options.signal", () => { // 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. - const signal = AbortSignal.timeout(30); - const signalFired = new Promise(resolve => { - signal.addEventListener("abort", () => resolve(), { once: true }); - }); - + // + // 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/Windows. - const req = request({ hostname: "127.0.0.1", port: 1, signal }); - req.on("error", err => errors.push(err)); + // 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 signalFired; + 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); @@ -251,4 +259,38 @@ describe("http.request options.signal", () => { 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); + }); }); From 0bb08fc932267fde1f2424a395a63cc5b2ec4863 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 13:29:59 +0000 Subject: [PATCH 08/12] http.request signal: detach listener on res 'end', document early-close MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up from claude[bot]: - Hook `removeSignalListener()` into `res.once('end', …)` so a long-lived shared signal (e.g. a process-wide shutdown AbortController) doesn't retain every successful request's closure for the rest of the signal's life. The previous code only cleaned up on abort/destroy paths; the normal success path left the listener attached. Pre-existing leak — the old inline arrow listener had the same property — but easy to close now that the wiring is already in place. - Rewrite the stale comment at `maybeEmitClose` accordingly. - Document the pre-existing ordering divergence in the body-streaming abort window: Bun's early-`'close'` on headers-arrived means a signal firing after data starts flowing produces `close → error → abort` rather than Node's `error → close`. The root cause is unrelated to this PR (it's the headers-arrived close behaviour), and fixing it touches pre-existing Bun code outside scope; note it in `emitSignalAbortNT` so future readers don't re-litigate. --- src/js/node/_http_client.ts | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 11a7f64f8cea..0642688eb78a 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -291,6 +291,16 @@ function ClientRequest(input, options, cb) { // 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. this.emit("error", err); socketCloseListener(); this.emit("abort"); @@ -476,6 +486,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 @@ -704,10 +719,11 @@ function ClientRequest(input, options, cb) { // 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. Late-fire - // protection is instead handled by the `!res.complete` guard in - // `onAbort`, and the listener is cleaned up on real teardown via - // `socketCloseListener()` and `req.destroy()`. + // `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); From 3a997a9c03d9fca912d393a0c99f1b0e5fc513b4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 14:25:27 +0000 Subject: [PATCH 09/12] http.request signal: swallow happy-eyeballs fail() after abort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up from claude[bot]: When a signal aborts while happy-eyeballs `iterate()` is mid-connect, the inner `.catch` early-returns on `isAbortError` but the outer `.catch(iterate)` still fires on the same underlying promise, draining the candidate list and landing in `fail()` — which then emits a spurious ECONNREFUSED on top of the AbortError that `emitSignalAbortNT` has already scheduled. Guard `fail()` on `this[abortedSymbol] || this.destroyed` so only the AbortError reaches the user. Regression test covers the pre-aborted + multi-candidate lookup case — fails without the guard with `[AbortError, ECONNREFUSED]`. Also trim the misleading `events.once()` rationale in the destroy-before-end test comment: `events.once` does support EventTarget via the fall-through branch, so the hand-rolled listener is a stylistic choice, not a workaround. Keep just the intent. --- src/js/node/_http_client.ts | 6 +++ test/js/node/http/client-signal-abort.test.ts | 43 +++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 0642688eb78a..c7d966ec62a0 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -601,6 +601,12 @@ 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) return; const error = new Error(message); error.name = name; error.code = code; diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index ba3cd03f28e2..0a536be8e3fd 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -161,10 +161,7 @@ describe("http.request options.signal", () => { 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`. We can't use `events.once(signal, "abort")` here - // — `AbortSignal` is an `EventTarget`, not an `EventEmitter`, and - // Node's `once()` hangs on one after destroy has already removed - // every listener. Attach a dedicated listener instead. + // re-enter `onAbort`. const signalFired = new Promise(resolve => { signal.addEventListener("abort", () => resolve(), { once: true }); }); @@ -293,4 +290,42 @@ describe("http.request options.signal", () => { 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"); + }); }); From 993ed24002a223994d761a2716ab1c246dac42e4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 15:22:20 +0000 Subject: [PATCH 10/12] http.request signal: latch 'error' emission, cover remaining double-emit paths Review follow-up from claude[bot]. Three adjacent double-emit cases were leaking past the per-path guards added in earlier commits: 1. Pre-aborted signal + sync-throwing `options.lookup`: the pre-aborted branch schedules `abortHandler` on nextTick but `removeSignalListener` can't cancel a queued `process.nextTick` that was never attached as a listener, so the catch block's cleanup is a no-op for pre-aborted signals. Result: lookup-error + AbortError. 2. Signal races an async `options.lookup` that then errors: the err-first callback at the top of `startFetch`'s lookup call had no `abortedSymbol`/`destroyed` check (the sibling `fail()` got one in 3a997a9c, but this earlier branch was missed). Result: AbortError + lookup error. 3. Happy-eyeballs last-candidate network failure (pre-existing, no signal involved): `go()` returns the raw fetch promise and attaches its inner `.catch(emitError).finally(...)` as a side branch, so `iterate()`'s `.catch(iterate)` sees the same rejection, drains to empty, and `fail()` fires a second ECONNREFUSED. The new `fail()` guard only checks `abortedSymbol`/`destroyed`, neither of which the inner `.catch` sets. All three collapse to the same invariant: at most one terminal `'error'` per request. Introduce a closure-local `errorEmitted` latch and gate every `'error'` emission path on it. This subsumes the existing `abortedSymbol`/`destroyed` check in `fail()`, makes the cleanup `removeSignalListener()` calls on the error paths idempotent-by-design, and closes the pre-existing iterate dual-catch without needing to restructure the promise chain. Three new regression tests (all fail without the latch, pass with it). --- src/js/node/_http_client.ts | 35 ++++++-- test/js/node/http/client-signal-abort.test.ts | 88 +++++++++++++++++++ 2 files changed, 117 insertions(+), 6 deletions(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index c7d966ec62a0..20e8dd5a9b35 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -223,6 +223,15 @@ function ClientRequest(input, options, cb) { // 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; @@ -301,7 +310,10 @@ function ClientRequest(input, options, cb) { // `req.on('error', …)` still observes the abort; only // `stream.finished(req)` / `pipeline` consumers (which settle on // `'close'`) will miss it. - this.emit("error", err); + if (!errorEmitted) { + errorEmitted = true; + this.emit("error", err); + } socketCloseListener(); this.emit("abort"); }; @@ -563,6 +575,8 @@ function ClientRequest(input, options, cb) { // (an AbortError) on top of this one. removeSignalListener(); + if (errorEmitted) return; + errorEmitted = true; try { this.emit("error", err); } catch (_err) { @@ -592,6 +606,8 @@ function ClientRequest(input, options, cb) { options.lookup(host, { all: true }, (err, results) => { if (err) { if (!!$debug) globalReportError(err); + if (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); @@ -606,7 +622,8 @@ function ClientRequest(input, options, cb) { // 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) return; + if (this[abortedSymbol] || this.destroyed || errorEmitted) return; + errorEmitted = true; const error = new Error(message); error.name = name; error.code = code; @@ -653,8 +670,11 @@ function ClientRequest(input, options, cb) { return true; } catch (err) { if (!!$debug) globalReportError(err); - removeSignalListener(); - 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; } }; @@ -686,8 +706,11 @@ function ClientRequest(input, options, cb) { }; } catch (err) { if (!!$debug) globalReportError(err); - removeSignalListener(); - this.emit("error", err); + if (!errorEmitted) { + errorEmitted = true; + removeSignalListener(); + this.emit("error", err); + } } finally { process.nextTick(emitFinishAndDeferredCloseNT); } diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index 0a536be8e3fd..fd869c0ece50 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -328,4 +328,92 @@ describe("http.request options.signal", () => { 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 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"); + }); }); From bf299855e787999c0d8bde005b7d0d752f1ccd14 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 16:00:49 +0000 Subject: [PATCH 11/12] http.request signal: align lookup err guard with fail() The err-first branch of the async `options.lookup` callback only checked `errorEmitted`, while the sibling `fail()` six lines below uses `abortedSymbol || destroyed || errorEmitted`. `errorEmitted` covers signal-driven teardown (via `emitSignalAbortNT`) but not user-driven `req.destroy()` / `req.abort()` (which set only `destroyed` / `abortedSymbol`), leaving a residual gap where an async lookup that errors after a user-driven teardown emits on a closed request. Mirror `fail()`'s three-way guard so the two adjacent branches handle late-arriving errors consistently. Regression test covers the user-driven-destroy + late-lookup-error path. --- src/js/node/_http_client.ts | 6 ++++- test/js/node/http/client-signal-abort.test.ts | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/js/node/_http_client.ts b/src/js/node/_http_client.ts index 20e8dd5a9b35..1170c111c9c5 100644 --- a/src/js/node/_http_client.ts +++ b/src/js/node/_http_client.ts @@ -606,7 +606,11 @@ function ClientRequest(input, options, cb) { options.lookup(host, { all: true }, (err, results) => { if (err) { if (!!$debug) globalReportError(err); - if (errorEmitted) return; + // 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(); diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index fd869c0ece50..83c8bd6e7221 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -390,6 +390,29 @@ describe("http.request options.signal", () => { 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 has guarded + // against this since 3a997a9c, the err-first callback should too. + const errors: Error[] = []; + const closed = Promise.withResolvers(); + + const req = request("http://example.invalid/", { + lookup: (_host, _opts, cb) => setImmediate(() => cb(new Error("resolver down"))), + }); + req.on("error", err => errors.push(err)); + req.on("close", () => closed.resolve()); + req.end(); + req.destroy(); + + await closed.promise; + await Bun.sleep(10); + + 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 From f0a3ea3f764d35ab3f5949d9141f3287e3cff9e6 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 21 May 2026 16:40:22 +0000 Subject: [PATCH 12/12] test(http client-signal-abort): await lookupFired instead of Bun.sleep(10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Align with the sibling tests in this file: resolve a promise from inside the lookup callback and `await lookupFired; await Bun.sleep(0);` instead of a 10ms wall-clock wait. Also drop the `since 3a997a9c` clause from the test comment — PR-branch SHAs don't survive squash-merge. --- test/js/node/http/client-signal-abort.test.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/test/js/node/http/client-signal-abort.test.ts b/test/js/node/http/client-signal-abort.test.ts index 83c8bd6e7221..6dfd79ea7761 100644 --- a/test/js/node/http/client-signal-abort.test.ts +++ b/test/js/node/http/client-signal-abort.test.ts @@ -394,13 +394,18 @@ describe("http.request options.signal", () => { // 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 has guarded - // against this since 3a997a9c, the err-first callback should too. + // 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"))), + lookup: (_host, _opts, cb) => + setImmediate(() => { + cb(new Error("resolver down")); + lookupFired.resolve(); + }), }); req.on("error", err => errors.push(err)); req.on("close", () => closed.resolve()); @@ -408,7 +413,8 @@ describe("http.request options.signal", () => { req.destroy(); await closed.promise; - await Bun.sleep(10); + await lookupFired.promise; + await Bun.sleep(0); expect(errors.length).toBe(0); });