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(callbacks): use Context bindings for shared execution
ldm03bd72ea8b410
diff --git a/moli-renderer-v8/src/common_runtime.rs b/moli-renderer-v8/src/common_runtime.rsindex a086c60e8..523eafde6 100644--- a/moli-renderer-v8/src/common_runtime.rs+++ b/moli-renderer-v8/src/common_runtime.rs@@ -7,6 +7,10 @@use std::{cell::{Cell, RefCell},rc::{Rc, Weak},+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },};use crate::{@@ -48,9 +52,16 @@ enum RuntimeOwner {},Worker {state: Weak<RefCell<WorkerGlobalState>>,+ termination_requested: Arc<AtomicBool>,},}+#[derive(Clone, Copy)]+pub(crate) enum RuntimeExecutionContext {+ Window(*mut JsContextHost),+ Worker,+}+impl CommonRuntimeBinding {pub(crate) fn install_window(context: v8::Local<'_, v8::Context>,@@ -80,11 +91,18 @@ impl CommonRuntimeBinding {context: v8::Local<'_, v8::Context>,state: &Rc<RefCell<WorkerGlobalState>>,) {- let common = Rc::clone(&state.borrow().common);+ let (common, termination_requested) = {+ let state = state.borrow();+ (+ Rc::clone(&state.common),+ Arc::clone(&state.termination_requested),+ )+ };let previous = context.set_slot(Rc::new(Self {common: Rc::downgrade(&common),owner: RuntimeOwner::Worker {state: Rc::downgrade(state),+ termination_requested,},}));assert!(@@ -124,6 +142,17 @@ impl CommonRuntimeBinding {Some(())}+ pub(crate) fn execution_context(+ &self,+ scope: &mut v8::PinScope<'_, '_>,+ ) -> Option<RuntimeExecutionContext> {+ self.validate_context(scope)?;+ Some(match self.owner {+ RuntimeOwner::Window { host_ptr, .. } => RuntimeExecutionContext::Window(host_ptr),+ RuntimeOwner::Worker { .. } => RuntimeExecutionContext::Worker,+ })+ }+pub(crate) fn window_host_ptr(&self) -> Option<*mut JsContextHost> {self.runtime()?;let RuntimeOwner::Window {@@ -135,6 +164,27 @@ impl CommonRuntimeBinding {};(lifecycle.upgrade()?.get() != ContextHostLifecycle::Destroyed).then_some(*host_ptr)}++ pub(crate) fn worker_can_invoke(&self) -> bool {+ self.runtime().is_some()+ && match &self.owner {+ RuntimeOwner::Worker {+ state,+ termination_requested,+ } => state.upgrade().is_some() && !termination_requested.load(Ordering::Acquire),+ RuntimeOwner::Window { .. } => false,+ }+ }++ pub(crate) fn worker_can_deliver_task(&self) -> bool {+ self.runtime().is_some()+ && match &self.owner {+ RuntimeOwner::Worker { state, .. } => state+ .upgrade()+ .is_some_and(|state| state.borrow().callback_task_delivery_allowed()),+ RuntimeOwner::Window { .. } => false,+ }+ }}#[cfg(test)]@@ -185,4 +235,22 @@ mod tests {assert!(CommonRuntimeBinding::from_scope(scope).is_none());assert!(first_binding.runtime().is_none());}++ #[test]+ fn missing_context_binding_rejects_callback_before_reading_its_carrier() {+ 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 context = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, context);+ let object = v8::Object::new(scope);+ assert!(CommonRuntimeBinding::from_scope(scope).is_none());+ assert!(+ crate::webidl_callback_execution::PreparedWebIdlCallbackExecution::from_traced(+ scope, object+ )+ .is_none()+ );+ }}diff --git a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rs b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rsindex 7c86c903e..bddddcea5 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_observer_runtime/registration.rs@@ -7,10 +7,10 @@use moli_webidl_callback::{PreparedWebIdlCallbackFunction, WebIdlCallbackFunction};use super::*;+use crate::common_runtime::{CommonRuntimeBinding, RuntimeExecutionContext};use crate::observer_runtime::{ObserverCallbackId, ObserverCallbackResidence};-use crate::util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value};+use crate::util::{get_private_value, set_private_value};use crate::webidl_callback_execution::PreparedWebIdlCallbackExecution;-use crate::worker::{get_worker_state, worker_global_is_closed, worker_termination_requested};enum RegistrationEnvironment {Window {@@ -23,6 +23,7 @@ enum RegistrationEnvironment {pub(super) struct PerformanceObserverRegistration<'s> {observer: v8::Local<'s, v8::Object>,environment: RegistrationEnvironment,+ binding: std::rc::Rc<CommonRuntimeBinding>,}pub(super) fn register_performance_observer_callback<'s>(@@ -35,13 +36,13 @@ pub(super) fn register_performance_observer_callback<'s>(v8::Local<'s, v8::Object>,v8::Local<'s, v8::Object>,)> {- if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {+ let binding = CommonRuntimeBinding::from_scope(scope)?;+ if let RuntimeExecutionContext::Window(host_ptr) = binding.execution_context(scope)? {let (id, callback, relevant, incumbent) =crate::observer_runtime::register_callback(scope, host_ptr, observer, callback).into_parts();return Some((id.as_u32(), callback, relevant, incumbent));}- get_worker_state(scope)?;let value = v8::Local::<v8::Object>::try_from(callback.value(scope)).ok()?;let relevant = callback.relevant_context(scope).global(scope);let incumbent = callback.incumbent_context(scope).global(scope);@@ -57,21 +58,24 @@ impl<'s> PerformanceObserverRegistration<'s> {) -> Option<Self> {let id = get_private_value(scope, observer, PERFORMANCE_OBSERVER_CALLBACK_ID_SLOT)?.number_value(scope)?;- let environment = if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {- RegistrationEnvironment::Window {+ let binding = CommonRuntimeBinding::from_scope(scope)?;+ let environment = match binding.execution_context(scope)? {+ RuntimeExecutionContext::Window(host_ptr) => RegistrationEnvironment::Window {host_ptr,callback_id: ObserverCallbackId::from_number(id)?,+ },+ RuntimeExecutionContext::Worker => {+ if id != 0.0 || observer.get_creation_context(scope)? != scope.get_current_context()+ {+ return None;+ }+ RegistrationEnvironment::Worker}- } else {- get_worker_state(scope)?;- if id != 0.0 || observer.get_creation_context(scope)? != scope.get_current_context() {- return None;- }- RegistrationEnvironment::Worker};Some(Self {observer,environment,+ binding,})}@@ -82,10 +86,7 @@ impl<'s> PerformanceObserverRegistration<'s> {callback_id,} => crate::observer_runtime::callback_is_current(host_ptr, callback_id),RegistrationEnvironment::Worker => {- get_worker_state(scope).is_some()- && !worker_global_is_closed(scope)- && !worker_termination_requested(scope)- && !scope.is_execution_terminating()+ self.binding.worker_can_deliver_task() && !scope.is_execution_terminating()}}}@@ -179,7 +180,7 @@ impl<'s> PerformanceObserverRegistration<'s> {incumbent,);crate::observer_runtime::prepare_callback(scope, host_ptr, residence)?- .into_execution(host_ptr)+ .into_execution(scope, host_ptr)}RegistrationEnvironment::Worker => {let context = self.observer.get_creation_context(scope)?;@@ -187,9 +188,7 @@ impl<'s> PerformanceObserverRegistration<'s> {let incumbent = incumbent.get_creation_context(scope)?;let callback =PreparedWebIdlCallbackFunction::try_new(scope, callback, relevant, incumbent)?;- Some(PreparedWebIdlCallbackExecution::worker(- scope, callback, context,- ))+ PreparedWebIdlCallbackExecution::worker(scope, callback, context)}}}@@ -206,11 +205,11 @@ pub(super) fn performance_observer_callback_is_current<'s>(pub(super) fn active_performance_observers<'s>(scope: &mut v8::PinScope<'s, '_>,) -> Vec<v8::Local<'s, v8::Object>> {- if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {- return crate::observer_runtime::active_performance_observer_callbacks(scope, host_ptr);- }- if get_worker_state(scope).is_none() {+ let Some(binding) = CommonRuntimeBinding::from_scope(scope) else {return Vec::new();+ };+ if let Some(RuntimeExecutionContext::Window(host_ptr)) = binding.execution_context(scope) {+ return crate::observer_runtime::active_performance_observer_callbacks(scope, host_ptr);}let Some(registry) = global_queue_array(scope, PERFORMANCE_OBSERVER_REGISTRY_SLOT) else {return Vec::new();diff --git a/moli-renderer-v8/src/observer_runtime/callback.rs b/moli-renderer-v8/src/observer_runtime/callback.rsindex f89a8c9a4..b360383ac 100644--- a/moli-renderer-v8/src/observer_runtime/callback.rs+++ b/moli-renderer-v8/src/observer_runtime/callback.rs@@ -329,6 +329,7 @@ impl PreparedObserverCallback {/// Window/Worker invocation and exception-reporting adapter.pub(crate) fn into_execution(self,+ scope: &mut v8::PinScope<'_, '_>,host_ptr: *mut JsContextHost,) -> Option<PreparedWebIdlCallbackExecution> {let PreparedWindowWebIdlCallbackFunction::Live {@@ -338,12 +339,13 @@ impl PreparedObserverCallback {else {return None;};- Some(PreparedWebIdlCallbackExecution::window(+ PreparedWebIdlCallbackExecution::window(+ scope,callback,host_ptr,Some(self.observer_identity?),relevant_identity,- ))+ )}pub(crate) fn relevant_context<'s>(diff --git a/moli-renderer-v8/src/webidl_callback_execution.rs b/moli-renderer-v8/src/webidl_callback_execution.rsindex 2aa9b90ed..41d1a4f16 100644--- a/moli-renderer-v8/src/webidl_callback_execution.rs+++ b/moli-renderer-v8/src/webidl_callback_execution.rs@@ -6,16 +6,14 @@use moli_webidl_callback::{PreparedWebIdlCallbackFunction, invoke_webidl_callback_function};use crate::{+ common_runtime::{CommonRuntimeBinding, RuntimeExecutionContext},exception_reporting::{CallbackExceptionLogLevel, V8ExceptionReport, invoke_callback_with_report,},host::report_event_callback_exception,native_bridge::{JsContextHost, WindowExecutionContextIdentity},- util::context_host_ptr_from_global_bridge,v8_traced_webidl_callback::V8TracedWebIdlCallbackFunction,- worker::{- dispatch_current_worker_callback_exception, get_worker_state, worker_termination_requested,- },+ worker::dispatch_current_worker_callback_exception,};/// A short-lived invocation snapshot. It must not be retained as an async@@ -23,6 +21,7 @@ use crate::{pub(crate) struct PreparedWebIdlCallbackExecution {callback: PreparedWebIdlCallbackFunction,environment: CallbackExecutionEnvironment,+ binding: std::rc::Rc<CommonRuntimeBinding>,}pub(crate) enum WebIdlCallbackExecutionOutcome<R, E> {@@ -33,7 +32,6 @@ pub(crate) enum WebIdlCallbackExecutionOutcome<R, E> {enum CallbackExecutionEnvironment {Window {- host_ptr: *mut JsContextHost,// Some API registrations, including observers, authorize both the// API object's owner and the callback's potentially different Realm.owner_identity: Option<WindowExecutionContextIdentity>,@@ -46,52 +44,76 @@ enum CallbackExecutionEnvironment {impl PreparedWebIdlCallbackExecution {pub(crate) fn window(+ scope: &mut v8::PinScope<'_, '_>,callback: PreparedWebIdlCallbackFunction,host_ptr: *mut JsContextHost,owner_identity: Option<WindowExecutionContextIdentity>,callback_identity: WindowExecutionContextIdentity,- ) -> Self {- Self {+ ) -> Option<Self> {+ let binding = CommonRuntimeBinding::from_scope(scope)?;+ if binding.window_host_ptr()? != host_ptr {+ return None;+ }+ Some(Self {callback,environment: CallbackExecutionEnvironment::Window {- host_ptr,owner_identity,callback_identity,},- }+ binding,+ })}pub(crate) fn worker<'s>(scope: &mut v8::PinScope<'s, '_>,callback: PreparedWebIdlCallbackFunction,context: v8::Local<'s, v8::Context>,- ) -> Self {- Self {+ ) -> Option<Self> {+ let binding = CommonRuntimeBinding::from_scope(scope)?;+ if !matches!(+ binding.execution_context(scope)?,+ RuntimeExecutionContext::Worker+ ) {+ return None;+ }+ Some(Self {callback,environment: CallbackExecutionEnvironment::Worker {context: v8::Global::new(scope, context),},- }+ binding,+ })}- /// Resolve the environment once while restoring the traced callback.+ /// Resolve execution policy through the Context's installed binding./// APIs with additional registration-time identities use `window` or/// `worker` after their owner-specific authorization instead.pub(crate) fn from_traced<'s>(scope: &mut v8::PinScope<'s, '_>,carrier: v8::Local<'s, v8::Object>,) -> Option<Self> {+ let binding = CommonRuntimeBinding::from_scope(scope)?;let callback = V8TracedWebIdlCallbackFunction::from_object(carrier).prepare(scope);- if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {- let host = unsafe { &*host_ptr };- let context = callback.relevant_context(scope);- let callback_identity =- host.window_execution_context_identity_for_v8_context(scope, context)?;- return Some(Self::window(callback, host_ptr, None, callback_identity));- }- get_worker_state(scope)?;- let context = scope.get_current_context();- Some(Self::worker(scope, callback, context))+ let environment = match binding.execution_context(scope)? {+ RuntimeExecutionContext::Window(host_ptr) => {+ let host = unsafe { &*host_ptr };+ let context = callback.relevant_context(scope);+ let callback_identity =+ host.window_execution_context_identity_for_v8_context(scope, context)?;+ CallbackExecutionEnvironment::Window {+ owner_identity: None,+ callback_identity,+ }+ }+ RuntimeExecutionContext::Worker => CallbackExecutionEnvironment::Worker {+ context: v8::Global::new(scope, scope.get_current_context()),+ },+ };+ Some(Self {+ callback,+ environment,+ binding,+ })}/// Execute the caller's invocation and return conversion while the Web@@ -109,7 +131,7 @@ impl PreparedWebIdlCallbackExecution {&'a [v8::Local<'s, v8::Value>],) -> Result<R, E>,) -> WebIdlCallbackExecutionOutcome<R, E> {- if !self.environment.can_invoke(scope) {+ if !self.environment.can_invoke(scope, &self.binding) {return WebIdlCallbackExecutionOutcome::Unavailable;}match invoke_webidl_callback_function(@@ -152,20 +174,26 @@ impl PreparedWebIdlCallbackExecution {},);if let WebIdlCallbackExecutionOutcome::Failed(report) = result {- self.environment.report_exception(scope, event_type, report);+ self.environment+ .report_exception(scope, &self.binding, event_type, report);}}}impl CallbackExecutionEnvironment {- fn can_invoke(&self, scope: &mut v8::PinScope<'_, '_>) -> bool {+ fn can_invoke(&self, scope: &mut v8::PinScope<'_, '_>, binding: &CommonRuntimeBinding) -> bool {+ if binding.execution_context(scope).is_none() {+ return false;+ }match self {Self::Window {- host_ptr,owner_identity,callback_identity,} => {- let host = unsafe { &**host_ptr };+ let Some(host_ptr) = binding.window_host_ptr() else {+ return false;+ };+ let host = unsafe { &*host_ptr };let current = owner_identity.is_none_or(|identity| {host.window_execution_context_identity_is_current(identity)}) && host@@ -180,8 +208,7 @@ impl CallbackExecutionEnvironment {// `close()` stops future task delivery, but synchronous// APIs and already queued V8 microtasks may still run.// API/task owners enforce their own closing policy.- && get_worker_state(scope).is_some()- && !worker_termination_requested(scope)+ && binding.worker_can_invoke()&& !scope.is_execution_terminating()}}@@ -190,25 +217,32 @@ impl CallbackExecutionEnvironment {fn report_exception(&self,scope: &mut v8::PinScope<'_, '_>,+ binding: &CommonRuntimeBinding,event_type: &str,report: Box<V8ExceptionReport>,) {match self {Self::Window {- host_ptr,- callback_identity,- ..+ callback_identity, ..} => {- report_event_callback_exception(- scope,- *host_ptr,- event_type,- Some(*callback_identity),- None,- &report,- );+ if let Some(host_ptr) = binding.window_host_ptr() {+ report_event_callback_exception(+ scope,+ host_ptr,+ event_type,+ Some(*callback_identity),+ None,+ &report,+ );+ }}Self::Worker { context } => {+ if !matches!(+ binding.execution_context(scope),+ Some(RuntimeExecutionContext::Worker)+ ) {+ return;+ }let context = v8::Local::new(scope, context);let scope = &mut v8::ContextScope::new(scope, context);dispatch_current_worker_callback_exception(scope, *report);diff --git a/moli-renderer-v8/src/worker/global_scope/state.rs b/moli-renderer-v8/src/worker/global_scope/state.rsindex f995caaa5..d438acede 100644--- a/moli-renderer-v8/src/worker/global_scope/state.rs+++ b/moli-renderer-v8/src/worker/global_scope/state.rs@@ -4,6 +4,16 @@ use super::*;pub(crate) const WORKER_STATE_SLOT: &str = "__workerState";+impl WorkerGlobalState {+ pub(crate) fn callback_invocation_allowed(&self) -> bool {+ !self.termination_requested.load(Ordering::Acquire)+ }++ pub(crate) fn callback_task_delivery_allowed(&self) -> bool {+ !self.closed && self.callback_invocation_allowed()+ }+}+pub(crate) struct WorkerGlobalState {/// Components shared with Window runtimes, owned by this Worker run.pub(crate) common: Rc<crate::common_runtime::CommonRuntimeState>,