Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 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
51 changes: 50 additions & 1 deletion src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ pub struct RequestContext<
// fall back to `response_weakref` (see its doc below), so a `Strong`
// here would root the Response unconditionally and change GC behavior.
pub response_jsvalue: JSValue,

/// Original error passed to `error()` when it returned a pending promise.
/// Protected while in-flight so a deferred non-Response resolution can
/// still report it; cleared on settle and in finalize_without_deinit.
pub error_promise_value: JSValue,
pub ref_count: u8,

/// Weak: for plain Blob/InternalBlob bodies the Response JSValue is
Expand Down Expand Up @@ -736,11 +741,40 @@ where
self.render_missing();
}

/// Release the GC root taken for a pending `error()` promise in
/// process_on_error_promise and clear the deferred-error state. Idempotent.
fn clear_error_promise_value(&mut self) {
self.flags.set_is_error_promise_pending(false);
let value = self.error_promise_value;
if !value.is_empty() {
value.unprotect();
self.error_promise_value = JSValue::ZERO;
}
}

fn handle_resolve(ctx: &mut Self, value: JSValue) {
if ctx.is_aborted_or_ended() || ctx.did_upgrade_web_socket() {
return;
}

// A deferred `error()` handler shares fetch's resolve callback; a
// non-Response fulfillment must report the original error at 500, not
// render a misleading empty 204 (matches the sync/settled twins).
if ctx.flags.is_error_promise_pending() {
// SAFETY: only probed for Response-ness; the borrow ends here.
if (unsafe { as_response(value) }).is_none() {
// The stash stays GC-rooted via its protect() across this
// JS-reentering report; clear_error_promise_value releases it after.
let original_error = ctx.error_promise_value;
ctx.finish_running_error_handler(original_error, 500);
ctx.clear_error_promise_value();
return;
}
// Deferred error() that produced a Response: release the root and
// fall through to render it.
ctx.clear_error_promise_value();
}

if ctx.server.is_none() {
ctx.render_missing_invalid_response(value);
return;
Expand Down Expand Up @@ -1291,6 +1325,7 @@ where
flags: Flags::<DEBUG_MODE>::default(),
upgrade_context: None,
response_jsvalue: JSValue::ZERO,
error_promise_value: JSValue::ZERO,
ref_count: 1,
response_weakref: response::WeakRef::EMPTY,
blob: AnyBlob::Blob(Blob::default()),
Expand Down Expand Up @@ -1481,6 +1516,9 @@ where
}
self.response_jsvalue = JSValue::ZERO;
}
// Release the root taken for a deferred error() promise that never
// settled (e.g. the connection aborted while it was in-flight).
self.clear_error_promise_value();
self.response_weakref.deref();

self.request_body_readable_stream_ref.deinit();
Expand Down Expand Up @@ -3310,7 +3348,14 @@ where
self.flags.set_has_written_status(true);
}

self.end(b"Something went wrong!", self.should_close_connection());
if self.method == Method::HEAD {
// HEAD must not carry a body (RFC 9110 §9.3.2); a stray
// body desyncs the keep-alive connection. Mirror the 404
// arm above and let uWS frame the empty body.
self.end_without_body(self.should_close_connection());
} else {
self.end(b"Something went wrong!", self.should_close_connection());
}
}
}
}
Expand Down Expand Up @@ -3434,6 +3479,10 @@ where
match promise.unwrap(vm.global().vm(), jsc::PromiseUnwrapMode::MarkHandled) {
jsc::PromiseResult::Pending => {
ctx.flags.set_is_error_promise_pending(true);
// Keep the original error rooted across the await so a deferred
// non-Response resolution can still report it (handle_resolve).
ctx.error_promise_value = value;
value.protect();
ctx.ref_();
let cell = NativePromiseContext::create(server.global_this(), ctx);
promise_js.then_with_value(
Expand Down
180 changes: 180 additions & 0 deletions test/js/bun/http/serve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1901,6 +1901,186 @@ it("should support promise returned from error", async () => {
subprocess.kill();
});

// Sends a HEAD request, then a keep-alive GET on the SAME socket once the HEAD
// headers arrive. fetch() hides the HEAD body, so a raw socket is the only way
// to observe whether the server wrote stray body bytes; a leaked HEAD body
// would desync (prepend to) the pipelined GET response. The GET closes the
// connection so the returned string is deterministic.
function headThenGet(base: string, headPath: string, getPath: string): Promise<string> {
const u = new URL(base);
const host = `${u.hostname}:${u.port}`;
const { promise, resolve, reject } = Promise.withResolvers<string>();
const socket = net.createConnection(Number(u.port), u.hostname);
let raw = "";
let sentGet = false;
socket.on("connect", () => socket.write(`HEAD ${headPath} HTTP/1.1\r\nHost: ${host}\r\n\r\n`));
socket.on("data", d => {
raw += d.toString();
if (!sentGet && raw.includes("\r\n\r\n")) {
sentGet = true;
socket.write(`GET ${getPath} HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`);
}
});
socket.on("error", reject);
socket.on("close", () => resolve(raw));
return promise;
}

// A deferred error() that returns a pending Promise<undefined> used to
// respond 204 and swallow the original error, unlike its sync and
// already-settled twins which respond 500. Runs in a subprocess so the
// server's error reports don't trip the test runner's unhandled-error check.
it("error() producing no Response always responds 500 (#33137)", async () => {
using dir = tempDir("serve-deferred-error-33137", {
"server.js": `
const server = Bun.serve({
port: 0,
development: false,
fetch(request) {
const { pathname } = new URL(request.url);
if (pathname === "/ok") return new Response("ok-marker");
// A rejected fetch promise routes through handle_reject into error().
if (pathname === "/fetch-rejects") {
return new Promise((_, reject) => setImmediate(() => reject(new Error(pathname))));
}
throw new Error(pathname);
},
error(cause) {
const { message } = cause;
if (message === "/sync") return undefined;
if (message === "/already-settled") return Promise.resolve(undefined);
if (message === "/already-settled-null") return Promise.resolve(null);
if (message === "/deferred-null") return new Promise(r => setImmediate(() => r(null)));
if (message === "/deferred-response") {
return new Promise(r => setImmediate(() => r(new Response("handled", { status: 503 }))));
}
// /deferred, /fetch-rejects, and the HEAD request below all resolve
// to undefined after the microtask drain.
return new Promise(r => setImmediate(() => r(undefined)));
},
});
process.send(server.url.href);
`,
});

const { promise, resolve, reject } = Promise.withResolvers<string>();
await using proc = Bun.spawn({
cmd: [bunExe(), "server.js"],
cwd: String(dir),
env: bunEnv,
stdout: "ignore",
stderr: "pipe",
ipc(message) {
resolve(message);
},
});
// Drain stderr concurrently, and fail fast if the server dies before the
// URL handshake instead of hanging until the test timeout.
const stderrPromise = proc.stderr.text();
proc.exited.then(async code => {
reject(new Error(`server exited (${code}) before sending its URL\n${await stderrPromise.catch(() => "")}`));
});

const url = await promise;

// Sync, already-settled, and deferred resolutions to a non-Response, plus a
// rejected fetch() promise routed through error(), all respond 500.
for (const pathname of [
"/sync",
"/already-settled",
"/already-settled-null",
"/deferred",
"/deferred-null",
"/fetch-rejects",
]) {
const res = await fetch(new URL(pathname, url));
const body = await res.text();
expect({ pathname, status: res.status, body }).toEqual({
pathname,
status: 500,
body: "Something went wrong!",
});
}

// A deferred error() that does return a Response still renders it.
{
const res = await fetch(new URL("/deferred-response", url));
const body = await res.text();
expect({ status: res.status, body }).toEqual({ status: 503, body: "handled" });
}

// A HEAD request on the error path responds 500 but must write no body bytes
// (RFC 9110 §9.3.2): a stray body would desync the next keep-alive response.
{
const raw = await headThenGet(url, "/deferred", "/ok");
const headStatus = Number(raw.match(/^HTTP\/1\.\d (\d+)/)?.[1] ?? 0);
expect(headStatus).toBe(500);
// The keep-alive GET afterward still gets its clean response...
expect(raw).toContain("ok-marker");
// ...and the HEAD wrote no body (a stray 500 page would appear inline).
expect(raw).not.toContain("Something went wrong!");
}

proc.kill();
const stderr = await stderrPromise;
// Each deferred path reports its own original error (matched at a line
// boundary so "/deferred" does not also satisfy "/deferred-null")...
expect(stderr).toMatch(/\/deferred(?:\n|$)/);
expect(stderr).toMatch(/\/deferred-null(?:\n|$)/);
expect(stderr).toMatch(/\/fetch-rejects(?:\n|$)/);
// ...and NOT fetch's invalid-return diagnostic for error()'s value.
expect(stderr).not.toContain("Expected a Response object");
});

// The fix keys on is_error_promise_pending, so fetch()'s OWN deferred
// non-Response must keep the documented 204 + invalid-return diagnostic and
// must not be hijacked onto the error() 500 path.
it("a deferred fetch() resolving to a non-Response still responds 204 (#33137)", async () => {
using dir = tempDir("serve-fetch-deferred-204", {
"server.js": `
const server = Bun.serve({
port: 0,
development: false,
fetch(request) {
const { pathname } = new URL(request.url);
const value = pathname === "/null" ? null : undefined;
return new Promise(r => setImmediate(() => r(value)));
},
});
process.send(server.url.href);
`,
});

const { promise, resolve, reject } = Promise.withResolvers<string>();
await using proc = Bun.spawn({
cmd: [bunExe(), "server.js"],
cwd: String(dir),
env: bunEnv,
stdout: "ignore",
stderr: "pipe",
ipc(message) {
resolve(message);
},
});
const stderrPromise = proc.stderr.text();
proc.exited.then(async code => {
reject(new Error(`server exited (${code}) before sending its URL\n${await stderrPromise.catch(() => "")}`));
});

const url = await promise;

for (const pathname of ["/undefined", "/null"]) {
const res = await fetch(new URL(pathname, url));
const body = await res.text();
expect({ pathname, status: res.status, body }).toEqual({ pathname, status: 204, body: "" });
}

proc.kill();
const stderr = await stderrPromise;
// fetch's own deferred non-Response keeps the invalid-return diagnostic.
expect(stderr).toContain("Expected a Response object");
});

if (process.platform === "linux")
it("should use correct error when using a root range port(#7187)", () => {
expect(() => {
Expand Down
Loading