Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 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
107 changes: 57 additions & 50 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2564,10 +2564,13 @@ where
let body_decides_framing = {
let body_value = response.get_body_value();
body_value.to_blob_if_possible();
!matches!(
body_value,
Body::Value::Used | Body::Value::Null | Body::Value::Empty | Body::Value::Error(_)
)
// A used or errored body reaches `error()`, as it does for GET.
if matches!(body_value, Body::Value::Used | Body::Value::Error(_)) {
let js_err = Self::take_unsendable_body_error(body_value, global_this);
this.run_error_handler(js_err);
return;
}
!matches!(body_value, Body::Value::Null | Body::Value::Empty)
};
// `fast_get`/`fast_has` take `&mut self` (FFI shim), so use the `_mut`
// accessor — `get_fetch_headers()` and `get_init_headers()` alias the
Expand Down Expand Up @@ -2609,22 +2612,10 @@ where
// handler-supplied Content-Length / Transfer-Encoding header)
let body_value = response.get_body_value();
match body_value {
Body::Value::InternalBlob(_) | Body::Value::WTFStringImpl(_) => {
let mut blob = body_value.use_as_any_blob_allow_non_utf8_string();
let size = blob.size();
this.render_metadata();

if size == crate::webcore::blob::MAX_SIZE {
resp.write_header_int(b"content-length", 0);
} else {
resp.write_header_int(b"content-length", size as u64);
}
this.end_without_body(this.should_close_connection());
blob.detach();
}

Body::Value::Blob(blob) => {
if shim::blob_is_s3(blob) {
Body::Value::InternalBlob(_) | Body::Value::WTFStringImpl(_) | Body::Value::Blob(_) => {
if let Body::Value::Blob(blob) = body_value
&& shim::blob_is_s3(blob)
{
// we need to read the size asynchronously
// in this case should always be a redirect so should not hit this path, but in case we change it in the future lets handle it
// Ref for the S3 stat; adopted and released by
Expand Down Expand Up @@ -2658,18 +2649,31 @@ where
); // TODO: properly propagate exception upwards
return;
}
// Size the blob *before* `render_metadata()`: it re-fetches the
// Response from `response_weakref`, so no borrow of the Response
// (here, `blob`) may still be live across it. Nothing is written
// to the socket in between, so the wire output is unchanged.
blob.resolve_size();
let blob_size = blob.size.get();
// `render_metadata` reads `this.blob`; a Blob body stays on the Response.
let body = match body_value {
Body::Value::Blob(blob) => AnyBlob::Blob(blob.dupe()),
_ => body_value.use_as_any_blob_allow_non_utf8_string(),
};
this.blob.set(body);
// Same open + fstat as GET; `do_sendfile` ends HEAD after the headers.
if this.blob.get().needs_to_read_file() {
this.render_with_blob_from_body_value();
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}
let size = {
let blob = this.blob.get();
if let AnyBlob::Blob(blob) = blob {
blob.resolve_size();
}
blob.size()
};
this.render_metadata();
this.blob.with_mut(|b| b.detach());

if blob_size == crate::webcore::blob::MAX_SIZE {
if size == crate::webcore::blob::MAX_SIZE {
resp.write_header_int(b"content-length", 0);
} else {
resp.write_header_int(b"content-length", blob_size as u64);
resp.write_header_int(b"content-length", size as u64);
}
this.end_without_body(this.should_close_connection());
}
Expand All @@ -2685,7 +2689,8 @@ where
}
this.end_without_body(this.should_close_connection());
}
Body::Value::Used | Body::Value::Null | Body::Value::Empty | Body::Value::Error(_) => {
// `Used` and `Error` went to `error()` above.
Body::Value::Null | Body::Value::Empty | Body::Value::Used | Body::Value::Error(_) => {
this.render_metadata();
// SAFETY: FFI handle
resp.write_header_int(b"content-length", 0);
Expand Down Expand Up @@ -3097,6 +3102,27 @@ where
true
}

/// The `error()` argument for an errored or already-used body.
fn take_unsendable_body_error(
value: &mut Body::Value,
global_this: &JSGlobalObject,
) -> JSValue {
debug_assert!(matches!(value, Body::Value::Error(_) | Body::Value::Used));
if let Body::Value::Error(err_ref) = value {
let js_err = err_ref.to_js(global_this);
let _ = value.use_();
return js_err;
}
global_this
.err(
jsc::ErrorCode::BODY_ALREADY_USED,
format_args!(
"Response body already used. A Response body can only be sent once; create a new Response for each request."
),
)
.to_js()
}

pub(crate) fn do_render_with_body(
&self,
value: *mut Body::Value,
Expand All @@ -3114,30 +3140,11 @@ where
value.to_blob_if_possible();
let global_this = this.server().global_this();
match value {
Body::Value::Error(err_ref) => {
let js_err = err_ref.to_js(global_this);
let _ = value.use_();
if this.is_aborted_or_ended() {
return;
}
this.run_error_handler(js_err);
return;
}
// The handler returned a Response whose body was already used,
// usually the same Response object returned for a second request.
// A disturbed body is an error, not a silent empty 200.
Body::Value::Used => {
Body::Value::Error(_) | Body::Value::Used => {
let js_err = Self::take_unsendable_body_error(value, global_this);
if this.is_aborted_or_ended() {
return;
}
let js_err = global_this
.err(
jsc::ErrorCode::BODY_ALREADY_USED,
format_args!(
"Response body already used. A Response body can only be sent once; create a new Response for each request."
),
)
.to_js();
this.run_error_handler(js_err);
return;
}
Expand Down
147 changes: 147 additions & 0 deletions test/js/bun/http/bun-serve-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,71 @@ describe("Bun.file in serve routes", () => {
expect(res.status).toBe(200);
expect(await res.text()).toBe("Hello, World!");
});

// A file body from the fetch handler takes the same open + fstat path for
// HEAD as for GET (RFC 9110 §9.3.2): same Content-Type, same Range
// handling, and nothing after the header section on the wire.
it("HEAD of a file from the fetch handler sends GET's headers and no body", async () => {
using handlerServer = Bun.serve({
port: 0,
hostname: "127.0.0.1",
fetch: () => new Response(Bun.file(join(tempDir, "partial.txt"))),
});

// A raw socket, so that body bytes after the head would be visible.
const { promise: wireDone, resolve, reject } = Promise.withResolvers<string>();
let wire = "";
const client = await Bun.connect({
hostname: "127.0.0.1",
port: handlerServer.port,
socket: {
open(s) {
s.write("HEAD / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n");
},
data(_s, d) {
wire += Buffer.from(d).toString("latin1");
},
close() {
resolve(wire);
},
error(_s, e) {
reject(e);
},
},
});
const captured = await wireDone;
client.end();
const [head, ...afterHead] = captured.split("\r\n\r\n");
const header = (name: string) =>
head
.split("\r\n")
.find(line => line.toLowerCase().startsWith(name + ":"))
?.slice(name.length + 1)
.trim() ?? null;

const ranged = await fetch(handlerServer.url, { method: "HEAD", headers: { Range: "bytes=2-5" } });
const unsatisfiable = await fetch(handlerServer.url, { method: "HEAD", headers: { Range: "bytes=99-" } });

expect({
status: head.split("\r\n")[0],
contentType: header("content-type"),
contentLength: header("content-length"),
body: afterHead.join("\r\n\r\n"),
ranged: {
status: ranged.status,
contentLength: ranged.headers.get("Content-Length"),
contentRange: ranged.headers.get("Content-Range"),
},
unsatisfiable: { status: unsatisfiable.status, contentRange: unsatisfiable.headers.get("Content-Range") },
}).toEqual({
status: "HTTP/1.1 200 OK",
contentType: "text/plain;charset=utf-8",
contentLength: "16",
body: "",
ranged: { status: 206, contentLength: "4", contentRange: "bytes 2-5/16" },
unsatisfiable: { status: 416, contentRange: "bytes */16" },
});
});
});

describe.concurrent("Custom headers and status", () => {
Expand Down Expand Up @@ -794,6 +859,55 @@ describe("Bun.file in serve routes", () => {
}
});

// HEAD answers with the status GET would produce (RFC 9110 §9.3.2). A
// file body is resolved with open + fstat for both, so a missing file or
// a directory reaches error() on HEAD too, instead of a 200 sized from a
// bare stat (0 for a missing file, the inode size for a directory).
// The error() Response's headers come from its own body (a string for
// ENOENT, a typed Blob for EISDIR), not from the file that failed: no
// text/html from "nope.html", no filename from the directory.
it("HEAD of a missing file or a directory from the fetch handler fails like GET", async () => {
using handlerServer = Bun.serve({
port: 0,
fetch: req =>
new Response(Bun.file(new URL(req.url).pathname === "/dir" ? tempDir : join(tempDir, "nope.html"))),
error: e => {
const code = (e as NodeJS.ErrnoException).code;
return code === "EISDIR"
? new Response(new Blob([`err ${code}`], { type: "text/x-error" }), { status: 500 })
: new Response(`err ${code}`, { status: 500 });
},
});
const probe = async (pathname: string, method: string) => {
const res = await fetch(new URL(pathname, handlerServer.url), { method });
return {
status: res.status,
contentLength: res.headers.get("Content-Length"),
contentType: res.headers.get("Content-Type"),
contentDisposition: res.headers.get("Content-Disposition"),
text: await res.text(),
};
};
const error = (contentType: string, text: string) => ({
status: 500,
contentLength: "10",
contentType,
contentDisposition: null,
text,
});
expect({
"GET /missing": await probe("/missing", "GET"),
"HEAD /missing": await probe("/missing", "HEAD"),
"GET /dir": await probe("/dir", "GET"),
"HEAD /dir": await probe("/dir", "HEAD"),
}).toEqual({
"GET /missing": error("text/plain;charset=utf-8", "err ENOENT"),
"HEAD /missing": error("text/plain;charset=utf-8", ""),
"GET /dir": error("text/x-error", "err EISDIR"),
"HEAD /dir": error("text/x-error", ""),
});
});

it("preserves custom status for empty files", async () => {
const res = await fetch(new URL(`/empty-400.txt`, server.url));
expect(res.status).toBe(400);
Expand Down Expand Up @@ -862,6 +976,39 @@ describe("Bun.file in serve routes", () => {
expect(await res.text()).toBe(`fallback: ${server.url}will-be-deleted.txt`);
expect(handler.mock.calls.length).toBe(previousCallCount + 1);
});

it("a missing file returned from the fetch handler reaches error() for HEAD like for GET", async () => {
const missingPath = join(tempDir, "does-not-exist.txt");
const errors: { code?: string; path?: string }[] = [];
using handlerServer = Bun.serve({
port: 0,
fetch: () => new Response(Bun.file(missingPath)),
error(err) {
errors.push({ code: err.code, path: (err as ErrnoException).path });
return new Response("from error()", { status: 404, headers: { "X-From": "error" } });
},
});
const results: unknown[] = [];
for (const method of ["GET", "HEAD"]) {
const res = await fetch(handlerServer.url, { method });
results.push({
method,
status: res.status,
from: res.headers.get("X-From"),
contentLength: res.headers.get("Content-Length"),
body: await res.text(),
});
}
// HEAD used to ignore the failed stat and answer 200 with content-length: 0.
expect(results).toEqual([
{ method: "GET", status: 404, from: "error", contentLength: "12", body: "from error()" },
{ method: "HEAD", status: 404, from: "error", contentLength: "12", body: "" },
]);
expect(errors).toEqual([
{ code: "ENOENT", path: missingPath },
{ code: "ENOENT", path: missingPath },
]);
});
});

describe.concurrent("Content-Type detection", () => {
Expand Down
52 changes: 32 additions & 20 deletions test/js/bun/http/serve-reused-response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,30 +57,42 @@ describe("returning a Response with an already-used body", () => {
expect(await third.text()).toBe("handled");
expect(third.status).toBe(500);

expect(errors).toEqual([alreadyUsedError, alreadyUsedError]);
// HEAD reports the status GET reports (RFC 9110 §9.3.2), not an empty 200.
const head = await fetch(server.url, { method: "HEAD" });
expect(await head.text()).toBe("");
expect(head.status).toBe(500);

expect(errors).toEqual([alreadyUsedError, alreadyUsedError, alreadyUsedError]);
},
);

it("returning a Response whose body was consumed before returning calls the error handler", async () => {
const errors: unknown[] = [];
await using server = serve({
port: 0,
async fetch() {
const response = new Response("consumed before returning");
await response.text();
return response;
},
error(err: any) {
errors.push({ code: err.code, name: err.constructor.name, message: err.message });
return new Response("handled", { status: 500 });
},
});
it.each(["GET", "HEAD"])(
"returning a Response whose body was consumed before returning calls the error handler (%s)",
async method => {
const errors: unknown[] = [];
await using server = serve({
port: 0,
async fetch() {
// A Content-Length left on the used Response must not frame a HEAD 200 either.
const response = new Response("consumed before returning", { headers: { "Content-Length": "24" } });
Comment thread
robobun marked this conversation as resolved.
Resolved
await response.text();
return response;
},
error(err: any) {
errors.push({ code: err.code, name: err.constructor.name, message: err.message });
return new Response("handled", { status: 500 });
},
});

const response = await fetch(server.url);
expect(await response.text()).toBe("handled");
expect(response.status).toBe(500);
expect(errors).toEqual([alreadyUsedError]);
});
const response = await fetch(server.url, { method });
expect(await response.text()).toBe(method === "HEAD" ? "" : "handled");
expect({ status: response.status, contentLength: response.headers.get("Content-Length") }).toEqual({
status: 500,
contentLength: "7",
});
expect(errors).toEqual([alreadyUsedError]);
},
);

it("a Response that is not reused keeps working", async () => {
const error = jest.fn();
Expand Down
Loading