Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
5 changes: 4 additions & 1 deletion src/runtime/server/FileRoute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ impl FileRoute {
"expected blob not to be heap-allocated"
);
*body_value = BodyValue::Blob(blob.dupe());
let headers = headers_from(response.get_init_headers(), &blob);
let headers = bun_http_jsc::headers_jsc::from_fetch_headers(
response.get_init_headers(),
response.body_content_type(blob_content_type(&blob)),
);
let status_code = response.status_code();

return Ok(Some(RefPtr::new(FileRoute::new(
Expand Down
15 changes: 12 additions & 3 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3800,7 +3800,7 @@ where
};

let (content_type, needs_content_type, content_type_needs_free) =
get_content_type(response.get_init_headers_mut(), blob);
get_content_type(response, blob);
// NOTE: `MimeType` owns a `Cow<'static, [u8]>`; Drop handles the owned case.
// Hold the value past all reads below, then let it drop at scope end.
let _ct_guard = scopeguard::guard(content_type_needs_free, |_needs| {
Expand Down Expand Up @@ -4788,12 +4788,18 @@ impl<const DEBUG_MODE: bool> Flags<DEBUG_MODE> {
}
}

fn get_content_type(headers: Option<&mut FetchHeaders>, blob: &AnyBlob) -> (MimeType, bool, bool) {
/// `(content_type, needs_content_type, content_type_needs_free)` for framing
/// `blob`, the body already moved out of `response`. `needs_content_type` is
/// `false` when `do_write_headers` sends the handler's own Content-Type, and
/// when the handler deleted it ([`Response::headers_own_content_type`]): then
/// none is sent, but `content_type` still describes the body for
/// `autoset_filename`.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn get_content_type(response: &Response, blob: &AnyBlob) -> (MimeType, bool, bool) {
let mut needs_content_type = true;
let mut content_type_needs_free = false;

let content_type: MimeType = 'brk: {
if let Some(headers_) = headers {
if let Some(headers_) = response.get_init_headers_mut() {
if let Some(content) = headers_.fast_get(jsc::HTTPHeaderName::ContentType) {
needs_content_type = false;

Expand All @@ -4808,6 +4814,9 @@ fn get_content_type(headers: Option<&mut FetchHeaders>, blob: &AnyBlob) -> (Mime
drop(content_slice);
break 'brk mt;
}
if response.headers_own_content_type() {
needs_content_type = false;
}
}

if !blob.content_type().is_empty() {
Expand Down
10 changes: 4 additions & 6 deletions src/runtime/server/StaticRoute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,18 +214,16 @@ impl StaticRoute {
// Consuming the body left a plain `Blob` behind, which no longer implies
// the `text/plain` a string body carried. Record it on the response's own
// headers so re-registering the same `Response` serves the same type.
if was_string {
let text_mime = bun_http_types::MimeType::TEXT;
response.get_or_create_headers(global_this)?.put_default(
HTTPHeaderName::ContentType,
&bun_core::String::ascii(text_mime.value.as_ref()),
if was_string && !response.headers_own_content_type() {
response.put_default_content_type(
global_this,
bun_http_types::MimeType::TEXT.value.as_ref(),
)?;
}

let mut headers: Headers = bun_http_jsc::headers_jsc::from_fetch_headers(
response.get_init_headers(),
any_blob_content_type(&blob),
response.body_content_type(any_blob_content_type(&blob)),
);

// Generate ETag if not already present
Expand Down
96 changes: 75 additions & 21 deletions src/runtime/webcore/Response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,8 +367,9 @@ impl Response {
}

/// R-2 `JsCell` escape hatch — single-JS-thread invariant. Centralises the
/// `unsafe { self.init.get_mut() }` deref so the four call sites
/// ([`get_init_headers_mut`], [`header`], [`get_or_create_headers`],
/// `unsafe { self.init.get_mut() }` deref so the call sites
/// ([`get_init_headers_mut`], [`clone_init_headers`],
/// [`get_or_create_headers`], [`put_default_content_type`],
Comment thread
robobun marked this conversation as resolved.
Resolved
/// [`get_content_type`]) read it as a plain `&mut Init`.
///
/// # Safety (encapsulated)
Expand Down Expand Up @@ -604,13 +605,59 @@ impl Response {
&BunString::ascii(content_type),
global_this,
)?;
init.headers_own_content_type = true;
}
}
}

Ok(init.headers.as_mut().unwrap())
}

/// `put_default` a Content-Type on the (created if needed) header list and
/// hand ownership of the Content-Type to it.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn put_default_content_type(
&self,
global_this: &JSGlobalObject,
content_type: &[u8],
) -> JsResult<()> {
self.get_or_create_headers(global_this)?.put_default(
HTTPHeaderName::ContentType,
&BunString::ascii(content_type),
global_this,
)?;
self.init_mut().headers_own_content_type = true;
Ok(())
}

/// Whether this response's Content-Type comes from the header list alone.
/// `true` once the list has held one: supplied in the init, copied from a
/// typed body (`Blob` with a `type`, `FormData`, `URLSearchParams`,
/// `Bun.file()`), or set by `Response.json()`. If the list then has no
/// Content-Type the user deleted it, and deriving one from the body again
/// would undo that. While `false` (a string or untyped body, or headers
/// never materialized) the body may still supply one. Every reader of the
/// Content-Type (the `Bun.serve` send paths, `formData()`,
/// `WebAssembly.compileStreaming`) goes through [`body_content_type`] or
/// [`get_content_type`] so they agree.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[inline]
pub(crate) fn headers_own_content_type(&self) -> bool {
self.init.get().headers_own_content_type
}

/// The Content-Type that `body` (this response's body, which a server may
/// already have moved out) still contributes: `None` once the header list
/// owns the Content-Type, else `body_content_type` unless it is empty.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[inline]
pub(crate) fn body_content_type<'b>(
&self,
body_content_type: Option<&'b [u8]>,
) -> Option<&'b [u8]> {
if self.headers_own_content_type() {
return None;
}
body_content_type.filter(|content_type| !content_type.is_empty())
}

pub(crate) fn get_headers(this: &Self, global_this: &JSGlobalObject) -> JsResult<JSValue> {
Ok(this.get_or_create_headers(global_this)?.to_js(global_this))
}
Expand All @@ -624,14 +671,11 @@ impl Response {
}
}

if let BodyValue::Blob(blob) = self.body.get().value.get() {
let content_type = blob.content_type_slice();
if !content_type.is_empty() {
return Ok(Some(Utf8Bytes::Borrowed(content_type)));
}
}

Ok(None)
let from_body = match self.body.get().value.get() {
BodyValue::Blob(blob) => Some(blob.content_type_slice()),
_ => None,
};
Ok(self.body_content_type(from_body).map(Utf8Bytes::Borrowed))
}
}

Expand Down Expand Up @@ -927,13 +971,8 @@ impl Response {
}
}

let headers_ref = response.get_or_create_headers(global_this)?;
let json_mime = bun_http_types::MimeType::JSON;
headers_ref.put_default(
HTTPHeaderName::ContentType,
&BunString::ascii(json_mime.value.as_ref()),
global_this,
)?;
response
.put_default_content_type(global_this, bun_http_types::MimeType::JSON.value.as_ref())?;
// Disarm the body-reset guard: all fallible ops have succeeded.
let response = scopeguard::ScopeGuard::into_inner(response);
// Ownership transfers to the JSC wrapper (freed via `finalize`).
Expand Down Expand Up @@ -1154,17 +1193,20 @@ impl Response {
// Perform the only remaining fallible op BEFORE heap-allocating:
// doing it on stack locals lets `?` trigger the scopeguard and
// `init`'s drop glue and avoids leaking the heap allocation entirely.
if let BodyValue::Blob(blob) = body.value.get() {
if let Some(headers) = init.headers.as_deref_mut() {
if let Some(headers) = init.headers.as_deref_mut() {
let mut owns_content_type = headers.fast_has(HTTPHeaderName::ContentType);
if !owns_content_type && let BodyValue::Blob(blob) = body.value.get() {
let content_type = blob.content_type_slice();
if !content_type.is_empty() && !headers.fast_has(HTTPHeaderName::ContentType) {
if !content_type.is_empty() {
headers.put(
HTTPHeaderName::ContentType,
&BunString::ascii(content_type),
global_this,
)?;
owns_content_type = true;
}
}
init.headers_own_content_type = owns_content_type;
}

// Disarm: all fallible ops have succeeded.
Expand Down Expand Up @@ -1197,6 +1239,12 @@ pub struct Init {
pub(crate) status_code: u16,
pub(crate) status_text: BunString,
pub method: Method,
/// `headers` held a Content-Type when it was attached (the init supplied
/// one) or Bun has since put the body's type into it. From then on the
/// header list is the only source of this response's Content-Type: when a
/// server finds none there the user removed it, and the body's type must
/// not be derived again. See [`Response::headers_own_content_type`].
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) headers_own_content_type: bool,
}

impl Default for Init {
Expand All @@ -1206,6 +1254,7 @@ impl Default for Init {
status_code: 0,
status_text: BunString::EMPTY,
method: Method::GET,
headers_own_content_type: false,
}
}
}
Expand All @@ -1224,6 +1273,7 @@ impl Init {
status_code: self.status_code,
status_text: self.status_text.clone(),
method: self.method,
headers_own_content_type: self.headers_own_content_type,
})
}

Expand Down Expand Up @@ -1267,7 +1317,11 @@ impl Init {
// SAFETY: `as_direct` returned a live `*mut Response` owned by the
// JS wrapper cell; rooted by `response_init` for this call.
let resp = unsafe { &*resp };
return Ok(Some(resp.init.get().clone(global_this)?));
let mut init = resp.init.get().clone(global_this)?;
// The donor's flag describes the donor's body, not the one this
// init is about to be paired with.
Comment thread
robobun marked this conversation as resolved.
Resolved
init.headers_own_content_type = false;
return Ok(Some(init));
}
}

Expand Down
Loading
Loading