Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(renderer): synchronize intrinsic interface registration
ldm0af6910cf9bf7
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rsindex da8eed047..1d90bbb7a 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs@@ -206,6 +206,7 @@ pub(crate) fn capture_eager_intrinsic_interfaces<'s>(let captured_constructor = registered_intrinsic_constructor(scope, global, metadata.name);let captured_prototype = registered_intrinsic_prototype(scope, global, metadata.name);if captured_constructor.is_some() != captured_prototype.is_some() {+ realm.set_state(metadata.id, RealmInterfaceState::Failed)?;return Err(anyhow!("eager intrinsic `{}` has partial constructor/prototype state",metadata.name@@ -216,7 +217,15 @@ pub(crate) fn capture_eager_intrinsic_interfaces<'s>(let public_interface = realm.public_interface(scope, metadata.id).unwrap_or(constructor);- realm.register_objects(scope, metadata.id, constructor, prototype, public_interface)?;+ realm.register_intrinsic_objects(+ scope,+ global,+ metadata.id,+ metadata.name,+ constructor,+ prototype,+ public_interface,+ )?;realm.set_state(metadata.id, RealmInterfaceState::Ready)?;continue;}@@ -239,13 +248,15 @@ pub(crate) fn capture_eager_intrinsic_interfaces<'s>(let Some(prototype) = constructor_prototype_object(scope, constructor) else {continue;};- if !register_intrinsic_interface(scope, global, metadata.name, constructor, prototype) {- return Err(anyhow!(- "failed to capture eager intrinsic `{}`",- metadata.name- ));- }- realm.register_objects(scope, metadata.id, constructor, prototype, constructor)?;+ realm.register_intrinsic_objects(+ scope,+ global,+ metadata.id,+ metadata.name,+ constructor,+ prototype,+ constructor,+ )?;realm.set_state(metadata.id, RealmInterfaceState::Ready)?;}Ok(())diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rsindex eba493a6a..e42668a3d 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/materialize.rs@@ -11,8 +11,8 @@ use crate::context_bootstrap::runtime_state::set_interface_prototype_constructoruse crate::context_bootstrap::shared::throw_error;use crate::context_bootstrap::specs::ConstructorKind;use crate::util::{- constructor_prototype_object, register_intrinsic_interface, registered_intrinsic_constructor,- registered_intrinsic_prototype, v8str,+ constructor_prototype_object, registered_intrinsic_constructor, registered_intrinsic_prototype,+ v8str,};pub(super) fn exposed_interface_lazy_getter<'s>(@@ -55,7 +55,6 @@ pub(super) fn materialize_interface<'s>(.metadata(id).ok_or_else(|| anyhow!("unknown exposed interface id {}", id.index()))?;let realm = IntrinsicInterfaceRegistry::for_current_context(scope, registry.len())?;- let global = scope.get_current_context().global(scope);match realm.state(id)@@ -95,15 +94,6 @@ pub(super) fn materialize_interface<'s>(RealmInterfaceState::Uninitialized => {}}- if registered_intrinsic_constructor(scope, global, metadata.name).is_some()- || registered_intrinsic_prototype(scope, global, metadata.name).is_some()- {- return Err(anyhow!(- "uninitialized interface `{}` has partial registry state",- metadata.name- ));- }-realm.set_state(id, RealmInterfaceState::Materializing)?;match materialize_uninitialized_interface(scope, ®istry, &realm, id) {Ok(interface) => Ok(interface),@@ -196,6 +186,46 @@ fn materialize_uninitialized_interface<'s>(let metadata = registry.metadata(id).ok_or_else(|| anyhow!("unknown exposed interface id {}", id.index()))?;+ let context = scope.get_current_context();+ let global = context.global(scope);+ match (+ registered_intrinsic_constructor(scope, global, metadata.name),+ registered_intrinsic_prototype(scope, global, metadata.name),+ ) {+ (Some(constructor), Some(prototype)) => {+ // A complete native-only pair can outlive an interrupted eager+ // capture. Reuse its identities without consulting author bindings.+ if constructor.get_creation_context(scope) != Some(context)+ || prototype.get_creation_context(scope) != Some(context)+ {+ return Err(anyhow!(+ "registered intrinsic interface `{}` belongs to another realm",+ metadata.name+ ));+ }+ let constructor = v8::Local::<v8::Function>::try_from(constructor).map_err(|_| {+ anyhow!(+ "intrinsic constructor `{}` is not a Function",+ metadata.name+ )+ })?;+ return finish_materialized_interface(+ scope,+ registry,+ realm,+ id,+ constructor,+ prototype,+ );+ }+ (None, None) => {}+ _ => {+ return Err(anyhow!(+ "uninitialized interface `{}` has partial registry state",+ metadata.name+ ));+ }+ }let parent = metadata.parent.map(|parent_id| intrinsic_parent(scope, registry, parent_id))@@ -256,19 +286,27 @@ fn materialize_uninitialized_interface<'s>(}}- let global = scope.get_current_context().global(scope);- if !register_intrinsic_interface(+ finish_materialized_interface(scope,- global,- metadata.name,- constructor.into(),+ registry,+ realm,+ id,+ constructor,constructor_prototype,- ) {- return Err(anyhow!(- "failed to register intrinsic interface `{}`",- metadata.name- ));- }+ )+}++fn finish_materialized_interface<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ registry: &Rc<ExposedInterfaceTemplateRegistry>,+ realm: &Rc<IntrinsicInterfaceRegistry>,+ id: InterfaceId,+ constructor: v8::Local<'s, v8::Function>,+ constructor_prototype: v8::Local<'s, v8::Object>,+) -> Result<v8::Local<'s, v8::Value>> {+ let metadata = registry+ .metadata(id)+ .ok_or_else(|| anyhow!("unknown exposed interface id {}", id.index()))?;let public_interface = match metadata.kind {ConstructorKind::HtmlElement => {let proxy =@@ -284,14 +322,16 @@ fn materialize_uninitialized_interface<'s>(}_ => constructor.into(),};- realm.register_objects(+ let global = scope.get_current_context().global(scope);+ realm.register_intrinsic_objects(scope,+ global,id,+ metadata.name,constructor.into(),constructor_prototype,public_interface,)?;- realm.set_state(id, RealmInterfaceState::Finalizing)?;finalize_materialized_interface(scope, metadata.name)?;realm.set_state(id, RealmInterfaceState::Ready)?;registry.record_materialization(id);diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rsindex 3408b5aa9..cad4f96f3 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/realm_registry.rs@@ -4,6 +4,9 @@ use std::rc::Rc;use anyhow::{Result, anyhow};use super::metadata::{InterfaceId, RealmKind};+use crate::util::{+ register_intrinsic_interface, registered_intrinsic_constructor, registered_intrinsic_prototype,+};#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub(super) enum RealmInterfaceState {@@ -102,10 +105,66 @@ impl IntrinsicInterfaceRegistry {)})?;*slot = state;+ if state == RealmInterfaceState::Failed {+ self.objects.borrow_mut()[id.index()] = None;+ }Ok(())}- pub(super) fn register_objects<'s>(+ /// Publishes the same intrinsic identities to both registries. Mark the+ /// interface in progress before either store changes, and make any failed+ /// publication terminal even if V8 has retained an immutable partial pair.+ pub(super) fn register_intrinsic_objects<'s>(+ &self,+ scope: &mut v8::PinScope<'s, '_>,+ global: v8::Local<'s, v8::Object>,+ id: InterfaceId,+ name: &str,+ constructor: v8::Local<'s, v8::Object>,+ prototype: v8::Local<'s, v8::Object>,+ public_interface: v8::Local<'s, v8::Object>,+ ) -> Result<()> {+ if self.state(id) == Some(RealmInterfaceState::Failed) {+ return Err(anyhow!("a previous materialization of `{name}` failed"));+ }+ self.set_state(id, RealmInterfaceState::Materializing)?;+ let result = (|| {+ // Validate and retain the Rust objects before writing the immutable+ // JS entries. Accessors expose them only once publication completes.+ self.register_objects(scope, id, constructor, prototype, public_interface)?;+ match (+ registered_intrinsic_constructor(scope, global, name),+ registered_intrinsic_prototype(scope, global, name),+ ) {+ (Some(existing_constructor), Some(existing_prototype)) => {+ if !existing_constructor.strict_equals(constructor.into())+ || !existing_prototype.strict_equals(prototype.into())+ {+ return Err(anyhow!(+ "intrinsic interface `{name}` was replaced after registration"+ ));+ }+ }+ (None, None) => {+ if !register_intrinsic_interface(scope, global, name, constructor, prototype) {+ return Err(anyhow!("failed to register intrinsic interface `{name}`"));+ }+ }+ _ => {+ return Err(anyhow!(+ "intrinsic interface `{name}` has partial registry state"+ ));+ }+ }+ self.set_state(id, RealmInterfaceState::Finalizing)+ })();+ if result.is_err() {+ self.set_state(id, RealmInterfaceState::Failed)?;+ }+ result+ }++ fn register_objects<'s>(&self,scope: &mut v8::PinScope<'s, '_>,id: InterfaceId,@@ -153,6 +212,12 @@ impl IntrinsicInterfaceRegistry {scope: &mut v8::PinScope<'s, '_>,id: InterfaceId,) -> Option<v8::Local<'s, v8::Object>> {+ if !matches!(+ self.state(id)?,+ RealmInterfaceState::Ready | RealmInterfaceState::Finalizing+ ) {+ return None;+ }let objects = self.objects.borrow();let object = objects.get(id.index())?.as_ref()?;Some(v8::Local::new(scope, &object.constructor))@@ -163,6 +228,12 @@ impl IntrinsicInterfaceRegistry {scope: &mut v8::PinScope<'s, '_>,id: InterfaceId,) -> Option<v8::Local<'s, v8::Object>> {+ if !matches!(+ self.state(id)?,+ RealmInterfaceState::Ready | RealmInterfaceState::Finalizing+ ) {+ return None;+ }let objects = self.objects.borrow();let object = objects.get(id.index())?.as_ref()?;Some(v8::Local::new(scope, &object.prototype))@@ -173,6 +244,12 @@ impl IntrinsicInterfaceRegistry {scope: &mut v8::PinScope<'s, '_>,id: InterfaceId,) -> Option<v8::Local<'s, v8::Object>> {+ if !matches!(+ self.state(id)?,+ RealmInterfaceState::Ready | RealmInterfaceState::Finalizing+ ) {+ return None;+ }let objects = self.objects.borrow();let object = objects.get(id.index())?.as_ref()?;Some(v8::Local::new(scope, &object.public_interface))@@ -230,6 +307,9 @@ mod tests {registry.register_objects(scope, id, constructor, prototype, public_interface).expect("realm interface objects should register");+ registry+ .set_state(id, RealmInterfaceState::Ready)+ .expect("realm interface objects should become ready");context.detach_global();assert!(diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rsindex ecd214b5c..5df3713fc 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/tests.rs@@ -297,6 +297,278 @@ fn entered_context_template_build_is_isolate_cached_and_realm_neutral() {assert_eq!(registry.build_count(id), 1);}+#[test]+fn uninitialized_dom_string_map_adopts_its_registered_intrinsics() {+ crate::ensure_v8_for_test();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let registry = super::template_registry::ExposedInterfaceTemplateRegistry::install(+ scope,+ crate::context_bootstrap::specs::constructor_specs(),+ super::metadata::TemplateBuildProfile::Window,+ )+ .expect("template registry");+ let realm = super::realm_registry::IntrinsicInterfaceRegistry::initialize_for_current_context(+ scope,+ registry.len(),+ super::RealmKind::Window,+ )+ .expect("realm registry");+ let id = registry+ .id_by_name("DOMStringMap")+ .expect("dataset interface");+ let constructor = registry+ .get_or_build_template(scope, id)+ .expect("dataset template")+ .get_function(scope)+ .expect("dataset constructor");+ let prototype = crate::util::constructor_prototype_object(scope, constructor.into())+ .expect("dataset prototype");+ let global = context.global(scope);+ assert!(crate::util::register_intrinsic_interface(+ scope,+ global,+ "DOMStringMap",+ constructor.into(),+ prototype,+ ));+ assert_eq!(+ global.set_lazy_data_property(+ scope,+ v8str(scope, "DOMStringMap").into(),+ counting_lazy_getter,+ ),+ Some(true)+ );+ reset_lazy_getter_calls();++ let recovered = super::ensure_intrinsic_interface_prototype(scope, "DOMStringMap")+ .expect("a complete trusted registration must recover the dataset prototype");++ assert!(recovered.strict_equals(prototype.into()));+ assert_eq!(+ realm.state(id),+ Some(super::realm_registry::RealmInterfaceState::Ready)+ );+ assert!(+ super::ensure_intrinsic_interface_constructor(scope, "DOMStringMap")+ .expect("recovered dataset constructor")+ .strict_equals(constructor.into())+ );+ assert!(+ super::materialize::materialize_interface(scope, id)+ .expect("repeated dataset materialization")+ .strict_equals(constructor.into())+ );+ assert_eq!(registry.build_count(id), 1);+ assert_eq!(+ lazy_getter_calls(),+ 0,+ "recovery must not read the public binding"+ );+}++#[test]+fn incomplete_intrinsic_registration_marks_materialization_failed() {+ crate::ensure_v8_for_test();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let registry = super::template_registry::ExposedInterfaceTemplateRegistry::install(+ scope,+ crate::context_bootstrap::specs::constructor_specs(),+ super::metadata::TemplateBuildProfile::Window,+ )+ .expect("template registry");+ let realm = super::realm_registry::IntrinsicInterfaceRegistry::initialize_for_current_context(+ scope,+ registry.len(),+ super::RealmKind::Window,+ )+ .expect("realm registry");+ let id = registry+ .id_by_name("DOMStringMap")+ .expect("dataset interface");+ let global = context.global(scope);+ crate::util::initialize_intrinsic_interface_registry(scope, global);+ let prototypes = crate::util::get_private_object(scope, global, "__moliIntrinsicPrototypes")+ .expect("private prototype registry");+ assert_eq!(+ prototypes.set_integrity_level(scope, v8::IntegrityLevel::Frozen),+ Some(true)+ );+ let constructor = v8::Object::new(scope);+ let prototype = v8::Object::new(scope);+ assert!(!crate::util::register_intrinsic_interface(+ scope,+ global,+ "DOMStringMap",+ constructor,+ prototype,+ ));+ assert!(crate::util::registered_intrinsic_constructor(scope, global, "DOMStringMap").is_some());+ assert!(crate::util::registered_intrinsic_prototype(scope, global, "DOMStringMap").is_none());++ let error = super::ensure_intrinsic_interface_prototype(scope, "DOMStringMap")+ .expect_err("an incomplete pair must not supply a dataset prototype");++ assert!(error.to_string().contains("partial registry state"));+ assert_eq!(+ realm.state(id),+ Some(super::realm_registry::RealmInterfaceState::Failed)+ );+ let repeated_error = super::ensure_intrinsic_interface_prototype(scope, "DOMStringMap")+ .expect_err("a failed materialization must not retry the partial registration");+ assert!(+ repeated_error+ .to_string()+ .contains("previous materialization")+ );+ assert_eq!(registry.build_count(id), 0);+}++#[test]+fn failed_eager_intrinsic_capture_does_not_leave_an_uninitialized_interface() {+ crate::ensure_v8_for_test();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let registry = super::template_registry::ExposedInterfaceTemplateRegistry::install(+ scope,+ crate::context_bootstrap::specs::constructor_specs(),+ super::metadata::TemplateBuildProfile::Window,+ )+ .expect("template registry");+ let realm = super::realm_registry::IntrinsicInterfaceRegistry::initialize_for_current_context(+ scope,+ registry.len(),+ super::RealmKind::Window,+ )+ .expect("realm registry");+ let global = context.global(scope);+ let error_constructor = crate::util::constructor_object(scope, global, "Error")+ .expect("ECMAScript Error constructor");+ let error_prototype = crate::util::constructor_prototype_object(scope, error_constructor)+ .expect("ECMAScript Error prototype");+ assert!(crate::util::register_intrinsic_interface(+ scope,+ global,+ "Error",+ error_constructor,+ error_prototype,+ ));+ let id = registry+ .id_by_name("Window")+ .expect("eager Window interface");+ let constructor = v8::Object::new(scope);+ let prototype = v8::Object::new(scope);+ assert_eq!(+ constructor.set(scope, v8str(scope, "prototype").into(), prototype.into()),+ Some(true)+ );+ assert_eq!(+ global.set(scope, v8str(scope, "Window").into(), constructor.into()),+ Some(true)+ );+ let prototypes = crate::util::get_private_object(scope, global, "__moliIntrinsicPrototypes")+ .expect("private prototype registry");+ assert_eq!(+ prototypes.set_integrity_level(scope, v8::IntegrityLevel::Frozen),+ Some(true)+ );++ super::capture_eager_intrinsic_interfaces(scope, global, super::RealmKind::Window)+ .expect_err("a failed private registration must abort eager capture");++ assert_eq!(+ realm.state(id),+ Some(super::realm_registry::RealmInterfaceState::Failed)+ );+ assert!(realm.constructor(scope, id).is_none());+ assert!(realm.prototype(scope, id).is_none());+ assert!(realm.public_interface(scope, id).is_none());+ assert!(super::ensure_intrinsic_interface_prototype(scope, "Window").is_err());+}++#[test]+fn failed_intrinsic_finalization_does_not_expose_registered_objects() {+ crate::ensure_v8_for_test();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let registry = super::template_registry::ExposedInterfaceTemplateRegistry::install(+ scope,+ crate::context_bootstrap::specs::constructor_specs(),+ super::metadata::TemplateBuildProfile::Window,+ )+ .expect("template registry");+ let realm = super::realm_registry::IntrinsicInterfaceRegistry::initialize_for_current_context(+ scope,+ registry.len(),+ super::RealmKind::Window,+ )+ .expect("realm registry");+ let id = registry.id_by_name("Crypto").expect("Crypto interface");+ let constructor = registry+ .get_or_build_template(scope, id)+ .expect("Crypto template")+ .get_function(scope)+ .expect("Crypto constructor");+ let prototype = crate::util::constructor_prototype_object(scope, constructor.into())+ .expect("Crypto prototype");+ let global = context.global(scope);+ assert!(crate::util::register_intrinsic_interface(+ scope,+ global,+ "Crypto",+ constructor.into(),+ prototype,+ ));+ let subtle_crypto_available = v8::Boolean::new(scope, true);+ crate::util::set_private_value(+ scope,+ global,+ "__moliWindowCryptoSubtleAvailable",+ subtle_crypto_available.into(),+ );+ assert_eq!(+ prototype.set_integrity_level(scope, v8::IntegrityLevel::Frozen),+ Some(true)+ );++ super::ensure_intrinsic_interface_prototype(scope, "Crypto")+ .expect_err("a frozen prototype must reject secure-context finalization");++ assert_eq!(+ realm.state(id),+ Some(super::realm_registry::RealmInterfaceState::Failed)+ );+ assert!(realm.constructor(scope, id).is_none());+ assert!(realm.prototype(scope, id).is_none());+ assert!(realm.public_interface(scope, id).is_none());+ assert!(super::ensure_intrinsic_interface_constructor(scope, "Crypto").is_err());+ assert!(super::ensure_intrinsic_interface_prototype(scope, "Crypto").is_err());+ assert!(super::materialized_intrinsic_interface_prototype(scope, "Crypto").is_none());+ assert_eq!(registry.materialization_count(id), 0);+ assert!(+ crate::util::registered_intrinsic_constructor(scope, global, "Crypto")+ .is_some_and(|value| value.strict_equals(constructor.into()))+ );+ assert!(+ crate::util::registered_intrinsic_prototype(scope, global, "Crypto")+ .is_some_and(|value| value.strict_equals(prototype.into()))+ );+}+#[test]fn worker_realm_lazy_properties_follow_chromium_exposure_sets() {fn own_properties(realm: super::RealmKind) -> Vec<bool> {