The headless browser for AI agents and web scraping
Resolve fetch responses before buffering their bodies
SGavrl3aa2f591bdc5
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 9039074a..af85deda 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -7759,6 +7759,13 @@ globalThis.fetch = async (input, init = {}) => {url: exposeRedirectMetadata ? (parsed.url || url) : (respType === "opaque" ? "" : url),redirected: exposeRedirectMetadata && !!parsed.redirected,});+ if (typeof parsed.bodyRid === 'number') {+ // ponytail: preserve bounded one-chunk bodies; incremental delivery needs+ // stream backpressure rather than eagerly queuing every network chunk.+ const promise = __obscuraCore.ops.op_fetch_body(parsed.bodyRid);+ promise.catch(() => {}); // An unread/cancelled body must not report an unhandled rejection.+ response._fetchBody = { promise, resource: { rid: parsed.bodyRid, consumers: 1 } };+ }if (parsed.requestId) {Object.defineProperty(response, "__obscuraRequestId", {value: parsed.requestId,@@ -8210,6 +8217,7 @@ if (typeof Response === 'undefined') {this._bodyNull = body === null || body === undefined;this._bodyStream = null;this._bodyUsed = false;+ this._fetchBody = null;}_consumeBody() {if (this._bodyUsed) throw new TypeError("Body is already consumed");@@ -8221,8 +8229,18 @@ if (typeof Response === 'undefined') {if (!this._bodyStream) {this._bodyStream = new ReadableStream({start: (controller) => {- if (this._bodyBytes.length) controller.enqueue(this._bodyBytes);- controller.close();+ const deliver = (bytes) => {+ if (bytes.length) controller.enqueue(bytes);+ controller.close();+ };+ if (this._fetchBody) this._fetchBody.promise.then(deliver, error => controller.error(error));+ else deliver(this._bodyBytes);+ },+ cancel: () => {+ this._bodyUsed = true;+ if (this._fetchBody && --this._fetchBody.resource.consumers === 0) {+ __obscuraCore.ops.op_try_close(this._fetchBody.resource.rid);+ }},});// bodyUsed flips the moment the stream is locked for reading@@ -8243,11 +8261,20 @@ if (typeof Response === 'undefined') {return this._bodyStream;}get bodyUsed() { return this._bodyUsed; }- async text() { this._consumeBody(); return _decodeBodyWithCharset(this._bodyBytes, this.headers); }- async json() { this._consumeBody(); return JSON.parse(await _decodeBodyWithCharset(this._bodyBytes, this.headers)); }- async arrayBuffer() { this._consumeBody(); return _arrayBufferFromBytes(this._bodyBytes); }- async blob() { this._consumeBody(); return new Blob([this._bodyBytes]); }- clone() { return new Response(this._bodyBytes, { status: this.status, statusText: this.statusText, headers: this.headers, type: this.type, url: this.url, redirected: this.redirected }); }+ async text() { this._consumeBody(); return _decodeBodyWithCharset(this._fetchBody ? await this._fetchBody.promise : this._bodyBytes, this.headers); }+ async json() { this._consumeBody(); return JSON.parse(await _decodeBodyWithCharset(this._fetchBody ? await this._fetchBody.promise : this._bodyBytes, this.headers)); }+ async arrayBuffer() { this._consumeBody(); return _arrayBufferFromBytes(this._fetchBody ? await this._fetchBody.promise : this._bodyBytes); }+ async blob() { this._consumeBody(); return new Blob([this._fetchBody ? await this._fetchBody.promise : this._bodyBytes]); }+ clone() {+ const copy = new Response(this._bodyNull ? null : this._bodyBytes, { status: this.status, statusText: this.statusText, headers: this.headers, type: this.type, url: this.url, redirected: this.redirected });+ if (this._fetchBody) {+ const promise = this._fetchBody.promise.then(bytes => bytes.slice());+ promise.catch(() => {});+ this._fetchBody.resource.consumers++;+ copy._fetchBody = { promise, resource: this._fetchBody.resource };+ }+ return copy;+ }static error() { return new Response(null, { status: 0 }); }static redirect(url, status) { return new Response(null, { status: status || 302, headers: { Location: url } }); }static json(data, init) { return new Response(JSON.stringify(data), { ...init, headers: { 'content-type': 'application/json', ...(init?.headers || {}) } }); }@@ -14849,7 +14876,9 @@ if (typeof ReadableStream === 'undefined') {};}cancel(reason) {+ if (this._state === "errored") return Promise.reject(this._error);this._queue.length = 0;+ if (this._state === "closed") return Promise.resolve();this._controller.close();try { return Promise.resolve(this._source.cancel?.(reason)); }catch (error) { return Promise.reject(error); }diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 77963b68..b510c0d2 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -7,6 +7,7 @@ use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};use deno_core::Extension;use deno_core::JsBuffer;use deno_core::OpState;+use deno_core::{AsyncResult, CancelFuture, CancelHandle, Resource};use deno_core::op2;use deno_core::v8;use obscura_dom::tree::{AttachShadowError, ShadowRootMode};@@ -679,6 +680,65 @@ async fn read_body_capped(Ok(buf)}+struct PageInFlightGuard(Arc<std::sync::atomic::AtomicU32>);+impl Drop for PageInFlightGuard {+ fn drop(&mut self) {+ self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);+ }+}++struct FetchBodyResource {+ body: RefCell<Option<AsyncResult<Vec<u8>>>>,+ cancel: Rc<CancelHandle>,+ opaque: bool,+}++impl Resource for FetchBodyResource {+ fn close(self: Rc<Self>) {+ self.cancel.cancel();+ self.body.borrow_mut().take();+ }+}++#[op2]+#[buffer]+async fn op_fetch_body(+ state: Rc<RefCell<OpState>>,+ rid: u32,+) -> Result<Vec<u8>, deno_error::JsErrorBox> {+ let resource = state.borrow().resource_table.get::<FetchBodyResource>(rid)+ .map_err(|error| deno_error::JsErrorBox::generic(error.to_string()))?;+ let body = resource.body.borrow_mut().take()+ .ok_or_else(|| deno_error::JsErrorBox::type_error("Body is already consumed"))?;+ let result = body.or_cancel(resource.cancel.clone()).await+ .map_err(|_| deno_error::JsErrorBox::generic("Response body was cancelled"));+ let closed = state.borrow_mut().resource_table.take_any(rid);+ if let Ok(resource) = closed {+ resource.close();+ }+ result?.map(|bytes| if resource.opaque { Vec::new() } else { bytes })+}++async fn fetch_body_result(+ state: &RefCell<OpState>,+ mut metadata: serde_json::Value,+ body: AsyncResult<Vec<u8>>,+ internal_load: bool,+) -> Result<String, deno_error::JsErrorBox> {+ if internal_load {+ let bytes = body.await?;+ metadata["body"] = serde_json::json!(String::from_utf8_lossy(&bytes));+ metadata["bodyBase64"] = serde_json::json!(BASE64.encode(&bytes));+ } else {+ let rid = state.borrow_mut().resource_table.add(FetchBodyResource {+ body: RefCell::new(Some(body)), cancel: CancelHandle::new_rc(),+ opaque: metadata["opaque"].as_bool().unwrap_or(false),+ });+ metadata["bodyRid"] = serde_json::json!(rid);+ }+ Ok(metadata.to_string())+}+/// Cap on the append-only `fetched_urls` asset list. A page can otherwise loop/// `fetch()`/XHR and grow it without bound on the process heap (where V8's/// heap-limit guard never sees it). It only feeds the CLI's `--dump assets`@@ -3206,12 +3266,6 @@ async fn op_fetch_url(}).to_string());}- struct PageInFlightGuard(Arc<std::sync::atomic::AtomicU32>);- impl Drop for PageInFlightGuard {- fn drop(&mut self) {- self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);- }- }page_in_flight.fetch_add(1, std::sync::atomic::Ordering::Relaxed);let _page_in_flight = PageInFlightGuard(page_in_flight);let credentials = FetchCredentials::parse(&credentials);@@ -3478,6 +3532,8 @@ async fn op_fetch_url(};if let Some(stealth) = stealth {return stealth_fetch_all(+ state.clone(),+ _page_in_flight,stealth,url.clone(),req_method.as_str().to_string(),@@ -3725,42 +3781,6 @@ async fn op_fetch_url(}}- let resp_bytes = read_body_capped(response, fetch_max_body_bytes()).await?;- let resp_body = String::from_utf8_lossy(&resp_bytes).to_string();- let resp_body_base64 = BASE64.encode(&resp_bytes);- if let Some(ref cbs) = callbacks {- if cbs.has_response_callbacks().await {- let resp = fetch_response(- current_url.as_str(),- status,- resp_headers.clone(),- resp_bytes.to_vec(),- redirected_from,- );- let info = RequestInfo {- url: resp.url.clone(),- method: current_method.as_str().to_string(),- headers: resp_headers.clone(),- resource_type: ResourceType::Fetch,- };- cbs.fire_response(&info, &resp).await;- }- }- record_js_network_completion(&state, JsNetworkEvent {- request_id: request_id.clone(), intercepted: was_intercepted,- url: current_url.clone(), method: current_method.as_str().to_string(), status,- response_headers: resp_headers.clone(), body_size: resp_bytes.len(),- timestamp: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default().as_secs_f64(),- }, &resp_body, false);-- tracing::debug!(- "op_fetch_url completed: {} {} ({} bytes)",- method,- url,- resp_body.len()- );-let opaque = !internal_load && mode == "no-cors" && crossed_origin;let script_headers = if opaque {HashMap::new()@@ -3768,17 +3788,45 @@ async fn op_fetch_url(visible_response_headers(&resp_headers, final_is_cross_origin, credentials)};- Ok(serde_json::json!({+ let metadata = serde_json::json!({"status": if opaque { 0 } else { status },- "body": if opaque { String::new() } else { resp_body },- "bodyBase64": if opaque { String::new() } else { resp_body_base64 },"requestId": request_id,"url": current_url,"redirected": redirected,"opaque": opaque,"headers": script_headers,- })- .to_string())+ });+ // A resource must not form an ownership cycle with its OpState table.+ let body_state = Rc::downgrade(&state);+ let body = Box::pin(async move {+ let _page_in_flight = _page_in_flight;+ let resp_bytes = read_body_capped(response, fetch_max_body_bytes()).await?;+ if let Some(ref cbs) = callbacks {+ if cbs.has_response_callbacks().await {+ let resp = fetch_response(+ current_url.as_str(), status, resp_headers.clone(),+ resp_bytes.to_vec(), redirected_from,+ );+ let info = RequestInfo {+ url: resp.url.clone(), method: current_method.as_str().to_string(),+ headers: resp_headers.clone(), resource_type: ResourceType::Fetch,+ };+ cbs.fire_response(&info, &resp).await;+ }+ }+ if let Some(state) = body_state.upgrade() {+ record_js_network_completion(&state, JsNetworkEvent {+ request_id, intercepted: was_intercepted,+ url: current_url, method: current_method.as_str().to_string(), status,+ response_headers: resp_headers, body_size: resp_bytes.len(),+ timestamp: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default().as_secs_f64(),+ }, &String::from_utf8_lossy(&resp_bytes), false);+ }+ tracing::debug!("op_fetch_url completed: {} {} ({} bytes)", method, url, resp_bytes.len());+ Ok(resp_bytes)+ });+ fetch_body_result(&state, metadata, body, internal_load).await}/// Assemble a `Response` for the on_response interception callbacks from the@@ -3808,6 +3856,8 @@ fn fetch_response(/// Network.getResponseBody buffer here; that is a follow-up for stealth fetches.#[cfg(feature = "stealth")]async fn stealth_fetch_all(+ state: Rc<RefCell<OpState>>,+ page_in_flight: PageInFlightGuard,stealth: Arc<StealthHttpClient>,url: String,method: String,@@ -3833,7 +3883,7 @@ async fn stealth_fetch_all(.unwrap_or(false);let cookie_initiator = url::Url::parse(&page_origin).ok();- let (status, resp_headers, resp_bytes): (u16, HashMap<String, String>, Vec<u8>) = loop {+ let response = loop {let parsed_current = match url::Url::parse(¤t_url) {Ok(u) => u,Err(_) => {@@ -3866,19 +3916,20 @@ async fn stealth_fetch_all(}});let r = stealth- .send_single_with_context(+ .send_single_headers_with_context(¤t_method,&parsed_current,&req_headers,¤t_body,cookie_context,credentials_allowed,+ fetch_max_body_bytes().min(64 * 1024 * 1024),).await.map_err(|e| deno_error::JsErrorBox::generic(e.to_string()))?;if !(300..400).contains(&r.status) {- break (r.status, r.headers, r.body);+ break r;}// Cross-origin redirect responses must pass the CORS check too, before// the redirect is followed (#973).@@ -3906,11 +3957,11 @@ async fn stealth_fetch_all(}}let Some(location) = r.headers.get("location").cloned() else {- break (r.status, r.headers, r.body);+ break r;};let next_url = match parsed_current.join(&location) {Ok(u) => u,- Err(_) => break (r.status, r.headers, r.body),+ Err(_) => break r,};// Re-validate every redirect target against the SSRF policy, matching// op_fetch_url (GHSA-8v6v-g4rh-jmcm).@@ -3944,6 +3995,8 @@ async fn stealth_fetch_all(current_url = next_url.to_string();};+ let status = response.status;+ let resp_headers = response.headers;let final_is_cross_origin = request_origin(¤t_url).map(|request_origin| request_origin != page_origin).unwrap_or(false);@@ -3976,27 +4029,6 @@ async fn stealth_fetch_all(}}- let resp_body = String::from_utf8_lossy(&resp_bytes).to_string();- let resp_body_base64 = BASE64.encode(&resp_bytes);- if let Some(ref cbs) = callbacks {- if cbs.has_response_callbacks().await {- let resp = fetch_response(- current_url.as_str(),- status,- resp_headers.clone(),- resp_bytes.clone(),- redirected_from,- );- let info = RequestInfo {- url: resp.url.clone(),- method: current_method.clone(),- headers: resp_headers.clone(),- resource_type: ResourceType::Fetch,- };- cbs.fire_response(&info, &resp).await;- }- }-let opaque = !internal_load && mode == "no-cors" && crossed_origin;let script_headers = if opaque {HashMap::new()@@ -4004,16 +4036,33 @@ async fn stealth_fetch_all(visible_response_headers(&resp_headers, final_is_cross_origin, credentials)};- Ok(serde_json::json!({+ let metadata = serde_json::json!({"status": if opaque { 0 } else { status },- "body": if opaque { String::new() } else { resp_body },- "bodyBase64": if opaque { String::new() } else { resp_body_base64 },"url": current_url,"redirected": redirects_followed > 0,"opaque": opaque,"headers": script_headers,- })- .to_string())+ });+ let body = Box::pin(async move {+ let _page_in_flight = page_in_flight;+ let resp_bytes = response.body.await+ .map_err(|error| deno_error::JsErrorBox::generic(error.to_string()))?;+ if let Some(ref cbs) = callbacks {+ if cbs.has_response_callbacks().await {+ let resp = fetch_response(+ current_url.as_str(), status, resp_headers.clone(),+ resp_bytes.clone(), redirected_from,+ );+ let info = RequestInfo {+ url: resp.url.clone(), method: current_method,+ headers: resp_headers, resource_type: ResourceType::Fetch,+ };+ cbs.fire_response(&info, &resp).await;+ }+ }+ Ok(resp_bytes)+ });+ fetch_body_result(&state, metadata, body, internal_load).await}pub(crate) fn glob_match(pattern: &str, url: &str) -> bool {@@ -6405,6 +6454,7 @@ pub fn build_extension() -> Extension {op_runtime_events_enabled(),op_console_msg(),op_fetch_url(),+ op_fetch_body(),op_get_cookies(),op_set_cookie(),op_navigate(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 7b4aa2a3..2213f071 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -18649,6 +18649,139 @@ mod tests {);}+ async fn held_fetch_body_runtime() -> (+ ObscuraJsRuntime, tokio::sync::oneshot::Sender<()>,+ tokio::task::JoinHandle<std::io::Result<()>>,+ ) {+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let target = format!("http://{}/resource", listener.local_addr().unwrap());+ let (release, body_release) = tokio::sync::oneshot::channel();+ let server = tokio::spawn(async move {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut request = [0u8; 4096];+ stream.read(&mut request).await.unwrap();+ stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\+ Access-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n").await.unwrap();+ body_release.await.unwrap();+ stream.write_all(b"tail").await+ });+ let mut rt = setup_runtime("<html><body></body></html>");+ let cookie_jar = std::sync::Arc::new(obscura_net::CookieJar::new());+ rt.set_http_client(std::sync::Arc::new(+ obscura_net::ObscuraHttpClient::with_full_options(+ cookie_jar.clone(), None, true,+ ),+ ));+ #[cfg(feature = "stealth")]+ rt.set_stealth_client(std::sync::Arc::new(+ obscura_net::StealthHttpClient::with_proxy(cookie_jar, None, true),+ ));+ rt.execute_script("header-first-fetch", &format!(+ "globalThis.headerResponse = null; fetch({target:?}).then(r => headerResponse = r);"+ )).unwrap();+ (rt, release, server)+ }++ #[tokio::test(flavor = "current_thread")]+ async fn fetch_resolves_headers_before_the_response_body_finishes() {+ let (mut rt, release, server) = held_fetch_body_runtime().await;+ let headers_first = rt.resolve_promises_until(+ |rt| rt.evaluate("headerResponse !== null").unwrap() == serde_json::json!(true),+ 2_000,+ ).await;+ let pending_body = rt.has_pending_network_requests();+ // Release and verify the bytes even on RED, so the fixture never hangs.+ release.send(()).unwrap();+ let result = rt.call_function_on_for_cdp(+ "async () => { const r = headerResponse || await new Promise(resolve => { \+ const check = () => headerResponse ? resolve(headerResponse) : setTimeout(check, 1); \+ check(); }); const unread = !r.bodyUsed; \+ return { status: r.status, unread, text: await r.text(), used: r.bodyUsed }; }",+ None, &[], true, true,+ ).await.unwrap();+ server.await.unwrap().unwrap();+ assert_eq!(result.value, Some(serde_json::json!({+ "status": 200, "unread": true, "text": "tail", "used": true,+ })));+ assert!(headers_first, "fetch must expose headers while the body is still held");+ assert!(pending_body, "headers must not mark the unfinished body as network-idle");+ assert!(!rt.has_pending_network_requests());+ }++ #[tokio::test(flavor = "current_thread")]+ async fn repeated_fetch_clone_cancellation_preserves_the_other_body() {+ let (mut rt, release, server) = held_fetch_body_runtime().await;+ let headers_first = rt.resolve_promises_until(+ |rt| rt.evaluate("headerResponse !== null").unwrap() == serde_json::json!(true),+ 2_000,+ ).await;+ if headers_first {+ assert_eq!(rt.evaluate("(() => { \+ const copy = headerResponse.clone(); const stream = copy.body; \+ stream.cancel(); stream.cancel(); \+ return [headerResponse.bodyUsed, copy.bodyUsed]; })()").unwrap(),+ serde_json::json!([false, true]));+ }+ release.send(()).unwrap();+ let result = rt.call_function_on_for_cdp(+ "async () => await headerResponse.text()", None, &[], true, true,+ ).await.unwrap();+ let _ = server.await.unwrap();+ assert_eq!(result.value, Some(serde_json::json!("tail")));+ assert!(headers_first);+ assert!(!rt.has_pending_network_requests());+ }++ #[tokio::test(flavor = "current_thread")]+ async fn fetch_clone_body_bytes_are_independent() {+ let (mut rt, release, server) = held_fetch_body_runtime().await;+ let headers_first = rt.resolve_promises_until(+ |rt| rt.evaluate("headerResponse !== null").unwrap() == serde_json::json!(true),+ 2_000,+ ).await;+ if headers_first {+ rt.execute_script("clone-held-body", "globalThis.clonedResponse = headerResponse.clone();").unwrap();+ }+ release.send(()).unwrap();+ let result = rt.call_function_on_for_cdp(+ "async () => { const reader = headerResponse.body.getReader(); \+ const { value } = await reader.read(); value[0] = 88; \+ return [new TextDecoder().decode(value), await clonedResponse.text()]; }",+ None, &[], true, true,+ ).await.unwrap();+ server.await.unwrap().unwrap();+ assert_eq!(result.value, Some(serde_json::json!(["Xail", "tail"])));+ assert!(headers_first);+ assert!(!rt.has_pending_network_requests());+ }++ #[tokio::test(flavor = "current_thread")]+ async fn cancelling_all_fetch_clones_releases_the_pending_body() {+ let (mut rt, release, server) = held_fetch_body_runtime().await;+ let headers_first = rt.resolve_promises_until(+ |rt| rt.evaluate("headerResponse !== null").unwrap() == serde_json::json!(true),+ 2_000,+ ).await;+ if headers_first {+ let result = rt.call_function_on_for_cdp(+ "async () => { const copy = headerResponse.clone(); \+ await copy.body.cancel(); await headerResponse.body.cancel(); \+ return [headerResponse.bodyUsed, copy.bodyUsed]; }",+ None, &[], true, true,+ ).await.unwrap();+ assert_eq!(result.value, Some(serde_json::json!([true, true])));+ }+ let cancelled = rt.resolve_promises_until(+ |rt| !rt.has_pending_network_requests(), 2_000,+ ).await;+ release.send(()).unwrap();+ let _ = server.await.unwrap();+ assert!(headers_first);+ assert!(cancelled, "cancelling every clone must release the held network body");+ }+fn cors_preflight_runtime() -> (ObscuraJsRuntime, String, std::sync::mpsc::Receiver<String>) {let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let address = listener.local_addr().unwrap();diff --git a/crates/obscura-net/src/wreq_client.rs b/crates/obscura-net/src/wreq_client.rsindex 550dd18e..e2964799 100644--- a/crates/obscura-net/src/wreq_client.rs+++ b/crates/obscura-net/src/wreq_client.rs@@ -193,6 +193,14 @@ pub struct StealthHttpClient {pub in_flight: Arc<std::sync::atomic::AtomicU32>,}+/// Scripted fetch exposes these headers before consuming the bounded body.+#[cfg(feature = "stealth")]+pub struct StealthResponseHeaders {+ pub status: u16,+ pub headers: HashMap<String, String>,+ pub body: futures_util::future::BoxFuture<'static, Result<Vec<u8>, ObscuraNetError>>,+}+#[cfg(feature = "stealth")]impl StealthHttpClient {pub fn new(cookie_jar: Arc<CookieJar>) -> Self {@@ -493,14 +501,32 @@ impl StealthHttpClient {cookie_context: Option<SameSiteContext>,store_cookies: bool,) -> Result<Response, ObscuraNetError> {+ let response = self.send_single_headers_with_context(+ method, url, headers, body, cookie_context, store_cookies, 64 * 1024 * 1024,+ ).await?;+ Ok(Response {+ url: url.clone(), status: response.status, headers: response.headers,+ body: response.body.await?, redirected_from: Vec::new(),+ })+ }++ /// Preserve request policy and cookie handling while deferring body reads.+ pub async fn send_single_headers_with_context(+ &self,+ method: &str,+ url: &Url,+ headers: &HashMap<String, String>,+ body: &[u8],+ cookie_context: Option<SameSiteContext>,+ store_cookies: bool,+ max_body_bytes: usize,+ ) -> Result<StealthResponseHeaders, ObscuraNetError> {if is_tracker_blocked(url, self.block_trackers) {tracing::debug!("Blocked tracker: {}", url);- return Ok(Response {+ return Ok(StealthResponseHeaders {status: 0,- url: url.clone(),headers: HashMap::new(),- body: Vec::new(),- redirected_from: Vec::new(),+ body: Box::pin(async { Ok(Vec::new()) }),});}@@ -543,15 +569,14 @@ impl StealthHttpClient {.iter().map(|(k, v)| (k.as_str().to_lowercase(), v.to_str().unwrap_or("").to_string())).collect();- let resp_body = read_wreq_body_limited(resp, url, 64 * 1024 * 1024).await?;- drop(in_flight);-- Ok(Response {- url: url.clone(),+ let body_url = url.clone();+ Ok(StealthResponseHeaders {status: status.as_u16(),headers: response_headers,- body: resp_body,- redirected_from: Vec::new(),+ body: Box::pin(async move {+ let _in_flight = in_flight;+ read_wreq_body_limited(resp, &body_url, max_body_bytes).await+ }),})}