Skip to content
21 changes: 15 additions & 6 deletions src/runtime/api/bun/js_bun_spawn_bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1475,12 +1475,6 @@ fn spawn_maybe_sync(
)
});

if promise_for_stream != JSValue::ZERO && !global_this.has_exception() {
if let Some(err) = promise_for_stream.to_error() {
let _ = global_this.throw_value(err);
}
}

if global_this.has_exception() {
let err = global_this.take_exception(JsError::Thrown);
// Ensure we kill the process so we don't leave things in an unexpected state.
Expand Down Expand Up @@ -1784,6 +1778,21 @@ fn spawn_maybe_sync(
.on_subprocess_spawn(NonNull::new_unchecked(subprocess.process.as_ptr()))
};
}

// The stdin pump already failed: throw its reason. The child is watched, so the kill is reaped.
if let Some(promise) = promise_for_stream.as_promise() {
// SAFETY: `as_promise` returned a live cell held by `promise_for_stream`.
let promise = unsafe { &mut *promise };
if promise.status() == jsc::js_promise::Status::Rejected {
let reason = promise.result(global_this.vm());
// The caller never receives this Subprocess, so none of its callbacks may run.
let _ = Subprocess::js::on_exit_callback_take_cached(out, global_this);
let _ = Subprocess::js::on_disconnect_callback_take_cached(out, global_this);
let _ = Subprocess::js::ipc_callback_take_cached(out, global_this);
let _ = subprocess.try_kill(subprocess.kill_signal);
return Err(global_this.throw_value(reason));
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
return Ok(out);
}

Expand Down
37 changes: 19 additions & 18 deletions src/runtime/api/bun/subprocess/Writable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,17 +171,17 @@ impl<'a> Writable<'a> {
});

if let Stdio::ReadableStream(rs) = stdio {
let assign_result = pipe.assign_to_stream(rs, global);
if let Some(err_val) = assign_result.to_error() {
subprocess.weak_file_sink_stdin_ptr.set(None);
subprocess.update_flags(|f| {
f.set(Flags::DEREF_ON_STDIN_DESTROYED, false)
});
subprocess.deref();
let _ = global.throw_value(err_val);
return Err(crate::Error::JSError);
match pipe.assign_to_stream(rs, global) {
Ok(assign_result) => *promise_for_stream = assign_result,
Err(_) => {
subprocess.weak_file_sink_stdin_ptr.set(None);
subprocess.update_flags(|f| {
f.set(Flags::DEREF_ON_STDIN_DESTROYED, false)
});
subprocess.deref();
return Err(crate::Error::JSError);
}
}
*promise_for_stream = assign_result;
}

return Ok(Writable::Pipe(pipe_ref));
Expand Down Expand Up @@ -271,15 +271,16 @@ impl<'a> Writable<'a> {
});

if let Stdio::ReadableStream(rs) = stdio {
let assign_result = pipe.assign_to_stream(rs, global);
if let Some(err_val) = assign_result.to_error() {
subprocess.weak_file_sink_stdin_ptr.set(None);
subprocess.update_flags(|f| f.set(Flags::DEREF_ON_STDIN_DESTROYED, false));
subprocess.deref();
let _ = global.throw_value(err_val);
return Err(crate::Error::JSError);
match pipe.assign_to_stream(rs, global) {
Ok(assign_result) => *promise_for_stream = assign_result,
Err(_) => {
subprocess.weak_file_sink_stdin_ptr.set(None);
subprocess
.update_flags(|f| f.set(Flags::DEREF_ON_STDIN_DESTROYED, false));
subprocess.deref();
return Err(crate::Error::JSError);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
*promise_for_stream = assign_result;
}

Ok(Writable::Pipe(pipe_ref))
Expand Down
20 changes: 13 additions & 7 deletions src/runtime/webcore/FileSink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1649,7 +1649,7 @@ impl FileSink {
&mut self,
stream: &mut ReadableStream,
global_this: &JSGlobalObject,
) -> JSValue {
) -> JsResult<JSValue> {
// SAFETY: `&mut self` carries write+dealloc provenance over the allocation.
let _guard = unsafe { RefPtr::init_ref(std::ptr::from_mut::<FileSink>(self)) };

Expand All @@ -1675,7 +1675,7 @@ impl FileSink {
self.ref_();
}
}
return JSValue::UNDEFINED;
return Ok(JSValue::UNDEFINED);
}
readable_stream::NativeWireResult::EndedInline(err) => {
self.source.set(streams::SourceHandle::None);
Expand All @@ -1685,7 +1685,7 @@ impl FileSink {
let _ = self.end(None);
}
}
return JSValue::UNDEFINED;
return Ok(JSValue::UNDEFINED);
}
readable_stream::NativeWireResult::NotNative => {}
}
Expand All @@ -1701,8 +1701,11 @@ impl FileSink {
);

if let Some(err) = promise_result.to_error() {
self.readable_stream.set(readable_stream::Strong::default());
return err;
// Same outcome as a pump that rejected before returning: the caller rethrows `err`.
let promise = bun_jsc::JSPromise::rejected_promise(global_this, err);
promise.set_handled();
self.handle_reject_stream(global_this, err)?;
return Ok(promise.to_js());
}

if !promise_result.is_empty_or_undefined_or_null() {
Expand Down Expand Up @@ -1737,16 +1740,19 @@ impl FileSink {
self.handle_resolve_stream();
}
bun_jsc::js_promise::Status::Rejected => {
// Nothing else holds this promise; the caller rethrows its reason.
// These don't ref().
// SAFETY: `js_promise` is non-null (`as_any_promise`).
let result = unsafe { (*js_promise).result(global_this.vm()) };
crate::dispatch::fold(self.handle_reject_stream(global_this, result));
// SAFETY: same cell as above.
unsafe { (*js_promise).set_handled() };
self.handle_reject_stream(global_this, result)?;
}
}
}
}

promise_result
Ok(promise_result)
}
}

Expand Down
210 changes: 191 additions & 19 deletions test/js/bun/spawn/spawn-stdin-readable-stream-edge-cases.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import { spawn } from "bun";
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { bunEnv, bunExe, isWindows } from "harness";

describe("spawn stdin ReadableStream edge cases", () => {
test("ReadableStream with exception in pull", async () => {
Expand Down Expand Up @@ -331,6 +331,176 @@ describe("spawn stdin ReadableStream edge cases", () => {
}).toThrow();
});

test("locked ReadableStream throws from spawn", () => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(3));
controller.close();
},
});
stream.getReader();

expect(() => {
spawn({
cmd: [bunExe(), "-e", "process.stdin.pipe(process.stdout)"],
stdin: stream,
env: bunEnv,
});
}).toThrow("ReadableStream is locked");
});

test("ReadableStream errored in start() throws its reason from spawn", () => {
const reason = new Error("boom");
const stream = new ReadableStream({
start(controller) {
controller.error(reason);
},
});

expect(() => {
spawn({
cmd: [bunExe(), "-e", "process.stdin.pipe(process.stdout)"],
stdin: stream,
env: bunEnv,
});
}).toThrow(reason);
});

test("ReadableStream with a non-byte chunk throws from spawn", () => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(2));
controller.enqueue(42);
controller.close();
},
});

expect(() => {
spawn({
cmd: [bunExe(), "-e", "process.stdin.pipe(process.stdout)"],
stdin: stream,
env: bunEnv,
});
}).toThrow("write() expects a string, ArrayBufferView, or ArrayBuffer");
});

test("a stdin stream that fails before spawn returns never reaches the unhandled rejection handler", async () => {
const script = `
const makers = {
locked() {
const s = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(3)); c.close(); } });
s.getReader();
return s;
},
errored() {
return new ReadableStream({ start(c) { c.error(new Error("boom")); } });
},
badChunk() {
return new ReadableStream({ start(c) { c.enqueue(new Uint8Array(2)); c.enqueue(42); c.close(); } });
},
};
for (const [name, make] of Object.entries(makers)) {
try {
Bun.spawn({ cmd: [process.execPath, "-e", "process.stdin.resume()"], stdin: make(), stdout: "ignore", stderr: "ignore" });
console.log(name, "did not throw");
} catch (e) {
console.log(name, "caught", e.message.includes("locked") ? "locked" : e.message);
}
}
`;
await using proc = spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toBe(
[
"locked caught locked",
"errored caught boom",
"badChunk caught write() expects a string, ArrayBufferView, or ArrayBuffer",
"",
].join("\n"),
);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
});

const failingStdinStreams = {
locked: {
make() {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(3));
controller.close();
},
});
stream.getReader();
return stream;
},
message: "ReadableStream is locked",
},
"non-byte chunk": {
make() {
return new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(2));
controller.enqueue(42);
controller.close();
},
});
},
message: "write() expects a string, ArrayBufferView, or ArrayBuffer",
},
"direct stream whose pull throws": {
make() {
return new ReadableStream({
type: "direct",
pull() {
throw new Error("direct boom");
},
});
},
message: "direct boom",
},
};

test.skipIf(isWindows).each(Object.entries(failingStdinStreams))(
"a spawn that throws on its stdin stream (%s) kills and reaps the child",
async (_name, { make, message }) => {
let onExitCalls = 0;

expect(() => {
spawn({
cmd: ["sleep", "5"],
stdin: make(),
stdout: "ignore",
stderr: "ignore",
onExit() {
onExitCalls++;
},
});
}).toThrow(message);

const listChildren = () =>
Bun.spawnSync(["ps", "-ax", "-o", "pid=,ppid=,stat=,comm="])
.stdout.toString()
.split("\n")
.map(line => line.trim().split(/\s+/))
.filter(([, ppid, , comm]) => ppid === String(process.pid) && comm === "sleep");
Comment thread
robobun marked this conversation as resolved.
Resolved

const deadline = Date.now() + 2000;
let children = listChildren();
while (children.length > 0 && Date.now() < deadline) {
await Bun.sleep(20);
children = listChildren();
}
expect(children).toEqual([]);
expect(onExitCalls).toBe(0);
},
);

test("ReadableStream with byte stream", async () => {
const data = new Uint8Array(256);
for (let i = 0; i < 256; i++) {
Expand Down Expand Up @@ -455,25 +625,27 @@ describe("spawn stdin ReadableStream edge cases", () => {
{ stdout: "pipe", stderr: "inherit" },
];

for (const config of configs) {
const stream = new ReadableStream({
async pull(controller) {
await Bun.sleep(0);
controller.enqueue("test input");
controller.close();
},
});
// Run the configs at once: three sequential debug-build children do not fit the per-test budget.
const results = await Promise.all(
configs.map(async config => {
const stream = new ReadableStream({
async pull(controller) {
await Bun.sleep(0);
controller.enqueue("test input");
controller.close();
},
});

const proc = spawn({
cmd: [bunExe(), "-e", "process.stdin.pipe(process.stdout)"],
stdin: stream,
...config,
env: bunEnv,
});
const proc = spawn({
cmd: [bunExe(), "-e", "process.stdin.pipe(process.stdout)"],
stdin: stream,
...config,
env: bunEnv,
});

const stdout = await proc.stdout.text();
expect(stdout).toBe("test input");
expect(await proc.exited).toBe(0);
}
return [await proc.stdout.text(), await proc.exited];
}),
);
expect(results).toEqual(configs.map(() => ["test input", 0]));
});
});
Loading