diff --git a/moli-core/tests/fixtures/runtime/fetch_body_native.js b/moli-core/tests/fixtures/runtime/fetch_body_native.js new file mode 100644 index 00000000000..b445d93596f --- /dev/null +++ b/moli-core/tests/fixtures/runtime/fetch_body_native.js @@ -0,0 +1,165 @@ +async function runFetchBodyNativeProbe(scenario) { + const errors = []; + const check = (condition, message) => { if (!condition) errors.push(message); }; + const encode = value => new TextEncoder().encode(value); + const own = (value, name) => Object.prototype.hasOwnProperty.call(value, name); + const closed = chunk => new ReadableStream({ start(c) { c.enqueue(chunk); c.close(); } }); + const makeBody = (type, stream, mime = "text/plain") => type === "Response" + ? new Response(stream, { headers: { "Content-Type": mime } }) + : new Request("https://example.test/body", { + method: "POST", body: stream, duplex: "half", headers: { "Content-Type": mime } + }); + const rejectWith = async (promise, predicate, name) => { + try { await promise; errors.push(name + " resolved"); } + catch (error) { check(predicate(error), name + " wrong rejection: " + String(error)); } + }; + + if (scenario === "then") { + for (const type of ["Response", "Request"]) { + for (const injected of [{ done: false, value: encode("bye") }, + { done: false, value: undefined }, undefined, 8.2]) { + const body = makeBody(type, closed(encode("hello"))); + let calls = 0; + Object.prototype.then = resolve => { + ++calls; + delete Object.prototype.then; + resolve(injected); + }; + try { + check(await body.text() === "hello", type + " injected read result"); + check(calls === 0, type + " exposed internal thenable"); + } catch (error) { + errors.push(type + " inherited then: " + String(error)); + } finally { delete Object.prototype.then; } + } + for (const method of ["text", "json", "bytes", "arrayBuffer", "blob", "formData"]) { + const payload = method === "json" ? '{"answer":42}' : method === "formData" ? "answer=42" : "hello"; + const body = makeBody(type, closed(encode(payload)), "application/x-www-form-urlencoded"); + let reads = 0; + let values = 0; + Object.defineProperty(Object.prototype, "then", { configurable: true, get() { + if (own(this, "done") && own(this, "value")) { ++reads; throw new Error("internal read leaked"); } + if (!(this instanceof Promise)) ++values; + return undefined; + } }); + let value; + try { value = await body[method](); } + catch (error) { errors.push(type + "." + method + " then getter: " + String(error)); } + finally { delete Object.prototype.then; } + check(reads === 0, type + "." + method + " exposed read result"); + check(values === (method === "text" ? 0 : 1), type + "." + method + " result assimilation count " + values); + if (method === "text") check(value === payload, type + " text bytes"); + if (method === "json") check(value?.answer === 42, type + " json bytes"); + if (method === "bytes") check(value instanceof Uint8Array && new TextDecoder().decode(value) === payload, type + " bytes value"); + if (method === "arrayBuffer") check(value instanceof ArrayBuffer && new TextDecoder().decode(value) === payload, type + " arrayBuffer value"); + if (method === "blob") check(value instanceof Blob && await value.text() === payload, type + " blob value"); + if (method === "formData") check(value instanceof FormData && value.get("answer") === "42", type + " formData value"); + } + } + // Public reader results still undergo the Promise resolution procedure. + const reader = closed(encode("hello")).getReader(); + const replacement = { public: true }; + Object.prototype.then = resolve => { delete Object.prototype.then; resolve(replacement); }; + try { check(await reader.read() === replacement, "public reader thenable semantics changed"); } + finally { delete Object.prototype.then; } + } else if (scenario === "chunks") { + for (const type of ["Response", "Request"]) { + const chunk = encode("_hello_").subarray(1, 6); + let getters = 0; + for (const key of [Symbol.toStringTag, "byteLength", "constructor"]) { + Object.defineProperty(chunk, key, { get() { ++getters; throw new Error("chunk getter"); } }); + } + try { check(await makeBody(type, closed(chunk)).text() === "hello", type + " offset bytes"); } + catch (error) { errors.push(type + " valid chunk: " + String(error)); } + check(getters === 0, type + " read chunk properties"); + for (const invalid of [undefined, [], new Uint8ClampedArray([1]), + new DataView(new ArrayBuffer(1)), new Proxy(encode("x"), {}), + { [Symbol.toStringTag]: "Uint8Array", byteLength: 1, 0: 120 }]) { + await rejectWith(makeBody(type, closed(invalid)).text(), e => e instanceof TypeError, type + " invalid chunk"); + } + } + for (const phase of ["pull", "enqueue"]) { + const chunk = encode("hello"); + let pulled = false; + const source = new ReadableStream({ + start(c) { if (phase === "pull") c.enqueue(chunk); }, + pull(c) { + if (pulled) return; + pulled = true; + if (phase === "enqueue") c.enqueue(chunk); + chunk.fill(120); + c.close(); + } + }, { highWaterMark: 0 }); + check(await new Response(source).text() === "hello", "chunk copy before " + phase + " mutation"); + } + const chunk = encode("hello"); + let controller; + const response = new Response(new ReadableStream({ start(c) { controller = c; } })); + const pending = response.text(); + controller.enqueue(chunk); + structuredClone(chunk.buffer, { transfer: [chunk.buffer] }); + controller.close(); + try { check(await pending === "hello", "chunk copy before detachment"); } + catch (error) { errors.push("detached after enqueue: " + String(error)); } + const count = 12000; + const many = new ReadableStream({ start(c) { + for (let i = 0; i < count; ++i) c.enqueue(new Uint8Array([i % 251])); + c.close(); + } }); + const bytes = await new Response(many).bytes(); + check(bytes.length === count && bytes.every((value, index) => value === index % 251), "queued chunk order or stack depth"); + const byob = new ReadableStream({ type: "bytes", autoAllocateChunkSize: 8, pull(c) { + c.byobRequest.view.set(encode("hello")); + c.byobRequest.respond(5); + c.close(); + } }); + check(await new Response(byob).text() === "hello", "auto allocated byte reader"); + } else if (scenario === "errors") { + for (const type of ["Response", "Request"]) { + for (const reason of [undefined, Symbol("reason"), { error: "original" }]) { + for (const phase of ["start", "pull", "after-chunk"]) { + const stream = new ReadableStream({ + start(c) { if (phase === "start") c.error(reason); }, + pull(c) { + if (phase === "after-chunk") c.enqueue(encode("partial")); + c.error(reason); + } + }); + const body = makeBody(type, stream); + await rejectWith(body.text(), e => e === reason, type + " " + phase); + check(body.bodyUsed && body.body.locked, type + " error consumption access state"); + } + } + await rejectWith(makeBody(type, closed(encode("{"))).json(), e => e instanceof SyntaxError, type + " JSON parse error"); + await rejectWith(makeBody(type, closed(encode("hello"))).formData(), e => e instanceof TypeError, type + " invalid form MIME"); + const body = makeBody(type, closed(encode("hello"))); + const first = body.text(); + check(body.bodyUsed && body.body.locked, type + " synchronous consumption access state"); + await rejectWith(body.text(), e => e instanceof TypeError, type + " repeated consumption"); + check(await first === "hello", type + " first consumption"); + } + } else if (scenario === "intrinsics") { + for (const method of ["text", "json", "bytes", "arrayBuffer", "blob", "formData"]) { + const payload = method === "json" ? '{"answer":42}' : method === "formData" ? "answer=42" : "hello"; + const body = makeBody("Response", closed(encode(payload)), "application/x-www-form-urlencoded"); + const saved = Object.fromEntries(["TextDecoder", "Uint8Array", "Blob", "Response"].map(key => [key, globalThis[key]])); + const parse = JSON.parse; + let value; + const poison = () => { throw new Error("public intrinsic called"); }; + try { + for (const key of Object.keys(saved)) globalThis[key] = poison; + JSON.parse = poison; + value = await body[method](); + } catch (error) { errors.push(method + " public constructor: " + String(error)); } + finally { Object.assign(globalThis, saved); JSON.parse = parse; } + if (method === "text") check(value === payload, "native text"); + if (method === "json") check(value?.answer === 42, "native JSON"); + if (method === "bytes") check(value instanceof Uint8Array, "native bytes"); + if (method === "arrayBuffer") check(value instanceof ArrayBuffer, "native arrayBuffer"); + if (method === "blob") check(value instanceof Blob && await value.text() === payload, "native blob"); + if (method === "formData") check(value instanceof FormData && value.get("answer") === "42", "native formData"); + } + } + return { errors }; +} diff --git a/moli-core/tests/fixtures/runtime/fetch_body_network.js b/moli-core/tests/fixtures/runtime/fetch_body_network.js new file mode 100644 index 00000000000..32dd0b2bb43 --- /dev/null +++ b/moli-core/tests/fixtures/runtime/fetch_body_network.js @@ -0,0 +1,7 @@ +async function runNetworkBodyProbe(scenario, url) { + const response = await fetch(url); + const body = scenario === "response" ? new Response(response.body) : + new Request(url, { method: "POST", body: response.body, duplex: "half" }); + const text = await body.text(); + return { text }; +} diff --git a/moli-core/tests/web_apis.rs b/moli-core/tests/web_apis.rs index 80fd1525c0c..e1682ac0d9f 100644 --- a/moli-core/tests/web_apis.rs +++ b/moli-core/tests/web_apis.rs @@ -33,6 +33,8 @@ mod body_state; mod callback_cleanup; #[path = "web_apis/event_dispatch.rs"] mod event_dispatch; +#[path = "web_apis/fetch_body_native.rs"] +mod fetch_body_native; #[path = "web_apis/pipe_disturbed.rs"] mod pipe_disturbed; #[path = "web_apis/request_init.rs"] diff --git a/moli-core/tests/web_apis/fetch_body_native.rs b/moli-core/tests/web_apis/fetch_body_native.rs new file mode 100644 index 00000000000..280e5525b06 --- /dev/null +++ b/moli-core/tests/web_apis/fetch_body_native.rs @@ -0,0 +1,74 @@ +use super::*; + +async fn assert_native_body_consumption(scenario: &str) -> Result<()> { + let server = FixtureServer::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let source = format!( + "{}\nrunFetchBodyNativeProbe({}).then(finish, error => finish({{error: String(error)}}));", + include_str!("../fixtures/runtime/fetch_body_native.js"), + serde_json::to_string(scenario)?, + ); + for target in ["window", "child", "worker"] { + let observed = tokio::time::timeout( + Duration::from_secs(20), + super::event_dispatch::run_probe(&browser, &server, target, &source), + ) + .await??; + assert_eq!( + observed, + serde_json::json!({"errors": []}), + "{scenario}/{target}" + ); + } + server.shutdown().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn fetch_body_reads_hide_internal_results_from_thenable_assimilation() -> Result<()> { + assert_native_body_consumption("then").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn fetch_body_reads_validate_and_copy_chunks_without_author_properties() -> Result<()> { + assert_native_body_consumption("chunks").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn fetch_body_reads_preserve_errors_and_consumption_access_state() -> Result<()> { + assert_native_body_consumption("errors").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn fetch_body_materialization_uses_native_intrinsics() -> Result<()> { + assert_native_body_consumption("intrinsics").await +} + +#[tokio::test(flavor = "multi_thread")] +async fn fetch_network_body_rewrapping_avoids_reentrant_source_borrows() -> Result<()> { + let server = FixtureServer::spawn().await?; + let browser = Browser::new(AppConfig::default())?; + let expected = "
naive-你好
"; + for scenario in ["response", "request"] { + let source = format!( + "{}\nrunNetworkBodyProbe({}, {}).then(finish, error => finish({{error: String(error)}}));", + include_str!("../fixtures/runtime/fetch_body_network.js"), + serde_json::to_string(scenario)?, + serde_json::to_string(&server.url("/streaming/chunked-html"))?, + ); + for target in ["window", "child", "worker"] { + let observed = tokio::time::timeout( + Duration::from_secs(20), + super::event_dispatch::run_probe(&browser, &server, target, &source), + ) + .await??; + assert_eq!( + observed, + serde_json::json!({"text": expected}), + "{scenario}/{target}" + ); + } + } + server.shutdown().await; + Ok(()) +} diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 089f0604ed9..76e5c73ad4b 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -469,19 +469,18 @@ pub use self::storage_buckets::{ }; pub(crate) use self::stream_adapter::{ begin_readable_stream_body_consumption, cancel_readable_stream, close_stream, - enqueue_byte_chunk, error_stream, readable_stream_disturbed, readable_stream_error, - readable_stream_has_pipe_owner, + enqueue_byte_chunk, error_stream, maybe_pull_stream, prepare_readable_stream_read_with_steps, + readable_stream_disturbed, readable_stream_error, readable_stream_has_pipe_owner, readable_stream_locked, require_internal_stream_value, }; pub(crate) use self::streams::{ ReadableStreamClonePayload, TransformStreamClonePayload, WritableStreamClonePayload, - body_stream_reader_operations, build_readable_stream_clone_shell, - build_transform_stream_clone_shell, build_writable_stream_clone_shell, - initialize_readable_stream_clone_shell, initialize_transform_stream_clone_shell, - initialize_writable_stream_clone_shell, new_readable_stream_from_array_buffer, - new_readable_stream_from_source, prepare_readable_stream_transfer, - prepare_transform_stream_transfer, prepare_writable_stream_transfer, proxy_fetch_body_stream, - tee_fetch_body_stream, + build_readable_stream_clone_shell, build_transform_stream_clone_shell, + build_writable_stream_clone_shell, initialize_readable_stream_clone_shell, + initialize_transform_stream_clone_shell, initialize_writable_stream_clone_shell, + new_readable_stream_from_array_buffer, new_readable_stream_from_source, + prepare_readable_stream_transfer, prepare_transform_stream_transfer, + prepare_writable_stream_transfer, proxy_fetch_body_stream, tee_fetch_body_stream, }; pub(crate) use self::time_ranges::new_time_ranges_value; #[cfg(test)] @@ -861,14 +860,6 @@ struct WorkerGlobalScopeCryptoPrototypeDeclaration { crypto: (), } -pub(crate) fn initialize_worker_fetch_realm_state<'s>( - scope: &mut v8::PinScope<'s, '_>, - _global: v8::Local<'s, v8::Object>, -) -> Result<()> { - crate::network_host::initialize_fetch_realm_helpers(scope)?; - Ok(()) -} - pub(crate) fn initialize_worker_performance_realm_state<'s>( scope: &mut v8::PinScope<'s, '_>, global: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs index 28b83f42bbc..97b5782ca51 100644 --- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs @@ -33,7 +33,6 @@ use crate::{ set_document_cookie_for_receiver, }, }, - network_host, util::{ callback_data_index_value, callback_data_item, context_host_ptr_from_global_bridge, get_private_value, set_private_value, throw_type_error, v8_string, v8str, @@ -1968,7 +1967,6 @@ fn install_window_runtime_state<'s>( install_default_window_performance_seed(scope, global)?; install_chrome_runtime_state(scope, global)?; install_storage_runtime_state(scope, global)?; - network_host::initialize_fetch_realm_helpers(scope)?; install_public_window_surface_accessors(scope, global)?; super::install_window_bar_props(scope, global, None)?; diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs index 676b07d9950..7e050251824 100644 --- a/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs +++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs @@ -77,14 +77,15 @@ pub(in crate::context_bootstrap) use queue_v8::{ readable_stream_queue_exists, readable_stream_queue_is_empty, readable_stream_queue_total_size, reset_readable_stream_queue, take_byte_stream_bytes, }; -pub(crate) use readable::cancel_readable_stream; pub(in crate::context_bootstrap::stream_adapter) use readable::mark_readable_stream_started; -pub(in crate::context_bootstrap) use readable::maybe_pull_stream; pub(in crate::context_bootstrap::stream_adapter) use readable::perform_read_from_stream; pub(super) use readable::{ PreparedReadableStreamRead, prepare_read_from_stream_as_promise, read_from_stream_as_promise, readable_stream_closed_promise, }; +pub(crate) use readable::{ + cancel_readable_stream, maybe_pull_stream, prepare_readable_stream_read_with_steps, +}; pub(crate) use readable_byte::enqueue_byte_chunk; pub(in crate::context_bootstrap) use readable_byte::{ enqueue_auto_allocate_pull_into, finish_byte_stream_tee_branch_close, diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable.rs index c39c83d08ef..c7c4cd7c8bf 100644 --- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable.rs +++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable.rs @@ -1,5 +1,18 @@ use super::*; +/// Installs an internal read request without materializing a JavaScript read +/// result. The caller runs `maybe_pull_stream` after its synchronous read loop. +pub(crate) fn prepare_readable_stream_read_with_steps<'s>( + scope: &mut v8::PinScope<'s, '_>, + stream: v8::Local<'s, v8::Object>, + chunk_steps: v8::Local<'s, v8::Function>, + close_steps: v8::Local<'s, v8::Function>, + error_steps: v8::Local<'s, v8::Function>, +) -> bool { + let request = new_internal_read_request(scope, chunk_steps, close_steps, error_steps); + perform_read_from_stream(scope, stream, request) +} + pub(in crate::context_bootstrap) fn read_from_stream_as_promise<'s>( scope: &mut v8::PinScope<'s, '_>, stream: v8::Local<'s, v8::Object>, @@ -136,7 +149,7 @@ fn error_read_request_for_queue_error<'s>( error_read_request(scope, request, error); } -pub(in crate::context_bootstrap) fn maybe_pull_stream<'s>( +pub(crate) fn maybe_pull_stream<'s>( scope: &mut v8::PinScope<'s, '_>, stream: v8::Local<'s, v8::Object>, ) { diff --git a/moli-renderer-v8/src/context_bootstrap/streams.rs b/moli-renderer-v8/src/context_bootstrap/streams.rs index 9d5eec2b86d..57e543444b7 100644 --- a/moli-renderer-v8/src/context_bootstrap/streams.rs +++ b/moli-renderer-v8/src/context_bootstrap/streams.rs @@ -34,17 +34,6 @@ mod readable; mod transferable; mod writable; -pub(crate) fn body_stream_reader_operations<'s>( - scope: &mut v8::PinScope<'s, '_>, -) -> Option<[v8::Local<'s, v8::Function>; 2]> { - // Fetch keeps intrinsic reader operations without eagerly materializing - // the public ReadableStream and reader interfaces during realm bootstrap. - Some([ - v8::Function::new(scope, readable_stream_get_reader_callback)?, - v8::Function::new(scope, readable_stream_reader_read_callback)?, - ]) -} - pub(crate) fn tee_fetch_body_stream<'s>( scope: &mut v8::PinScope<'s, '_>, stream: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs index 46c6bb359ae..3b7dda7decb 100644 --- a/moli-renderer-v8/src/network_host.rs +++ b/moli-renderer-v8/src/network_host.rs @@ -98,9 +98,8 @@ pub(crate) use self::fetch_surface::{ RESPONSE_URL_SLOT, is_branded_response_object, }; pub(crate) use self::fetch_surface::{ - consume_webassembly_streaming_response_value, initialize_fetch_realm_helpers, - install_request_bindings, install_response_bindings, - set_request_destination_for_service_worker_fetch_event, + consume_webassembly_streaming_response_value, install_request_bindings, + install_response_bindings, set_request_destination_for_service_worker_fetch_event, set_request_mode_for_service_worker_fetch_event, set_request_reload_navigation_for_service_worker_fetch_event, }; @@ -198,7 +197,6 @@ pub(in crate::network_host) const NETWORK_BODY_SLOT: &str = "__lmBody"; pub(in crate::network_host) const NETWORK_BODY_BYTES_SLOT: &str = "__lmBodyBytes"; pub(in crate::network_host) const NETWORK_BODY_SOURCE_SLOT: &str = "__lmNetworkBodySource"; pub(in crate::network_host) const NETWORK_BODY_SOURCE_KIND_SLOT: &str = "__lmNetworkBodySourceKind"; -pub(in crate::network_host) const BODY_STREAM_CONSUMER_SLOT: &str = "__lmConsumeReadableStreamBody"; pub(crate) const BLOCKED_BY_CLIENT_ERROR_TEXT: &str = "net::ERR_BLOCKED_BY_CLIENT"; pub(crate) const FILE_NOT_FOUND_ERROR_TEXT: &str = "net::ERR_FILE_NOT_FOUND"; pub(crate) const FAILED_ERROR_TEXT: &str = "net::ERR_FAILED"; diff --git a/moli-renderer-v8/src/network_host/body_source.rs b/moli-renderer-v8/src/network_host/body_source.rs index 03fd797790a..7edc95f383b 100644 --- a/moli-renderer-v8/src/network_host/body_source.rs +++ b/moli-renderer-v8/src/network_host/body_source.rs @@ -1,3 +1,6 @@ +mod stream_consumer; + +use self::stream_consumer::consume_readable_body_stream; use super::*; use crate::context_bootstrap::{ close_stream, enqueue_byte_chunk, error_stream, readable_stream_error, @@ -1424,76 +1427,6 @@ fn readable_body_stream_from_value<'s>( None } -fn consume_readable_body_stream<'s>( - scope: &mut v8::PinScope<'s, '_>, - stream: v8::Local<'s, v8::Object>, - kind: NetworkBodyConsumptionKind, - chunk_callback: Option>, -) -> (NetworkBodyConsumption<'s>, Option>) { - let global = scope.get_current_context().global(scope); - let Some(consumer) = global - .get(scope, v8str(scope, BODY_STREAM_CONSUMER_SLOT).into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - return (NetworkBodyConsumption::Failed, None); - }; - let (kind_name, mime_type) = body_stream_consumer_args(&kind); - let Some(kind_value) = v8_string(scope, kind_name) else { - return (NetworkBodyConsumption::Failed, None); - }; - let Some(mime_value) = v8_string(scope, mime_type.unwrap_or_default()) else { - return (NetworkBodyConsumption::Failed, None); - }; - let this = v8::undefined(scope).into(); - let (value, cancel_handle) = if let Some(chunk_callback) = chunk_callback { - let cancel_handle = v8::Global::new(scope, stream); - ( - consumer.call( - scope, - this, - &[ - stream.into(), - kind_value.into(), - mime_value.into(), - chunk_callback.into(), - ], - ), - Some(cancel_handle), - ) - } else { - ( - consumer.call( - scope, - this, - &[stream.into(), kind_value.into(), mime_value.into()], - ), - None, - ) - }; - let Some(value) = value else { - return (NetworkBodyConsumption::Failed, None); - }; - let consumption = if let Ok(promise) = v8::Local::::try_from(value) { - NetworkBodyConsumption::Pending(promise) - } else { - NetworkBodyConsumption::Ready(value) - }; - (consumption, cancel_handle) -} - -fn body_stream_consumer_args(kind: &NetworkBodyConsumptionKind) -> (&'static str, Option<&str>) { - match kind { - NetworkBodyConsumptionKind::Text => ("text", None), - NetworkBodyConsumptionKind::Json => ("json", None), - NetworkBodyConsumptionKind::ArrayBuffer => ("arrayBuffer", None), - NetworkBodyConsumptionKind::Bytes => ("bytes", None), - NetworkBodyConsumptionKind::Blob { mime_type } => ("blob", Some(mime_type.as_str())), - NetworkBodyConsumptionKind::FormData { content_type } => { - ("formData", Some(content_type.as_str())) - } - } -} - fn object_has_null_body_slot<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, @@ -1997,10 +1930,27 @@ fn pending_body_source_pull_callback<'s>( ) { let source = args.this(); mark_registry_body_source_used(scope, source); + // Internal read requests can ask for another chunk while network delivery + // still borrows its pending-source state. Access that state after enqueue + // has returned, while retaining the stream's synchronous read request. + let callback = v8::Function::builder(pending_body_source_pull_microtask) + .data(source.into()) + .build(scope) + .expect("pending body pull callback must allocate"); + scope.enqueue_microtask(callback); + rv.set_undefined(); +} + +fn pending_body_source_pull_microtask<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + let source = v8::Local::::try_from(args.data()) + .expect("pending body pull must retain its source"); if let Some(id) = registry_body_source_id(scope, source) { pull_pending_network_body_source(scope, id); } - rv.set_undefined(); } fn pull_pending_network_body_source(scope: &mut v8::PinScope<'_, '_>, id: NetworkBodySourceId) { diff --git a/moli-renderer-v8/src/network_host/body_source/stream_consumer.rs b/moli-renderer-v8/src/network_host/body_source/stream_consumer.rs new file mode 100644 index 00000000000..532d9f5fc93 --- /dev/null +++ b/moli-renderer-v8/src/network_host/body_source/stream_consumer.rs @@ -0,0 +1,322 @@ +//! Fetch's read-all-bytes loop uses internal Streams read requests. Public +//! reader promises would expose intermediate `{ value, done }` objects to +//! thenable assimilation before Fetch has checked or copied the chunk. + +use super::*; +use crate::context_bootstrap::{ + begin_readable_stream_body_consumption, maybe_pull_stream, + prepare_readable_stream_read_with_steps, +}; +use crate::util::set_null_prototype; + +const STREAM: &str = "__moliBodyConsumerStream"; +const RESOLVER: &str = "__moliBodyConsumerResolver"; +const CHUNKS: &str = "__moliBodyConsumerChunks"; +const KIND: &str = "__moliBodyConsumerKind"; +const MIME: &str = "__moliBodyConsumerMime"; +const ON_CHUNK: &str = "__moliBodyConsumerOnChunk"; +const PENDING_CHUNK: &str = "__moliBodyConsumerPendingChunk"; +const STEPS: &str = "__moliBodyConsumerSteps"; +const DRAINING: &str = "__moliBodyConsumerDraining"; +const READ_AGAIN: &str = "__moliBodyConsumerReadAgain"; +const FINISHED: &str = "__moliBodyConsumerFinished"; +const SUCCEEDED: &str = "__moliBodyConsumerSucceeded"; +const REASON: &str = "__moliBodyConsumerReason"; + +#[derive(WebApiObject)] +#[webapi(plain)] +struct BodyConsumerDeclaration<'scope> { + #[webapi(slot = STREAM)] + stream: v8::Local<'scope, v8::Object>, + #[webapi(slot = RESOLVER)] + resolver: v8::Local<'scope, v8::Object>, + #[webapi(slot = CHUNKS)] + chunks: v8::Local<'scope, v8::Array>, + #[webapi(slot = KIND)] + kind: &'static str, + #[webapi(slot = MIME)] + mime: String, + #[webapi(slot = ON_CHUNK)] + on_chunk: Option>, + #[webapi(slot = PENDING_CHUNK, init = "null")] + pending_chunk: (), + #[webapi(slot = STEPS, init = "null")] + steps: (), + #[webapi(slot = DRAINING, init = false)] + draining: (), + #[webapi(slot = READ_AGAIN, init = false)] + read_again: (), + #[webapi(slot = FINISHED, init = false)] + finished: (), + #[webapi(slot = SUCCEEDED, init = false)] + succeeded: (), + #[webapi(slot = REASON, init = "null")] + reason: (), +} + +#[derive(Clone, Copy)] +struct Consumer<'s>(v8::Local<'s, v8::Object>); + +impl<'s> Consumer<'s> { + fn value(self, scope: &mut v8::PinScope<'s, '_>, slot: &str) -> v8::Local<'s, v8::Value> { + get_private_value(scope, self.0, slot).unwrap_or_else(|| v8::undefined(scope).into()) + } + + fn flag(self, scope: &mut v8::PinScope<'s, '_>, slot: &str) -> bool { + self.value(scope, slot).is_true() + } + + fn set_flag(self, scope: &mut v8::PinScope<'s, '_>, slot: &str, value: bool) { + set_private_value(scope, self.0, slot, v8::Boolean::new(scope, value).into()); + } + + fn array(self, scope: &mut v8::PinScope<'s, '_>, slot: &str) -> v8::Local<'s, v8::Array> { + v8::Local::try_from(self.value(scope, slot)).expect("body consumer array must exist") + } + + fn read(self, scope: &mut v8::PinScope<'s, '_>) { + if self.flag(scope, FINISHED) { + return; + } + if self.flag(scope, DRAINING) { + self.set_flag(scope, READ_AGAIN, true); + return; + } + self.set_flag(scope, DRAINING, true); + let stream = v8::Local::try_from(self.value(scope, STREAM)) + .expect("body consumer must retain its stream"); + let steps = self.array(scope, STEPS); + let callbacks = [0, 1, 2].map(|index| { + v8::Local::try_from(steps.get_index(scope, index).expect("read step must exist")) + .expect("read step must be a function") + }); + let mut pull = false; + loop { + self.set_flag(scope, READ_AGAIN, false); + pull |= prepare_readable_stream_read_with_steps( + scope, + stream, + callbacks[0], + callbacks[1], + callbacks[2], + ); + if self.flag(scope, FINISHED) || !self.flag(scope, READ_AGAIN) { + break; + } + } + self.set_flag(scope, DRAINING, false); + // Drain already queued chunks before calling author pull code. This + // implements recursive chunk steps without growing the native stack. + if pull { + maybe_pull_stream(scope, stream); + } + } + + fn finish(self, scope: &mut v8::PinScope<'s, '_>, error: Option>) { + if self.flag(scope, FINISHED) { + return; + } + self.set_flag(scope, FINISHED, true); + self.set_flag(scope, SUCCEEDED, error.is_none()); + if let Some(error) = error { + set_private_value(scope, self.0, REASON, error); + set_private_value(scope, self.0, CHUNKS, v8::null(scope).into()); + } + let callback = v8::Function::builder(materialize_callback) + .data(self.0.into()) + .build(scope) + .expect("body materialization callback must allocate"); + // Retain the existing asynchronous completion boundary while removing + // the observable intermediate reader promises. + scope.enqueue_microtask(callback); + } +} + +pub(super) fn consume_readable_body_stream<'s>( + scope: &mut v8::PinScope<'s, '_>, + stream: v8::Local<'s, v8::Object>, + kind: NetworkBodyConsumptionKind, + chunk_callback: Option>, +) -> (NetworkBodyConsumption<'s>, Option>) { + let Some(resolver) = v8::PromiseResolver::new(scope) else { + return (NetworkBodyConsumption::Failed, None); + }; + if !begin_readable_stream_body_consumption(scope, stream) { + let error = v8::Exception::type_error(scope, v8str(scope, "Body stream is locked")); + return (NetworkBodyConsumption::Rejected(error), None); + } + let promise = resolver.get_promise(scope); + let (kind, mime) = match kind { + NetworkBodyConsumptionKind::Text => ("text", String::new()), + NetworkBodyConsumptionKind::Json => ("json", String::new()), + NetworkBodyConsumptionKind::ArrayBuffer => ("arrayBuffer", String::new()), + NetworkBodyConsumptionKind::Bytes => ("bytes", String::new()), + NetworkBodyConsumptionKind::Blob { mime_type } => ("blob", mime_type), + NetworkBodyConsumptionKind::FormData { content_type } => ("formData", content_type), + }; + let chunks = v8::Array::new(scope, 0); + set_null_prototype(scope, chunks.into()); + let consumer = Consumer( + BodyConsumerDeclaration::new(stream, resolver.into(), chunks, kind, mime, chunk_callback) + .bind(scope) + .expect("body consumer declaration must bind"), + ); + let callbacks = [ + v8::Function::builder(chunk_callback_step) + .data(consumer.0.into()) + .build(scope), + v8::Function::builder(close_callback_step) + .data(consumer.0.into()) + .build(scope), + v8::Function::builder(error_callback_step) + .data(consumer.0.into()) + .build(scope), + ] + .map(|step| step.expect("body read step must allocate").into()); + let steps = v8::Array::new_with_elements(scope, &callbacks); + set_null_prototype(scope, steps.into()); + set_private_value(scope, consumer.0, STEPS, steps.into()); + let cancel_handle = chunk_callback.map(|_| v8::Global::new(scope, stream)); + consumer.read(scope); + (NetworkBodyConsumption::Pending(promise), cancel_handle) +} + +fn chunk_callback_step<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + let consumer = Consumer(v8::Local::try_from(args.data()).expect("body read step owner")); + let Ok(chunk) = v8::Local::::try_from(args.get(0)) else { + let error = v8::Exception::type_error( + scope, + v8str(scope, "ReadableStream body chunks must be Uint8Array"), + ); + consumer.finish(scope, Some(error)); + return; + }; + // Snapshot the represented bytes now, including view offset and length. + // A subsequent pull, enqueue, or callback may mutate or detach this chunk. + let mut bytes = vec![0; chunk.byte_length()]; + let written = chunk.copy_contents(&mut bytes); + bytes.truncate(written); + let buffer = blob::array_buffer_from_bytes(scope, bytes).expect("chunk copy must allocate"); + let chunks = consumer.array(scope, CHUNKS); + chunks + .set_index(scope, chunks.length(), buffer.into()) + .expect("private chunk list must append"); + if consumer.value(scope, ON_CHUNK).is_function() { + // Streaming response delivery first publishes its head and cancel + // handle. Host network enqueue paths can also hold a mutable worker + // borrow: invoke their chunk consumer after that delivery returns. + set_private_value(scope, consumer.0, PENDING_CHUNK, buffer.into()); + let callback = v8::Function::builder(deliver_chunk_callback) + .data(consumer.0.into()) + .build(scope) + .expect("body chunk delivery callback must allocate"); + scope.enqueue_microtask(callback); + } else { + consumer.read(scope); + } +} + +fn deliver_chunk_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + let consumer = Consumer(v8::Local::try_from(args.data()).expect("body chunk delivery owner")); + let buffer = v8::Local::::try_from(consumer.value(scope, PENDING_CHUNK)) + .expect("body chunk delivery must retain its copied bytes"); + let chunk = v8::Uint8Array::new(scope, buffer, 0, buffer.byte_length()) + .expect("body chunk delivery view must allocate"); + set_private_value(scope, consumer.0, PENDING_CHUNK, v8::null(scope).into()); + let callback = v8::Local::::try_from(consumer.value(scope, ON_CHUNK)) + .expect("body chunk delivery consumer must exist"); + { + let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); + let scope = &mut try_catch.init(); + if callback + .call(scope, v8::undefined(scope).into(), &[chunk.into()]) + .is_none() + { + let error = scope + .exception() + .unwrap_or_else(|| v8::undefined(scope).into()); + consumer.finish(scope, Some(error)); + return; + } + } + consumer.read(scope); +} + +fn close_callback_step<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + Consumer(v8::Local::try_from(args.data()).expect("body read step owner")).finish(scope, None); +} + +fn error_callback_step<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + Consumer(v8::Local::try_from(args.data()).expect("body read step owner")) + .finish(scope, Some(args.get(0))); +} + +fn materialize_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + _rv: v8::ReturnValue<'_, v8::Value>, +) { + let consumer = Consumer(v8::Local::try_from(args.data()).expect("body materialization owner")); + let resolver = v8::Local::::try_from(consumer.value(scope, RESOLVER)) + .expect("body materialization resolver"); + // SAFETY: the private slot is initialized only from PromiseResolver::new + // and is cleared after this single completion callback. + let resolver = unsafe { v8::Local::::cast_unchecked(resolver) }; + if consumer.flag(scope, SUCCEEDED) { + let chunks = consumer.array(scope, CHUNKS); + let mut bytes = Vec::new(); + for index in 0..chunks.length() { + let chunk = chunks + .get_index(scope, index) + .expect("body chunk copy must exist"); + bytes.extend( + blob::buffer_source_bytes_from_value(scope, chunk).expect("body chunk bytes"), + ); + } + let mime = consumer.value(scope, MIME).to_rust_string_lossy(scope); + let kind = match consumer + .value(scope, KIND) + .to_rust_string_lossy(scope) + .as_str() + { + "text" => PendingBodyMaterializationKind::Text, + "json" => PendingBodyMaterializationKind::Json, + "arrayBuffer" => PendingBodyMaterializationKind::ArrayBuffer, + "bytes" => PendingBodyMaterializationKind::Bytes, + "blob" => PendingBodyMaterializationKind::Blob { mime_type: mime }, + "formData" => PendingBodyMaterializationKind::FormData { content_type: mime }, + _ => unreachable!("body materialization kind is private"), + }; + resolve_body_materialization(scope, resolver, bytes, kind); + } else { + let error = consumer.value(scope, REASON); + let _ = resolver.reject(scope, error); + } + for slot in [ + STREAM, + RESOLVER, + CHUNKS, + ON_CHUNK, + PENDING_CHUNK, + STEPS, + REASON, + ] { + set_private_value(scope, consumer.0, slot, v8::null(scope).into()); + } +} diff --git a/moli-renderer-v8/src/network_host/fetch_surface.rs b/moli-renderer-v8/src/network_host/fetch_surface.rs index fe03db70bc1..365457a6577 100644 --- a/moli-renderer-v8/src/network_host/fetch_surface.rs +++ b/moli-renderer-v8/src/network_host/fetch_surface.rs @@ -1071,85 +1071,3 @@ pub(crate) fn install_response_bindings<'s>( ResponseSlotAccessorsDeclaration::initialize_prototype_template(scope, prototype); install_response_body_methods(scope, prototype); } - -const BODY_STREAM_CONSUMER_RUNTIME_SOURCE: &str = r#" -((getReader, read) => { - const consumerName = "__lmConsumeReadableStreamBody"; - if (Object.prototype.hasOwnProperty.call(globalThis, consumerName)) { - return; - } - const parseJSON = JSON.parse; - - function uint8ArrayChunkBytes(chunk) { - if (Object.prototype.toString.call(chunk) !== "[object Uint8Array]") { - throw new TypeError("ReadableStream body chunks must be Uint8Array"); - } - return chunk; - } - - async function consumeReadableStreamBody(stream, kind, mimeType, onChunk) { - const reader = getReader.call(stream); - const chunks = []; - let total = 0; - for (;;) { - const result = await read.call(reader); - if (result.done) break; - const chunk = uint8ArrayChunkBytes(result.value); - if (typeof onChunk === "function") onChunk(chunk); - chunks.push(chunk); - total += chunk.byteLength; - } - - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - - if (kind === "arrayBuffer") return bytes.buffer; - if (kind === "bytes") return bytes; - if (kind === "text") return new TextDecoder().decode(bytes); - if (kind === "json") return parseJSON(new TextDecoder().decode(bytes)); - if (kind === "blob") return new Blob([bytes], { type: mimeType || "" }); - if (kind === "formData") { - return new Response(bytes, { - headers: [["Content-Type", mimeType || ""]] - }).formData(); - } - throw new TypeError("Unsupported body consumption kind"); - } - - Object.defineProperty(globalThis, consumerName, { - value: consumeReadableStreamBody, - configurable: true - }); -}) -"#; - -pub(crate) fn initialize_fetch_realm_helpers( - scope: &mut v8::PinScope<'_, '_>, -) -> anyhow::Result<()> { - install_body_stream_consumer_runtime(scope) -} - -fn install_body_stream_consumer_runtime(scope: &mut v8::PinScope<'_, '_>) -> anyhow::Result<()> { - let [get_reader, read] = crate::context_bootstrap::body_stream_reader_operations(scope) - .ok_or_else(|| anyhow::anyhow!("failed to allocate Fetch body reader operations"))?; - let Some(source) = v8_string(scope, BODY_STREAM_CONSUMER_RUNTIME_SOURCE) else { - anyhow::bail!("failed to allocate Fetch body stream consumer runtime source"); - }; - let script = v8::Script::compile(scope, source, None) - .ok_or_else(|| anyhow::anyhow!("failed to compile Fetch body stream consumer runtime"))?; - let initializer = crate::script_execution::execute_compiled_script(scope, script) - .and_then(|value| v8::Local::::try_from(value).ok()) - .ok_or_else(|| anyhow::anyhow!("failed to create Fetch body stream consumer runtime"))?; - crate::script_execution::call_function( - scope, - initializer, - v8::undefined(scope).into(), - &[get_reader.into(), read.into()], - ) - .ok_or_else(|| anyhow::anyhow!("failed to initialize Fetch body stream consumer runtime"))?; - Ok(()) -} diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs index a6f557dc455..4b48ef5bb6a 100644 --- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs +++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs @@ -144,7 +144,12 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[ ), allowed( "network_host/body_source.rs", - 3, + 1, + DirectCallOwner::BrowserAlgorithm, + ), + allowed( + "network_host/body_source/stream_consumer.rs", + 1, DirectCallOwner::BrowserAlgorithm, ), allowed( @@ -154,9 +159,7 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[ ), allowed( "network_host/fetch_surface.rs", - // Includes the Fetch bootstrap closure receiving native reader - // operations; the closure is compiled from browser-owned source. - 2, + 1, DirectCallOwner::BrowserAlgorithm, ), allowed( diff --git a/moli-renderer-v8/src/worker/global_scope/bootstrap.rs b/moli-renderer-v8/src/worker/global_scope/bootstrap.rs index db83c065067..6fb50125f32 100644 --- a/moli-renderer-v8/src/worker/global_scope/bootstrap.rs +++ b/moli-renderer-v8/src/worker/global_scope/bootstrap.rs @@ -173,7 +173,6 @@ pub(in crate::worker) fn install_worker_global_scope<'s>( ) { install_service_worker_extendable_event_constructors(scope, global)?; } - crate::context_bootstrap::initialize_worker_fetch_realm_state(scope, global)?; crate::context_bootstrap::initialize_worker_performance_realm_state(scope, global)?; let subtle_crypto_available = secure_context; crate::context_bootstrap::initialize_worker_crypto_realm_state(