Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 88 additions & 7 deletions src/js/node/_http_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@
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) {
Expand Down Expand Up @@ -210,9 +218,15 @@
}
};

// 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;

Expand Down Expand Up @@ -241,6 +255,7 @@

const socketCloseListener = () => {
this.destroyed = true;
removeSignalListener();

const res = this.res;
if (res) {
Expand All @@ -265,8 +280,38 @@
}
};

// 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");
};

Check failure on line 297 in src/js/node/_http_client.ts

View check run for this annotation

Claude / Claude Code Review

Signal abort during body streaming emits 'error' after 'close' on the request

Commit 687016a fixed the `'error'`-after-`'close'` ordering for the no-response case, but in test 7's scenario (signal fires after headers arrive, while the body is streaming) `maybeEmitClose()` has *already* run `emitCloseNTAndComplete` → `req._closed = true` / `req.emit('close')` before `onAbort` schedules `emitSignalAbortNT` — so the request sees **`close` → `error` → `abort`**, the same stream-contract violation. `emitSignalAbortNT` only orders `'error'` before the `'close'` it emits via `so
Comment thread
robobun marked this conversation as resolved.
Resolved

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;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
socketCloseListener();
if (!this[abortedSymbol] && !this?.res?.complete) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
process.nextTick(emitAbortNextTick, this);
Expand Down Expand Up @@ -497,6 +542,12 @@

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) {
Expand Down Expand Up @@ -526,6 +577,8 @@
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;
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Expand All @@ -538,6 +591,7 @@
error.code = code;
error.syscall = syscall;
if (!!$debug) globalReportError(error);
removeSignalListener();
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
process.nextTick((self, err) => self.emit("error", err), this, error);
};

Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -578,6 +632,7 @@
return true;
} catch (err) {
if (!!$debug) globalReportError(err);
removeSignalListener();
process.nextTick((self, err) => self.emit("error", err), this, err);
return false;
}
Expand Down Expand Up @@ -610,6 +665,7 @@
};
} catch (err) {
if (!!$debug) globalReportError(err);
removeSignalListener();
this.emit("error", err);
} finally {
process.nextTick(emitFinishAndDeferredCloseNT);
Expand Down Expand Up @@ -645,6 +701,13 @@

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. 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()`.

Check warning on line 710 in src/js/node/_http_client.ts

View check run for this annotation

Claude / Claude Code Review

Signal abort listener never removed on successful completion; maybeEmitClose comment is misleading

This comment says the listener "is cleaned up on real teardown via `socketCloseListener()` and `req.destroy()`", but neither of those actually runs on a normal successful completion — the success path is `maybeEmitClose()` → `emitCloseNTAndComplete`, and `socketCloseListener()` is only invoked from abort paths. So for `http.request(url, { signal })` where the response completes and the signal never fires (e.g. a long-lived shared shutdown `AbortController`), `abortHandler` stays attached to the
Comment thread
robobun marked this conversation as resolved.
Resolved

if (!this._closed) {
process.nextTick(emitCloseNTAndComplete, this);
Expand Down Expand Up @@ -729,14 +792,32 @@
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);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Comment thread
robobun marked this conversation as resolved.
Resolved
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";
Expand Down
Loading
Loading