Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(runtime): share Context state and V8 finalizers
ldm04f9a3a1bc62e
diff --git a/moli-renderer-v8/src/common_runtime.rs b/moli-renderer-v8/src/common_runtime.rsnew file mode 100644index 000000000..a086c60e8--- /dev/null+++ b/moli-renderer-v8/src/common_runtime.rs@@ -0,0 +1,188 @@+//! Shared owner-local Web API state and its Context entry point.+//!+//! A Context locates its owner through a weak binding. Window Realm tokens and+//! Worker run state remain the authoritative execution identities; retaining a+//! Context must not independently root its host or its callback graph.++use std::{+ cell::{Cell, RefCell},+ rc::{Rc, Weak},+};++use crate::{+ native_bridge::JsContextHost,+ util::{ContextHostLifecycle, page_context_is_disconnected},+ v8_finalizer::V8FinalizerRegistry,+ worker::WorkerGlobalState,+};++#[derive(Default)]+pub(crate) struct CommonRuntimeState {+ pub(crate) finalizers: RefCell<V8FinalizerRegistry>,+}++impl CommonRuntimeState {+ pub(crate) fn clear_for_context_teardown(&self) {+ // Cleanup may reenter native components. Drop the component borrow+ // before executing any cleanup, just as registration releases owner+ // borrows before allocating a V8 weak handle.+ let mut finalizers = std::mem::take(&mut *self.finalizers.borrow_mut());+ finalizers.clear_for_context_teardown();+ }++ #[cfg(test)]+ pub(crate) fn finalizer_count(&self) -> usize {+ self.finalizers.borrow().len()+ }+}++pub(crate) struct CommonRuntimeBinding {+ common: Weak<CommonRuntimeState>,+ owner: RuntimeOwner,+}++enum RuntimeOwner {+ Window {+ host_ptr: *mut JsContextHost,+ lifecycle: Weak<Cell<ContextHostLifecycle>>,+ },+ Worker {+ state: Weak<RefCell<WorkerGlobalState>>,+ },+}++impl CommonRuntimeBinding {+ pub(crate) fn install_window(+ context: v8::Local<'_, v8::Context>,+ common: &Rc<CommonRuntimeState>,+ host_ptr: *mut JsContextHost,+ lifecycle: &Rc<Cell<ContextHostLifecycle>>,+ ) {+ if let Some(existing) = context.get_slot::<Self>() {+ assert!(+ Weak::ptr_eq(&existing.common, &Rc::downgrade(common))+ && matches!(existing.owner, RuntimeOwner::Window { host_ptr: installed, .. } if installed == host_ptr),+ "a Context's common runtime owner must not be rebound"+ );+ return;+ }+ let previous = context.set_slot(Rc::new(Self {+ common: Rc::downgrade(common),+ owner: RuntimeOwner::Window {+ host_ptr,+ lifecycle: Rc::downgrade(lifecycle),+ },+ }));+ debug_assert!(previous.is_none());+ }++ pub(crate) fn install_worker(+ context: v8::Local<'_, v8::Context>,+ state: &Rc<RefCell<WorkerGlobalState>>,+ ) {+ let common = Rc::clone(&state.borrow().common);+ let previous = context.set_slot(Rc::new(Self {+ common: Rc::downgrade(&common),+ owner: RuntimeOwner::Worker {+ state: Rc::downgrade(state),+ },+ }));+ assert!(+ previous.is_none(),+ "a Worker Context must have one common runtime binding"+ );+ }++ pub(crate) fn from_scope(scope: &mut v8::PinScope<'_, '_>) -> Option<Rc<Self>> {+ let binding = scope.get_current_context().get_slot::<Self>()?;+ binding.validate_context(scope)?;+ Some(binding)+ }++ pub(crate) fn runtime(&self) -> Option<Rc<CommonRuntimeState>> {+ self.common.upgrade()+ }++ fn validate_context(&self, scope: &mut v8::PinScope<'_, '_>) -> Option<()> {+ let context = scope.get_current_context();+ let installed = context.get_slot::<Self>()?;+ if !std::ptr::eq(self, installed.as_ref()) {+ return None;+ }+ self.runtime()?;+ match &self.owner {+ RuntimeOwner::Window { .. } => {+ if page_context_is_disconnected(context) {+ return None;+ }+ self.window_host_ptr()?;+ }+ RuntimeOwner::Worker { state, .. } => {+ state.upgrade()?;+ }+ }+ Some(())+ }++ pub(crate) fn window_host_ptr(&self) -> Option<*mut JsContextHost> {+ self.runtime()?;+ let RuntimeOwner::Window {+ host_ptr,+ lifecycle,+ } = &self.owner+ else {+ return None;+ };+ (lifecycle.upgrade()?.get() != ContextHostLifecycle::Destroyed).then_some(*host_ptr)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn context_bindings_share_components_without_rooting_or_confusing_owners() {+ crate::ensure_v8_for_test();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let first = v8::Context::new(scope, Default::default());+ let second = v8::Context::new(scope, Default::default());+ let other = v8::Context::new(scope, Default::default());+ let common = Rc::new(CommonRuntimeState::default());+ let other_common = Rc::new(CommonRuntimeState::default());+ let lifecycle = Rc::new(Cell::new(ContextHostLifecycle::Active));+ let other_lifecycle = Rc::new(Cell::new(ContextHostLifecycle::Active));+ // This test exercises component ownership and Context identity only.+ // The opaque host address is never dereferenced by a host API.+ let host = std::ptr::NonNull::<JsContextHost>::dangling().as_ptr();+ CommonRuntimeBinding::install_window(first, &common, host, &lifecycle);+ CommonRuntimeBinding::install_window(second, &common, host, &lifecycle);+ CommonRuntimeBinding::install_window(other, &other_common, host, &other_lifecycle);+ let first_binding = {+ let scope = &mut v8::ContextScope::new(scope, first);+ let binding = CommonRuntimeBinding::from_scope(scope).unwrap();+ assert!(Rc::ptr_eq(&binding.runtime().unwrap(), &common));+ binding+ };+ {+ let scope = &mut v8::ContextScope::new(scope, second);+ let binding = CommonRuntimeBinding::from_scope(scope).unwrap();+ assert!(Rc::ptr_eq(&binding.runtime().unwrap(), &common));+ assert!(!Rc::ptr_eq(&binding, &first_binding));+ assert!(first_binding.validate_context(scope).is_none());+ }+ {+ let scope = &mut v8::ContextScope::new(scope, other);+ let binding = CommonRuntimeBinding::from_scope(scope).unwrap();+ assert!(!Rc::ptr_eq(&binding.runtime().unwrap(), &common));+ other_lifecycle.set(ContextHostLifecycle::Destroyed);+ assert!(CommonRuntimeBinding::from_scope(scope).is_none());+ }+ drop(common);+ let scope = &mut v8::ContextScope::new(scope, first);+ assert!(CommonRuntimeBinding::from_scope(scope).is_none());+ assert!(first_binding.runtime().is_none());+ }+}diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rsindex eb11cc0c5..9425bba00 100644--- a/moli-renderer-v8/src/lib.rs+++ b/moli-renderer-v8/src/lib.rs@@ -33,6 +33,7 @@ mod broadcast_channel_runtime;mod callback_invocation;#[cfg(test)]mod chromium_property_surface;+mod common_runtime;mod content_security_policy;mod context_bootstrap;mod cross_origin_isolation;diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rsindex bb538fa69..1cb330e59 100644--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs@@ -355,7 +355,7 @@ impl JsContextHost {retained_document_runtime: None,published_document_host: false,page_default_context: None,- v8_finalizers: crate::v8_finalizer::V8FinalizerRegistry::default(),+ common: Rc::new(crate::common_runtime::CommonRuntimeState::default()),bridge: NativeDomBridge::new(bindings),dom_agent_state: crate::runtime::RendererDomAgentState::new(backend_node_registry.clone(),diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex 373c426c0..b5b44ffc4 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -831,7 +831,7 @@ pub(crate) struct JsContextHost {context_host_lifecycle: Rc<Cell<crate::util::ContextHostLifecycle>>,deferred_context_host_release_queue: crate::script_vm::RendererDeferredContextHostReleaseQueue,page_default_context: Option<v8::Weak<v8::Context>>,- pub(crate) v8_finalizers: crate::v8_finalizer::V8FinalizerRegistry,+ pub(crate) common: Rc<crate::common_runtime::CommonRuntimeState>,pub(super) bridge: NativeDomBridge,backend_node_registry: SharedRendererBackendNodeRegistry,dom_agent_state: crate::runtime::RendererDomAgentState,@@ -1352,6 +1352,6 @@ impl Drop for JsContextHost {self.close_page_context_resources_for_teardown();self.context_host_lifecycle.set(crate::util::ContextHostLifecycle::Destroyed);- self.v8_finalizers.clear_for_context_teardown();+ self.common.clear_for_context_teardown();}}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.rsindex 20970a7a3..b99bb598b 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@@ -2109,7 +2109,7 @@ fn page_context_teardown_preserves_finalizers_for_retained_native_objects() {.expect("context-owned finalizer objects should evaluate");assert_eq!(created, "96");assert!(- vm._context_host.borrow().v8_finalizers.len() >= 128,+ vm._context_host.borrow().common.finalizer_count() >= 128,"CSS declaration/rule-tree and Blob objects should be tracked by the page context owner");assert!(@@ -2122,7 +2122,7 @@ fn page_context_teardown_preserves_finalizers_for_retained_native_objects() {vm.close_page_context_resources_for_context_teardown();assert!(- vm._context_host.borrow().v8_finalizers.len() >= 128,+ vm._context_host.borrow().common.finalizer_count() >= 128,"retiring active execution must preserve native objects retained by author code");assert_eq!(diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rsindex e722be5b4..b1ef55c35 100644--- a/moli-renderer-v8/src/util.rs+++ b/moli-renderer-v8/src/util.rs@@ -559,6 +559,13 @@ pub(super) fn install_context_host_pointer_slot(host_lifecycle.get() == ContextHostLifecycle::Active,"a retired JsContextHost must not be installed into a V8 context");+ let common = Rc::clone(&unsafe { &*host_ptr.as_ptr() }.common);+ crate::common_runtime::CommonRuntimeBinding::install_window(+ context,+ &common,+ host_ptr.as_ptr(),+ &host_lifecycle,+ );if let Some(existing) = context.get_slot::<ContextHostPointerSlot>() {assert!(existing.host_ptr == host_ptr && Rc::ptr_eq(&existing.host_lifecycle, &host_lifecycle),diff --git a/moli-renderer-v8/src/v8_finalizer.rs b/moli-renderer-v8/src/v8_finalizer.rsindex 488971a88..022cf7519 100644--- a/moli-renderer-v8/src/v8_finalizer.rs+++ b/moli-renderer-v8/src/v8_finalizer.rs@@ -52,13 +52,17 @@ impl Drop for ContextOwnedV8Finalizer {}impl V8FinalizerRegistry {- fn push(&mut self, entry: ContextOwnedV8Finalizer) {+ fn push(&mut self, entry: ContextOwnedV8Finalizer) -> Vec<ContextOwnedV8Finalizer> {self.entries.push(entry);self.insertions_since_compaction = self.insertions_since_compaction.saturating_add(1);if self.insertions_since_compaction >= FINALIZER_COMPACTION_INTERVAL {- self.entries.retain(|entry| !entry.weak.is_empty());self.insertions_since_compaction = 0;+ return self+ .entries+ .extract_if(.., |entry| entry.weak.is_empty())+ .collect();}+ Vec::new()}pub(crate) fn clear_for_context_teardown(&mut self) {@@ -90,22 +94,58 @@ pub(crate) fn track_context_owned_v8_finalizer() {let cleanup: FinalizerCleanup = Box::new(cleanup);- if let Some(worker_state) = crate::worker::get_worker_state(scope) {- let entry = ContextOwnedV8Finalizer::new(scope, object, cleanup);- worker_state.borrow_mut().v8_finalizers.push(entry);- return;- }-- let host_ptr = crate::util::context_host_ptr_from_global_bridge(scope)+ let common = crate::common_runtime::CommonRuntimeBinding::from_scope(scope)+ .and_then(|binding| binding.runtime()).expect("V8 finalizer object must belong to a page or worker context");let entry = ContextOwnedV8Finalizer::new(scope, object, cleanup);- unsafe { &mut *host_ptr }.v8_finalizers.push(entry);+ let retired = common.finalizers.borrow_mut().push(entry);+ // Compaction can release a pending native cleanup as well. Keep those+ // drops outside the component borrow, matching explicit teardown.+ drop(retired);}#[cfg(test)]mod tests {use super::*;+ #[test]+ fn common_runtime_teardown_releases_borrow_before_running_cleanup() {+ use crate::common_runtime::{CommonRuntimeBinding, CommonRuntimeState};+ crate::ensure_v8_for_test();+ let common = Rc::new(CommonRuntimeState::default());+ let lifecycle = Rc::new(Cell::new(crate::util::ContextHostLifecycle::Active));+ let cleanup_count = Rc::new(Cell::new(0));+ let mut isolate = v8::Isolate::new(Default::default());+ {+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let context = v8::Context::new(scope, Default::default());+ // Finalizer registration uses only the shared component, so this+ // owner identity does not need to dereference a Document host.+ CommonRuntimeBinding::install_window(+ context,+ &common,+ std::ptr::NonNull::<crate::native_bridge::JsContextHost>::dangling().as_ptr(),+ &lifecycle,+ );+ let scope = &mut v8::ContextScope::new(scope, context);+ let object = v8::Object::new(scope);+ let owner = Rc::downgrade(&common);+ let count = Rc::clone(&cleanup_count);+ track_context_owned_v8_finalizer(scope, object, move || {+ assert_eq!(owner.upgrade().unwrap().finalizer_count(), 0);+ count.set(count.get() + 1);+ });+ assert_eq!(common.finalizer_count(), 1);+ }+ common.clear_for_context_teardown();+ common.clear_for_context_teardown();+ assert_eq!(common.finalizer_count(), 0);+ assert_eq!(cleanup_count.get(), 1);+ drop(common);+ drop(isolate);+ }+#[test]fn context_teardown_runs_cleanup_exactly_once_before_isolate_drop() {crate::ensure_v8_for_test();@@ -119,14 +159,14 @@ mod tests {let scope = &mut v8::ContextScope::new(scope, context);let object = v8::Object::new(scope);let cleanup_count_for_callback = Rc::clone(&cleanup_count);- registry.push(ContextOwnedV8Finalizer::new(+ drop(registry.push(ContextOwnedV8Finalizer::new(scope,object,Box::new(move || {cleanup_count_for_callback.set(cleanup_count_for_callback.get().saturating_add(1));}),- ));+ )));assert_eq!(registry.len(), 1);}diff --git a/moli-renderer-v8/src/worker/global_scope/bootstrap.rs b/moli-renderer-v8/src/worker/global_scope/bootstrap.rsindex e587f61eb..c8fb77b44 100644--- a/moli-renderer-v8/src/worker/global_scope/bootstrap.rs+++ b/moli-renderer-v8/src/worker/global_scope/bootstrap.rs@@ -117,6 +117,10 @@ pub(in crate::worker) fn install_worker_global_scope<'s>(state: Rc<RefCell<WorkerGlobalState>>,worker_templates: Option<&PreparedWorkerGlobalScopeTemplates>,) -> Result<()> {+ crate::common_runtime::CommonRuntimeBinding::install_worker(+ scope.get_current_context(),+ &state,+ );// Store state pointer as an external on the global so callbacks can find it.let state_ptr = Rc::into_raw(state.clone()) as *mut c_void;let external = v8::External::new(scope, state_ptr);diff --git a/moli-renderer-v8/src/worker/global_scope/state.rs b/moli-renderer-v8/src/worker/global_scope/state.rsindex 495985400..f995caaa5 100644--- a/moli-renderer-v8/src/worker/global_scope/state.rs+++ b/moli-renderer-v8/src/worker/global_scope/state.rs@@ -5,9 +5,8 @@ use super::*;pub(crate) const WORKER_STATE_SLOT: &str = "__workerState";pub(crate) struct WorkerGlobalState {- /// Weak handles and native cleanups owned by this worker isolate. Worker- /// teardown clears this registry before `OwnedIsolate` is destroyed.- pub(crate) v8_finalizers: crate::v8_finalizer::V8FinalizerRegistry,+ /// Components shared with Window runtimes, owned by this Worker run.+ pub(crate) common: Rc<crate::common_runtime::CommonRuntimeState>,/// Channel to send messages back to the parent.pub(in crate::worker) parent_tx: mpsc::UnboundedSender<WorkerToParentMessage>,/// Internal wake channel used by worker-owned async runtime surfaces.diff --git a/moli-renderer-v8/src/worker/mod.rs b/moli-renderer-v8/src/worker/mod.rsindex 625e2642e..0fbec0bfe 100644--- a/moli-renderer-v8/src/worker/mod.rs+++ b/moli-renderer-v8/src/worker/mod.rs@@ -24,9 +24,9 @@ mod timer_callback;pub(crate) use data_url::decode_data_url_script_source;pub(crate) use global_scope::{- NestedWorkerContext, WORKER_STATE_SLOT, WorkerOpfsCompletion, WorkerWebCryptoCompletion,- cancel_worker_opfs_task, check_worker_websocket_csp, close_worker_websocket,- dispatch_worker_trusted_types_sink_violation_event,+ NestedWorkerContext, WORKER_STATE_SLOT, WorkerGlobalState, WorkerOpfsCompletion,+ WorkerWebCryptoCompletion, cancel_worker_opfs_task, check_worker_websocket_csp,+ close_worker_websocket, dispatch_worker_trusted_types_sink_violation_event,ensure_worker_opfs_directory_iterator_registry, ensure_worker_opfs_handle_registry,forget_nested_worker_context, forget_worker_broadcast_channel_wrapper,forget_worker_message_port_wrapper, get_worker_state,diff --git a/moli-renderer-v8/src/worker/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rsindex f4896d14e..3e0ee37b7 100644--- a/moli-renderer-v8/src/worker/thread/mod.rs+++ b/moli-renderer-v8/src/worker/thread/mod.rs@@ -1622,7 +1622,7 @@ async fn worker_main(.as_ref().map(|client| client.client_id);let state = Rc::new(RefCell::new(WorkerGlobalState {- v8_finalizers: crate::v8_finalizer::V8FinalizerRegistry::default(),+ common: Rc::new(crate::common_runtime::CommonRuntimeState::default()),parent_tx: parent_tx.clone(),worker_wake_tx,termination_requested: Arc::clone(&termination_requested),@@ -3352,10 +3352,8 @@ async fn worker_main(let ctx = v8::Local::new(scope, &context);runtime_inspector.context_destroyed(ctx);}- state- .borrow_mut()- .v8_finalizers- .clear_for_context_teardown();+ let common = Rc::clone(&state.borrow().common);+ common.clear_for_context_teardown();close_worker_owned_broadcast_channels(&state);close_worker_owned_message_ports(&state);resource_loader.finish_detach();