Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
31 changes: 31 additions & 0 deletions packages/bun-types/globals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2034,6 +2034,37 @@ interface BunFetchRequestInit extends RequestInit {
*/
decompress?: boolean;

/**
* Automatically compress the request body before sending and set the
* `Content-Encoding` request header accordingly.
*
* - `true` is equivalent to `"gzip"`.
* - A string selects the encoding with its default level.
* - An object selects the encoding and an explicit compression `level`.
*
* Only buffered bodies (string, `ArrayBuffer`/`TypedArray`, `Blob`) are
* compressed; `ReadableStream` bodies are sent as-is. If the request
* already has a `Content-Encoding` header, the body is left unchanged.
* This is a custom property that is not part of the Fetch API specification.
*
* @default false
* @example
* ```js
* await fetch("https://example.com/upload", {
* method: "POST",
* body: JSON.stringify(bigPayload),
* compress: "gzip",
* });
* ```
*/
compress?:
| boolean
| "gzip"
| "deflate"
| "br"
| "zstd"
| { encoding: "gzip" | "deflate" | "br" | "zstd"; level?: number };

/**
* The maximum number of redirects to follow when `redirect` is `"follow"`.
* If the response chain redirects more than this many times, the request
Expand Down
6 changes: 6 additions & 0 deletions src/http/AsyncHTTP.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,9 @@ fn make_client<'a>(
async_http_id,
hostname,
unix_socket_path: ZigStringSlice::EMPTY,
compress: None,
compressed_request_body: Vec::new(),
compressed_body_len: 0,
}
}

Expand Down Expand Up @@ -270,6 +273,7 @@ pub struct Options<'a> {
pub max_redirects: Option<u8>,
pub reject_unauthorized: Option<bool>,
pub tls_props: Option<SSLConfigSharedPtr>,
pub compress: Option<crate::compress_body::CompressOption>,
}

// ──────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -530,6 +534,7 @@ impl<'a> AsyncHTTP<'a> {
if let Some(val) = options.tls_props {
this.client.tls_props = Some(val);
}
this.client.compress = options.compress;

if let Some(proxy) = &this.http_proxy {
if let Some(auth) = build_proxy_authorization(proxy) {
Expand Down Expand Up @@ -768,6 +773,7 @@ impl<'a> AsyncHTTP<'a> {
// Clone-owned (allocated after `ptr::read`).
drop(core::mem::take(&mut client.redirect));
drop(core::mem::take(&mut client.prev_redirect));
drop(core::mem::take(&mut client.compressed_request_body));
Comment thread
claude[bot] marked this conversation as resolved.
if let Some(tunnel) = client.proxy_tunnel.take() {
// SAFETY: tunnel was created by ProxyTunnel::start
// (heap::alloc) and is refcounted; detach the socket
Expand Down
24 changes: 24 additions & 0 deletions src/http/HTTPThread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ pub struct CertCheckResumeMessage {

pub struct LibdeflateState {
pub decompressor: *mut bun_libdeflate_sys::libdeflate::Decompressor,
pub compressor: *mut bun_libdeflate_sys::libdeflate::Compressor,
pub shared_buffer: [u8; 512 * 1024],
}

Expand All @@ -306,6 +307,28 @@ impl LibdeflateState {
// SAFETY: see INVARIANT above.
unsafe { &mut *self.decompressor }
}

/// Lazy libdeflate compressor at [`DEFAULT_DEFLATE_LEVEL`]; same lifetime
/// and aliasing invariants as [`decompressor_mut`].
///
/// [`DEFAULT_DEFLATE_LEVEL`]: crate::compress_body::DEFAULT_DEFLATE_LEVEL
/// [`decompressor_mut`]: Self::decompressor_mut
#[inline]
pub(crate) fn compressor_mut<'a>(
&mut self,
) -> &'a mut bun_libdeflate_sys::libdeflate::Compressor {
if self.compressor.is_null() {
self.compressor = bun_libdeflate_sys::libdeflate::Compressor::alloc(
crate::compress_body::DEFAULT_DEFLATE_LEVEL,
);
if self.compressor.is_null() {
bun_core::out_of_memory();
}
}
// SAFETY: just ensured non-null; HTTP-thread-only; separate C heap
// allocation disjoint from `shared_buffer`.
unsafe { &mut *self.compressor }
}
}

pub const REQUEST_BODY_SEND_STACK_BUFFER_SIZE: usize = 32 * 1024;
Expand Down Expand Up @@ -1049,6 +1072,7 @@ impl HttpThread {
let client = &mut (*nn.as_ptr()).async_http.client;
drop(core::mem::take(&mut client.redirect));
drop(core::mem::take(&mut client.prev_redirect));
drop(core::mem::take(&mut client.compressed_request_body));
if let Some(tunnel) = client.proxy_tunnel.take() {
(*tunnel.as_ptr()).detach_socket();
tunnel.deref();
Expand Down
6 changes: 6 additions & 0 deletions src/http/InternalState.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ pub struct InternalStateFlags {
/// check passed (and implicitly by `InternalState::reset()` on every
/// redirect hop / failure, so each hop re-parks independently).
pub is_waiting_for_cert_check: bool,
/// Set once `HTTPClient::compress_body_for_send` has run for this attempt.
/// Guards header-retry re-entries from compressing again. Cleared by
/// `reset()`/`init()` so each redirect/retry hop re-compresses from the
/// original uncompressed `original_request_body`.
pub body_compressed: bool,
}

impl InternalStateFlags {
Expand All @@ -88,6 +93,7 @@ impl InternalStateFlags {
resend_request_body_on_redirect: false,
clear_hostname_on_redirect: false,
is_waiting_for_cert_check: false,
body_compressed: false,
}
}
}
Expand Down
Loading
Loading