From 92ce40877aefc77e898f93fec472210a84aa2ac0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 02:37:41 +0000 Subject: [PATCH 1/3] Bun.serve: route a missing file to error() for HEAD like for GET A HEAD request for a Response whose body is Bun.file(missing) answered 200 with content-length: 0, while GET reached the error() handler (or the default 500). do_render_head_response sized the body through Blob::resolve_size(), whose stat deliberately tolerates a missing file and falls back to 0. Split resolve_file_stat into a fallible stat_file_store() plus the tolerant wrapper, and have the HEAD arm stat first and hand a failure to run_error_handler before any status or header is written. --- src/runtime/server/RequestContext.rs | 12 ++++++ src/runtime/webcore/Blob.rs | 49 ++++++++++--------------- test/js/bun/http/bun-serve-file.test.ts | 33 +++++++++++++++++ 3 files changed, 65 insertions(+), 29 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 094f34edc381..a5d0d1df58b5 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -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`. + 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 diff --git a/src/runtime/webcore/Blob.rs b/src/runtime/webcore/Blob.rs index 77c0b20b20df..170dfba18f60 100644 --- a/src/runtime/webcore/Blob.rs +++ b/src/runtime/webcore/Blob.rs @@ -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) { + // 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) -> bun_sys::Result<()> { // `Store::data_mut` encapsulates the raw-pointer deref under the // `RefPtr` 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()))? } - 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(()) } // ────────────────────────────────────────────────────────────────────────── diff --git a/test/js/bun/http/bun-serve-file.test.ts b/test/js/bun/http/bun-serve-file.test.ts index f21c68018c4d..410d303d8a4b 100644 --- a/test/js/bun/http/bun-serve-file.test.ts +++ b/test/js/bun/http/bun-serve-file.test.ts @@ -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(), + }); + } + // 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", () => { From c3c83f602c1d9b2341a3ee2249703f32844e67de Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 04:17:13 +0000 Subject: [PATCH 2/3] Blob: keep the tolerant stat path allocation-free; attach path/fd at the HEAD caller --- src/runtime/server/RequestContext.rs | 14 ++++++++++---- src/runtime/webcore/Blob.rs | 7 ++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index a5d0d1df58b5..206922cfffba 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -2662,10 +2662,16 @@ where // stat here so HEAD does the same instead of answering 200 // with `content-length: 0`. 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 { + let store = blob.store.get().as_ref().expect("file blob has a store"); + if let Err(err) = crate::webcore::blob::stat_file_store(store) { + let err = match &store.data.as_file().pathlike { + crate::webcore::node_types::PathOrFileDescriptor::Path(p) => { + err.with_path(p.slice()) + } + crate::webcore::node_types::PathOrFileDescriptor::Fd(fd) => { + err.with_fd(*fd) + } + }; this.run_error_handler(err.to_js(global_this)); return; } diff --git a/src/runtime/webcore/Blob.rs b/src/runtime/webcore/Blob.rs index 170dfba18f60..59d680ed886f 100644 --- a/src/runtime/webcore/Blob.rs +++ b/src/runtime/webcore/Blob.rs @@ -5964,7 +5964,8 @@ fn resolve_file_stat(store: &RefPtr) { } /// Stat a file-backed store and record size, mode, seekability and mtime on -/// it. The error carries the path or fd. +/// it. The error is the bare stat error; callers that surface it attach the +/// path or fd. pub(crate) fn stat_file_store(store: &RefPtr) -> bun_sys::Result<()> { // `Store::data_mut` encapsulates the raw-pointer deref under the // `RefPtr` liveness invariant; the caller holds the only ref across @@ -5973,9 +5974,9 @@ pub(crate) fn stat_file_store(store: &RefPtr) -> bun_sys::Result<()> { let stat = match &file.pathlike { PathOrFileDescriptor::Path(path) => { let mut buffer = bun_paths::path_buffer_pool::get(); - bun_sys::stat(path.slice_z(&mut buffer)).map_err(|err| err.with_path(path.slice()))? + bun_sys::stat(path.slice_z(&mut buffer))? } - PathOrFileDescriptor::Fd(fd) => bun_sys::fstat(*fd).map_err(|err| err.with_fd(*fd))?, + PathOrFileDescriptor::Fd(fd) => bun_sys::fstat(*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 From 379907b7574a7c30378b561da8cea480686dc0af Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 04:20:52 +0000 Subject: [PATCH 3/3] shorten two comments --- src/runtime/server/RequestContext.rs | 4 +--- src/runtime/webcore/Blob.rs | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 206922cfffba..7f567c0cb69f 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -2658,9 +2658,7 @@ 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`. + // A failed stat goes to `error()`, as the open does for GET. if blob.needs_to_read_file() { let store = blob.store.get().as_ref().expect("file blob has a store"); if let Err(err) = crate::webcore::blob::stat_file_store(store) { diff --git a/src/runtime/webcore/Blob.rs b/src/runtime/webcore/Blob.rs index 59d680ed886f..fbb3904ad58e 100644 --- a/src/runtime/webcore/Blob.rs +++ b/src/runtime/webcore/Blob.rs @@ -5963,9 +5963,7 @@ fn resolve_file_stat(store: &RefPtr) { let _ = stat_file_store(store); } -/// Stat a file-backed store and record size, mode, seekability and mtime on -/// it. The error is the bare stat error; callers that surface it attach the -/// path or fd. +/// Records size, mode, seekability and mtime on the store. The error has no path attached. pub(crate) fn stat_file_store(store: &RefPtr) -> bun_sys::Result<()> { // `Store::data_mut` encapsulates the raw-pointer deref under the // `RefPtr` liveness invariant; the caller holds the only ref across