Skip to content
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
8141b01
node:child_process: keep an IPC message that arrives before there is …
dylan-conway Oct 17, 2026
dd3283d
node:child_process: emit held IPC messages in one tick in the parent …
dylan-conway Oct 17, 2026
31474d6
Held IPC messages are emitted as in Node where a listener throws: the…
dylan-conway Oct 18, 2026
07f946e
Import bunEnv in the IPC test
dylan-conway Oct 18, 2026
2a7ae47
In a child the held IPC messages are emitted from a real 'newListener…
dylan-conway Oct 18, 2026
647f0c7
process.emit() throws what a listener throws as in Node, and IPC mess…
dylan-conway Oct 18, 2026
d1fa042
Remove a test that belongs to another change
dylan-conway Oct 18, 2026
3b17139
In a child the IPC code asks the listenerCount() that JavaScript sees…
dylan-conway Oct 18, 2026
8000854
process.emit() is main's again, the parent's code for held messages i…
dylan-conway Oct 18, 2026
3c32b31
With no 'message' listener a child asks the listenerCount() that Java…
dylan-conway Oct 18, 2026
ff0ac4c
The child's 'newListener' listener for held IPC messages is native, s…
dylan-conway Oct 18, 2026
5889eb8
The parent's tick for held IPC messages tests the channel, as in Node
dylan-conway Oct 18, 2026
a01f1c4
Test that on() at the stack limit throws to its caller while IPC mess…
dylan-conway Oct 18, 2026
3654a5a
Kept IPC messages are not emitted after an exception nobody handles o…
dylan-conway Oct 18, 2026
14e38d2
The owner of an IPC channel hears of the peer's EOF in the loop itera…
dylan-conway Oct 18, 2026
e1edd65
A tick queued in a dns, dgram, inspector, fs.watch or child stdio cal…
dylan-conway Oct 18, 2026
1158d52
A kept IPC message builds the tick queue in a preload too
dylan-conway Oct 18, 2026
804af16
Take the callback order changes in dns, dgram, inspector, fs.watch an…
dylan-conway Oct 18, 2026
4e0ae84
The owner of an IPC channel hears of a reset by the peer in the loop …
dylan-conway Oct 18, 2026
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
46 changes: 26 additions & 20 deletions src/js/internal/fs/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ type FD = number;

const { validateInteger, validateInt32, validateFunction } = require("internal/validators");

// Captured at load: a process.nextTick that user code replaces later (fake timers) must not hold back what a native write or read ends.
const nextTick = process.nextTick;

const kIsPerformingIO = Symbol("kIsPerformingIO");
const kIoDone = Symbol("kIoDone");
// Bun supports a fast path for `createWriteStream("path.txt")` where instead of
Expand Down Expand Up @@ -618,15 +621,18 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any)

const maybePromise = fileSink.write(data);
if ($isPromise(maybePromise)) {
// Via nextTick: called from the reaction itself (a microtask), a callback's microtasks would run before its nextTicks.
maybePromise.then(
() => {
if (cb) cb(null);
emitDrain(this);
},
err => {
if (cb) cb(err);
require("internal/streams/destroy").errorOrDestroy(this, err);
},
() =>
nextTick(() => {
if (cb) cb(null);
emitDrain(this);
}),
err =>
nextTick(() => {
if (cb) cb(err);
require("internal/streams/destroy").errorOrDestroy(this, err);
}),
);
return false;
} else {
Expand Down Expand Up @@ -684,19 +690,19 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) {
if (fileSink && fileSink !== true) {
const maybePromise = fileSink.write(data);
if ($isPromise(maybePromise)) {
// Two-arg then(): a throw from the fulfillment handler must not be
// mistaken for a write failure.
// Via nextTick: called from the reaction itself (a microtask), a callback's microtasks would run before its nextTicks.
maybePromise.then(
() => {
emitDrain(this);
cb(null);
},
err => {
cb(err);
// Node.js onwriteError: callback AND destroy are both invoked; the
// callback is additive, not a replacement for the 'error' event.
require("internal/streams/destroy").errorOrDestroy(this, err);
},
() =>
nextTick(() => {
emitDrain(this);
cb(null);
}),
err =>
nextTick(() => {
cb(err);
// Node.js onwriteError: the callback is additive, not a replacement for the 'error' event.
require("internal/streams/destroy").errorOrDestroy(this, err);
}),
);
return false; // Indicate backpressure
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/js/internal/fs/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ class FSWatcher extends EventEmitter {
#onEvent(eventType, filenameOrError, fromAbort = false) {
if (eventType === "close") {
if (this.#silentClose) return;
// close on next microtask tick to avoid long-running function calls when
// close on next tick to avoid long-running function calls when
// we're trying to detach the watcher
queueMicrotask(() => {
process.nextTick(() => {
this.emit("close", filenameOrError);
});
return;
Expand Down
23 changes: 13 additions & 10 deletions src/js/internal/streams/native-readable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const transferToNativeReadable = $newCppFunction(
);
const { errorOrDestroy } = require("internal/streams/destroy");

// Captured at load: a process.nextTick that user code replaces later (fake timers) must not hold back what a native write or read ends.
const nextTick = process.nextTick;

const kRefCount = Symbol("refCount");
const kCloseState = Symbol("closeState");
const kConstructed = Symbol("constructed");
Expand Down Expand Up @@ -175,17 +178,17 @@ function read(this: NativeReadable, maxToRead: number) {
);
if ($isPromise(result)) {
this[kPendingRead] = true;
// Via nextTick: called from the reaction itself (a microtask), a callback's microtasks would run before its nextTicks.
return result.then(
result => {
$debug(
`[${this.debugId}] pull, resolved: ${$isTypedArrayView(result) ? `<${result.byteLength} bytes>` : result}, closeState: ${this[kCloseState][0]}`,
);
this[kPendingRead] = false;
this[kRemainingChunk] = handleResult(this, result, chunk, this[kCloseState][0]);
},
reason => {
errorOrDestroy(this, reason);
},
result =>
nextTick(() => {
$debug(
`[${this.debugId}] pull, resolved: ${$isTypedArrayView(result) ? `<${result.byteLength} bytes>` : result}, closeState: ${this[kCloseState][0]}`,
);
this[kPendingRead] = false;
this[kRemainingChunk] = handleResult(this, result, chunk, this[kCloseState][0]);
}),
reason => nextTick(errorOrDestroy, this, reason),
);
} else {
this[kRemainingChunk] = handleResult(this, result, chunk, this[kCloseState][0]);
Expand Down
23 changes: 22 additions & 1 deletion src/js/node/child_process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,7 @@ function spawnSync(file, args, options?): SpawnSyncResult {
}
const etimedoutErrorCode = $newRustFunction("node_util_binding.rs", "etimedoutErrorCode", 0);
const enobufsErrorCode = $newRustFunction("node_util_binding.rs", "enobufsErrorCode", 0);
const hasUnhandledError = $newCppFunction("BunProcess.cpp", "jsFunctionHasUnhandledError", 0);

/**
* Spawns a file as a shell synchronously.
Expand Down Expand Up @@ -1144,6 +1145,7 @@ class ChildProcess extends EventEmitter {
#handle;
#closesNeeded = 1;
#closesGot = 0;
#pendingMessages = [];

declare send?: (message, handle?, options?, callback?) => boolean;
declare disconnect?: () => void;
Expand Down Expand Up @@ -1512,6 +1514,9 @@ class ChildProcess extends EventEmitter {
this.send = this.#send;
this.disconnect = this.#disconnect;
this.channel = new Control();
this.on("newListener", () => {
process.nextTick(() => this.#emitPendingMessages());
});
Object.defineProperty(this, "_channel", {
get() {
return this.channel;
Expand Down Expand Up @@ -1563,8 +1568,22 @@ class ChildProcess extends EventEmitter {
}
}

// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/child_process.js#L954-L964
#emitIpcMessage(message, _, handle) {
this.emit(isInternalIpcMessage(message) ? "internalMessage" : "message", message, handle);
if (isInternalIpcMessage(message)) this.emit("internalMessage", message, handle);
else if (this.listenerCount("message")) this.emit("message", message, handle);
else ArrayPrototypePush.$call(this.#pendingMessages, [message, handle]);
}

// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/child_process.js#L726-L742
#emitPendingMessages() {
// Bun ends the turn of an exception that nobody handles, ticks included. Node is gone by then.
if (!this.channel || hasUnhandledError() || !this.listenerCount("message")) return;
const messages = this.#pendingMessages;
const { length } = messages;
if (!length) return;
for (let i = 0; i < length; i++) this.emit("message", messages[i][0], messages[i][1]);
this.#pendingMessages = [];
}

#send(message, handle, options, callback) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -1618,6 +1637,8 @@ class ChildProcess extends EventEmitter {
return;
}
$assert(!this.connected);
this.channel = null;
this.#pendingMessages = [];
process.nextTick(() => this.emit("disconnect"));
process.nextTick(() => this.#maybeClose());
}
Expand Down
10 changes: 7 additions & 3 deletions src/js/node/dgram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ const EventEmitter = require("node:events");

const { deprecate } = require("internal/util/deprecate");

// Captured at load: a process.nextTick that user code replaces later (fake timers) must not hold back 'listening'.
const nextTick = process.nextTick;

const SymbolDispose = Symbol.dispose;
const SymbolAsyncDispose = Symbol.asyncDispose;
const ObjectDefineProperty = Object.defineProperty;
Expand Down Expand Up @@ -777,6 +780,7 @@ function startBunSocket(self, state, createOptions, sharedHandle?) {
};
// Private name: a cluster-shared descriptor is read one datagram at a time so workers share the load.
if (sharedHandle) $putByIdDirectPrivate(udpOptions, "sharedFd", true);
// Events via nextTick: emitted from the reaction itself (a microtask), a listener's microtasks would run before its nextTicks.
Bun.udpSocket(udpOptions).$then(
socket => {
if (!state.handle) {
Expand All @@ -798,16 +802,16 @@ function startBunSocket(self, state, createOptions, sharedHandle?) {
if (recvBufferSize) bufferSize(self, recvBufferSize, RECV_BUFFER);
if (sendBufferSize) bufferSize(self, sendBufferSize, SEND_BUFFER);
} catch (err) {
self.emit("error", err);
nextTick(() => self.emit("error", err));
return;
}

self.emit("listening");
nextTick(() => self.emit("listening"));
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
},
err => {
state.bindState = BIND_STATE_UNBOUND;
if (sharedHandle) releaseSharedHandle(state, sharedHandle);
self.emit("error", err);
nextTick(() => self.emit("error", err));
},
);
} catch (err) {
Expand Down
25 changes: 17 additions & 8 deletions src/js/node/dns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ const dns = Bun.dns;
const utilPromisifyCustomSymbol = Symbol.for("nodejs.util.promisify.custom");
const { isIP } = require("internal/net/isIP");
const { guardCallback } = require("internal/shared");

// Captured at load: a process.nextTick that user code replaces later (fake timers) must not hold back dns callbacks.
const nextTick = process.nextTick;

// Via nextTick: called from the reaction itself (a microtask), a callback's microtasks would run before its nextTicks.
function wrapCallback(callback) {
callback = guardCallback(callback);
return (...args) => nextTick(callback, ...args);
}
const {
validateFunction,
validateArray,
Expand Down Expand Up @@ -228,7 +237,7 @@ function validateOrderOption(options) {
}
}

// Validates and returns the callback wrapped by guardCallback.
// Validates and returns the callback wrapped by wrapCallback.
// Callers must use the return value, not the argument.
function validateResolve(hostname, callback) {
if (typeof hostname !== "string") {
Expand All @@ -239,7 +248,7 @@ function validateResolve(hostname, callback) {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}

return guardCallback(callback);
return wrapCallback(callback);
}

function validateLocalAddresses(first, second) {
Expand Down Expand Up @@ -339,7 +348,7 @@ function lookup(hostname, options, callback?) {
return;
}

callback = guardCallback(callback);
callback = wrapCallback(callback);
dns
.lookup(hostname, options)
.then(res => {
Expand Down Expand Up @@ -384,7 +393,7 @@ function lookupService(address, port, callback) {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}

callback = guardCallback(callback);
callback = wrapCallback(callback);
dns.lookupService(address, +port).then(
results => {
callback(null, ...results);
Expand Down Expand Up @@ -625,7 +634,7 @@ class Resolver {
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = wrapCallback(callback);

Resolver.#getResolver(this)
.resolveCaa(hostname)
Expand All @@ -646,7 +655,7 @@ class Resolver {
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = wrapCallback(callback);

Resolver.#getResolver(this)
.resolveTxt(hostname)
Expand All @@ -666,7 +675,7 @@ class Resolver {
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = wrapCallback(callback);

Resolver.#getResolver(this)
.resolveSoa(hostname)
Expand All @@ -687,7 +696,7 @@ class Resolver {
if (typeof callback !== "function") {
throw $ERR_INVALID_ARG_TYPE("callback", "function", callback);
}
callback = guardCallback(callback);
callback = wrapCallback(callback);

Resolver.#getResolver(this)
.reverse(ip)
Expand Down
19 changes: 8 additions & 11 deletions src/js/node/inspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,16 +512,13 @@ class Session extends EventEmitter {
const result = this.#handleMethod(method, params as object | undefined);

if (callback) {
// Callback API - async
queueMicrotask(() => {
if (result instanceof Error) {
callback(result, undefined);
} else if (result !== null && typeof result === "object" && kProtocolError in result) {
callback(result[kProtocolError], undefined);
} else {
callback(null, result);
}
});
if (result instanceof Error) {
callback(result, undefined);
} else if (result !== null && typeof result === "object" && kProtocolError in result) {
callback(result[kProtocolError], undefined);
} else {
callback(null, result);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}
} else {
// Sync throw for errors when no callback
if (result instanceof Error) {
Expand Down Expand Up @@ -722,7 +719,7 @@ class Session extends EventEmitter {
// Node streams the collected events back over the session in chunks
// (trace events, then metadata) before signalling completion. Emit
// synchronously: listeners observe everything before the post()
// callback (queued as a microtask above) runs.
// callback runs.
this.emit("NodeTracing.dataCollected", {
method: "NodeTracing.dataCollected",
params: { value: collected },
Expand Down
Loading