Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(fetch): keep body errors in the readable stream

ldm03b9003b3268d
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index 3b69b9675..3658dd70f 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -441,8 +441,8 @@ pub use self::storage_buckets::{
};
pub(crate) use self::stream_adapter::{
cancel_readable_stream, close_stream, enqueue_byte_chunk, error_stream,
- readable_stream_disturbed, readable_stream_has_pipe_owner, readable_stream_locked,
- require_internal_stream_value,
+ 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,
diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs
index 5928dc977..4873a0369 100644
--- a/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs
+++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter.rs
@@ -103,10 +103,10 @@ pub(in crate::context_bootstrap) use readable_state::{
finish_readable_stream_close_if_requested_and_queue_empty, lock_readable_stream,
readable_stream_access_snapshot, readable_stream_is_byte_stream, unlock_readable_stream,
};
-pub(crate) use readable_state::{close_stream, enqueue_chunk, error_stream};
+pub(crate) use readable_state::{close_stream, enqueue_chunk, error_stream, readable_stream_error};
pub(super) use readable_state::{
- readable_stream_closed, readable_stream_error, reject_pending_read_requests,
- remove_pending_closed_promise, writable_stream_locked,
+ readable_stream_closed, reject_pending_read_requests, remove_pending_closed_promise,
+ writable_stream_locked,
};
pub(in crate::context_bootstrap::stream_adapter) use transform_finish::transform_stream_readable_cancel_callback;
pub(super) use utils::{
diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs
index e39916299..1115ea7c1 100644
--- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/readable_state.rs
@@ -317,7 +317,7 @@ fn readable_stream_pull_state<'s>(
.unwrap_or(READABLE_STREAM_PULL_STATE_STARTED)
}
-pub(in crate::context_bootstrap) fn readable_stream_error<'s>(
+pub(crate) fn readable_stream_error<'s>(
scope: &mut v8::PinScope<'s, '_>,
stream: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Value>> {
diff --git a/moli-renderer-v8/src/network_host/body_source.rs b/moli-renderer-v8/src/network_host/body_source.rs
index f28aec8b4..bedfc3bf5 100644
--- a/moli-renderer-v8/src/network_host/body_source.rs
+++ b/moli-renderer-v8/src/network_host/body_source.rs
@@ -1,10 +1,11 @@
use super::*;
use crate::context_bootstrap::{
- close_stream, enqueue_byte_chunk, error_stream, readable_stream_has_pipe_owner,
+ close_stream, enqueue_byte_chunk, error_stream, readable_stream_error,
+ readable_stream_has_pipe_owner,
};
use crate::protocol_types::SubresourceResponseBody;
use crate::types::NetworkBodySourceId;
-use crate::util::{RealmObjectHandle, RealmValueHandle, get_private_value, set_private_value};
+use crate::util::{RealmObjectHandle, get_private_value, set_private_value};
use crate::web_api_interfaces;
use crate::worker::get_worker_state;
use std::collections::{HashMap, HashSet};
@@ -261,10 +262,22 @@ pub(crate) struct PendingNetworkBodySourceState {
pull_requested: bool,
closed: bool,
error: Option<String>,
- error_reason: Option<RealmValueHandle>,
materializations: Vec<PendingBodyMaterialization>,
}
+impl PendingNetworkBodySourceState {
+ fn error_reason<'s>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ ) -> Option<v8::Local<'s, v8::Value>> {
+ self.error.as_ref()?;
+ // The stream owns the original rejection value, including undefined.
+ // This native lookup must not keep that value or its realm alive.
+ let stream = self.stream.to_local(scope)?;
+ readable_stream_error(scope, stream)
+ }
+}
+
pub(crate) fn retain_pending_network_body_state_in_retired_realm(
scope: &mut v8::PinScope<'_, '_>,
include_shared_default_world: bool,
@@ -273,9 +286,8 @@ pub(crate) fn retain_pending_network_body_state_in_retired_realm(
let Some(host) = context_host_mut(scope) else {
return;
};
- // Retained Responses keep their buffered bytes and error identity. Their
- // native body state must not in turn root the retired realm through a
- // pending body-method resolver or stored JavaScript rejection reason.
+ // Retained Responses keep their buffered bytes. Pending body-method
+ // resolvers must not in turn root the retired realm through native state.
for state in host.pending_network_body_sources.values_mut() {
for materialization in &mut state.materializations {
if include_shared_default_world
@@ -288,22 +300,6 @@ pub(crate) fn retain_pending_network_body_state_in_retired_realm(
materialization.resolver.retain_in_realm(scope);
}
}
- let stream_context = state
- .stream
- .to_local(scope)
- .and_then(|stream| stream.get_creation_context(scope));
- if (include_shared_default_world || stream_context == Some(context))
- && let Some(reason) = &mut state.error_reason
- {
- // A shared native host can own body state from several realms.
- // Anchor the reason in the stream's realm, even during main teardown.
- if let Some(stream_context) = stream_context {
- let scope = &mut v8::ContextScope::new(scope, stream_context);
- reason.retain_in_realm(scope);
- } else {
- reason.retain_in_realm(scope);
- }
- }
}
}
@@ -604,7 +600,6 @@ fn pending_network_body_source_and_stream<'s>(
pull_requested: false,
closed: false,
error: None,
- error_reason: None,
materializations: Vec::new(),
},
);
@@ -622,7 +617,6 @@ fn pending_network_body_source_and_stream<'s>(
pull_requested: false,
closed: false,
error: None,
- error_reason: None,
materializations: Vec::new(),
},
);
@@ -949,7 +943,6 @@ fn error_pending_network_body_stream_with_clone_ids<'s>(
}
state.closed = true;
state.error = Some(error_text.to_owned());
- state.error_reason = Some(RealmValueHandle::new(scope, reason));
if let Some(stream) = state.stream.to_local(scope) {
error_stream(scope, stream, reason);
}
@@ -968,7 +961,6 @@ fn error_pending_network_body_stream_with_clone_ids<'s>(
}
clone.closed = true;
clone.error = Some(error_text.to_owned());
- clone.error_reason = Some(RealmValueHandle::new(scope, reason));
if let Some(stream) = clone.stream.to_local(scope) {
error_stream(scope, stream, reason);
}
@@ -1241,10 +1233,9 @@ fn clone_pending_network_body_source_in_maps(
let snapshot = original.bytes.clone();
outcome.close_now = original.closed;
outcome.error_now = original.error.clone();
- outcome.error_reason_now = original.error_reason.as_ref().map(|reason| {
- let reason = reason.to_local(scope);
- v8::Global::new(scope, reason)
- });
+ outcome.error_reason_now = original
+ .error_reason(scope)
+ .map(|reason| v8::Global::new(scope, reason));
if let Some(clone) = sources.get_mut(&clone_id) {
append_pending_body_state_bytes(scope, clone, &snapshot);
}
@@ -1552,12 +1543,8 @@ fn inspect_pending_body_source_for_materialization<'s>(
if let Some(error_text) = state.error.clone() {
*rejected = Some(
state
- .error_reason
- .as_ref()
- .map(|reason| {
- let reason = reason.to_local(scope);
- PendingBodyRejection::Reason(v8::Global::new(scope, reason))
- })
+ .error_reason(scope)
+ .map(|reason| PendingBodyRejection::Reason(v8::Global::new(scope, reason)))
.unwrap_or(PendingBodyRejection::Message(error_text)),
);
sources.remove(&id);
diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs b/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs
index c0670fca4..78769afae 100644
--- a/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs
+++ b/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs
@@ -221,6 +221,158 @@ fn retained_response_body_keeps_error_reason_until_the_last_v8_reference() {
);
}
+fn error_response_with_foreign_reason_for_test(
+ vm: &mut StandaloneScriptVmHarness,
+ body_source_id: crate::types::NetworkBodySourceId,
+) -> (v8::Weak<v8::Object>, v8::Weak<v8::Context>) {
+ vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| {
+ let foreign_context = v8::Context::new(scope, Default::default());
+ let reason = {
+ let scope = &mut v8::ContextScope::new(scope, foreign_context);
+ let message = crate::util::v8str(scope, "foreign body failure");
+ v8::Exception::error(scope, message)
+ };
+ crate::network_host::error_pending_network_body_stream_with_reason(
+ scope,
+ body_source_id,
+ "foreign body failure".to_owned(),
+ reason,
+ );
+ Ok((
+ v8::Weak::new(scope, v8::Local::<v8::Object>::try_from(reason).unwrap()),
+ v8::Weak::new(scope, foreign_context),
+ ))
+ })
+ .unwrap()
+}
+
+#[test]
+fn unread_response_body_error_is_collectible_while_document_is_alive() {
+ let (mut vm, body_source_id) = new_vm_with_pending_response_for_teardown_test();
+ let (reason, foreign_context) =
+ error_response_with_foreign_reason_for_test(&mut vm, body_source_id);
+ let isolate = vm.renderer_document_isolate.clone();
+ for _ in 0..2 {
+ isolate.with_renderer_document_isolate_mut(|isolate| isolate.low_memory_notification());
+ }
+ vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| {
+ assert!(
+ reason.to_local(scope).is_some(),
+ "Response must retain its error"
+ );
+ assert!(foreign_context.to_local(scope).is_some());
+ Ok(())
+ })
+ .unwrap();
+
+ vm.eval("globalThis.response = null").unwrap();
+ for _ in 0..2 {
+ isolate.with_renderer_document_isolate_mut(|isolate| isolate.low_memory_notification());
+ }
+ let host = vm.context_host_weak_for_test().upgrade().unwrap();
+ assert!(
+ host.borrow()
+ .pending_network_body_sources
+ .contains_key(&body_source_id)
+ );
+ vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| {
+ assert!(
+ reason.to_local(scope).is_none(),
+ "the native body table must not root an unreachable error"
+ );
+ assert!(
+ foreign_context.to_local(scope).is_none(),
+ "the native body table must not retain the error's foreign realm"
+ );
+ Ok(())
+ })
+ .unwrap();
+}
+
+#[test]
+fn response_body_and_clones_preserve_foreign_error_after_gc() {
+ let (mut vm, body_source_id) = new_vm_with_pending_response_for_teardown_test();
+ vm.eval("globalThis.before = response.clone()").unwrap();
+ let (reason, _) = error_response_with_foreign_reason_for_test(&mut vm, body_source_id);
+ vm.eval("globalThis.after = response.clone()").unwrap();
+ let isolate = vm.renderer_document_isolate.clone();
+ for _ in 0..2 {
+ isolate.with_renderer_document_isolate_mut(|isolate| isolate.low_memory_notification());
+ }
+ vm.eval(
+ "globalThis.rejections = [];\n\
+ for (const item of [response, before, after]) {\n\
+ item.text().catch(error => rejections.push(error));\n\
+ }",
+ )
+ .unwrap();
+ vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| {
+ let reason = reason
+ .to_local(scope)
+ .expect("observable body errors must survive GC");
+ let global = scope.get_current_context().global(scope);
+ let rejections = global
+ .get(scope, crate::util::v8str(scope, "rejections").into())
+ .unwrap();
+ let rejections = v8::Local::<v8::Array>::try_from(rejections).unwrap();
+ assert_eq!(rejections.length(), 3);
+ for index in 0..3 {
+ assert!(
+ rejections
+ .get_index(scope, index)
+ .unwrap()
+ .strict_equals(reason.into())
+ );
+ }
+ Ok(())
+ })
+ .unwrap();
+}
+
+#[test]
+fn response_body_and_clones_preserve_primitive_errors_after_gc() {
+ for expression in ["undefined", "null", "42", "'body failure'"] {
+ let (mut vm, body_source_id) = new_vm_with_pending_response_for_teardown_test();
+ vm.eval(&format!(
+ "globalThis.bodyFailure = {expression}; globalThis.before = response.clone()"
+ ))
+ .unwrap();
+ vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| {
+ let global = scope.get_current_context().global(scope);
+ let reason = global
+ .get(scope, crate::util::v8str(scope, "bodyFailure").into())
+ .unwrap();
+ crate::network_host::error_pending_network_body_stream_with_reason(
+ scope,
+ body_source_id,
+ "fallback must not replace the original value".to_owned(),
+ reason,
+ );
+ Ok(())
+ })
+ .unwrap();
+ vm.eval("globalThis.after = response.clone()").unwrap();
+ for _ in 0..2 {
+ vm.renderer_document_isolate
+ .with_renderer_document_isolate_mut(|isolate| {
+ isolate.low_memory_notification();
+ });
+ }
+ vm.eval(
+ "globalThis.matches = [];\n\
+ for (const item of [response, before, after]) {\n\
+ item.text().then(() => matches.push(false), error => matches.push(error === bodyFailure));\n\
+ }",
+ )
+ .unwrap();
+ assert_eq!(
+ vm.eval("matches.join(',')").unwrap(),
+ "true,true,true",
+ "{expression}"
+ );
+ }
+}
+
fn new_vm_with_evaluated_module_for_teardown_test() -> StandaloneScriptVmHarness {
let mut vm = new_storage_test_vm("https://module-teardown.test/");
let url = vm.document_runtime.document_url().clone();