Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2658,6 +2658,18 @@ where
); // TODO: properly propagate exception upwards
return;
}
// GET opens the file and reports a failure through `error()`;
// stat here so HEAD does the same instead of answering 200
// with `content-length: 0`.
Comment thread
robobun marked this conversation as resolved.
Resolved
if blob.needs_to_read_file() {
let stat = crate::webcore::blob::stat_file_store(
blob.store.get().as_ref().expect("file blob has a store"),
);
if let Err(err) = stat {
this.run_error_handler(err.to_js(global_this));
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
Expand Down
49 changes: 20 additions & 29 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5959,42 +5959,33 @@ fn window_size(current: SizeType, available: SizeType) -> SizeType {

/// resolve file stat like size, last_modified
fn resolve_file_stat(store: &RefPtr<Store>) {
// the file may not exist yet. That's okay.
let _ = stat_file_store(store);
}

/// Stat a file-backed store and record size, mode, seekability and mtime on
/// it. The error carries the path or fd.
pub(crate) fn stat_file_store(store: &RefPtr<Store>) -> bun_sys::Result<()> {
// `Store::data_mut` encapsulates the raw-pointer deref under the
// `RefPtr<Store>` liveness invariant; the caller holds the only ref across
// this call, so an exclusive borrow is sound.
let file = Store::data_mut(store).as_file_mut();
match &file.pathlike {
let stat = match &file.pathlike {
PathOrFileDescriptor::Path(path) => {
let mut buffer = bun_paths::path_buffer_pool::get();
match bun_sys::stat(path.slice_z(&mut buffer)) {
bun_sys::Result::Ok(stat) => {
file.max_size = if bun_sys::S::ISREG(stat.st_mode as _) || stat.st_size > 0 {
((stat.st_size.max(0)) as u64) as SizeType
} else {
MAX_SIZE
};
file.mode = stat.st_mode as bun_sys::Mode;
file.seekable = Some(bun_sys::S::ISREG(stat.st_mode as _));
file.last_modified = stat_to_js_mtime(&stat);
}
// the file may not exist yet. That's okay.
_ => {}
}
bun_sys::stat(path.slice_z(&mut buffer)).map_err(|err| err.with_path(path.slice()))?
Comment thread
robobun marked this conversation as resolved.
Resolved
}
PathOrFileDescriptor::Fd(fd) => match bun_sys::fstat(*fd) {
bun_sys::Result::Ok(stat) => {
file.max_size = if bun_sys::S::ISREG(stat.st_mode as _) || stat.st_size > 0 {
((stat.st_size.max(0)) as u64) as SizeType
} else {
MAX_SIZE
};
file.mode = stat.st_mode as bun_sys::Mode;
file.seekable = Some(bun_sys::S::ISREG(stat.st_mode as _));
file.last_modified = stat_to_js_mtime(&stat);
}
_ => {}
},
}
PathOrFileDescriptor::Fd(fd) => bun_sys::fstat(*fd).map_err(|err| err.with_fd(*fd))?,
};
file.max_size = if bun_sys::S::ISREG(stat.st_mode as _) || stat.st_size > 0 {
((stat.st_size.max(0)) as u64) as SizeType
} else {
MAX_SIZE
};
file.mode = stat.st_mode as bun_sys::Mode;
file.seekable = Some(bun_sys::S::ISREG(stat.st_mode as _));
file.last_modified = stat_to_js_mtime(&stat);
Ok(())
}

// ──────────────────────────────────────────────────────────────────────────
Expand Down
33 changes: 33 additions & 0 deletions test/js/bun/http/bun-serve-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,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(),
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// HEAD used to skip 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
Loading