Skip to content
6 changes: 0 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
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
23 changes: 17 additions & 6 deletions src/runtime/webcore/FileSink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1645,11 +1645,16 @@ impl FileSink {
}
}

/// Pump `stream` into this sink. `Ok(UNDEFINED)` when the native fast-path took the stream,
/// `Ok(promise)` for a JS pump still in flight (the sink settles itself through `then`).
/// `Err` when the pump cannot start: the stream is already cancelled and the writer closed, and
/// the pump's rejection reason is the pending exception, so the caller throws it instead of the
/// reason escaping as an unhandled rejection nothing can catch.
pub fn assign_to_stream(
&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 +1680,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 +1690,7 @@ impl FileSink {
let _ = self.end(None);
}
}
return JSValue::UNDEFINED;
return Ok(JSValue::UNDEFINED);
}
readable_stream::NativeWireResult::NotNative => {}
}
Expand All @@ -1702,7 +1707,7 @@ impl FileSink {

if let Some(err) = promise_result.to_error() {
self.readable_stream.set(readable_stream::Strong::default());
return err;
return Err(global_this.throw_value(err));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

if !promise_result.is_empty_or_undefined_or_null() {
Expand Down Expand Up @@ -1737,16 +1742,22 @@ impl FileSink {
self.handle_resolve_stream();
}
bun_jsc::js_promise::Status::Rejected => {
// The pump failed before it returned (the source errored in start(), or
// the first chunk was not bytes). Nothing holds this promise, so take its
// rejection here: mark it handled and hand the reason to the caller.
// 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)?;
return Err(global_this.throw_value(result));
}
}
}
}

promise_result
Ok(promise_result)
}
}

Expand Down
96 changes: 96 additions & 0 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 @@ -331,6 +331,102 @@ 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);
});

test("ReadableStream with byte stream", async () => {
const data = new Uint8Array(256);
for (let i = 0; i < 256; i++) {
Expand Down
Loading