Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(callbacks): share observer registration state

ldm04f7a01fd0042
diff --git a/moli-renderer-v8/src/common_runtime.rs b/moli-renderer-v8/src/common_runtime.rs
index 872ef04af..fadd6a2f4 100644
--- a/moli-renderer-v8/src/common_runtime.rs
+++ b/moli-renderer-v8/src/common_runtime.rs
@@ -4,6 +4,14 @@
//! Worker run state remain the authoritative execution identities; retaining a
//! Context must not independently root its host or its callback graph.
+mod callback_registry;
+
+pub(crate) use callback_registry::{
+ CallbackRegistrationId, CallbackRegistrationKind, CallbackResidence,
+};
+
+use callback_registry::CallbackRegistry;
+
use std::{
cell::{Cell, RefCell},
rc::{Rc, Weak},
@@ -25,6 +33,7 @@ use crate::{
pub(crate) struct CommonRuntimeState {
pub(crate) finalizers: RefCell<V8FinalizerRegistry>,
pub(crate) text_codecs: TextCodecStore,
+ pub(crate) callbacks: CallbackRegistry,
}
impl CommonRuntimeState {
@@ -39,6 +48,7 @@ impl CommonRuntimeState {
}
pub(crate) fn clear_for_context_teardown(&self) {
+ self.callbacks.clear_for_context_teardown();
// 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.
diff --git a/moli-renderer-v8/src/common_runtime/callback_registry.rs b/moli-renderer-v8/src/common_runtime/callback_registry.rs
new file mode 100644
index 000000000..bd0acc744
--- /dev/null
+++ b/moli-renderer-v8/src/common_runtime/callback_registry.rs
@@ -0,0 +1,408 @@
+//! Owner-local registrations for callbacks whose values and pending records
+//! live on JavaScript objects. Window and Worker share identity lookup,
+//! activation, ordering and cleanup; only execution authorization differs.
+
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+
+use indexmap::IndexMap;
+use moli_webidl_callback::{PreparedWebIdlCallbackFunction, WebIdlCallbackFunction};
+
+use super::{CommonRuntimeBinding, RuntimeExecutionContext};
+use crate::{
+ native_bridge::{
+ RuntimeObservableContextToken, WindowExecutionContextIdentity, WindowExecutionContextOwner,
+ },
+ webidl_callback_execution::PreparedWebIdlCallbackExecution,
+};
+
+/// IDs are local to one common runtime and never reused. Lookup also checks
+/// the exact JS owner, so an ID from another runtime cannot alias a binding.
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub(crate) struct CallbackRegistrationId(u32);
+
+impl CallbackRegistrationId {
+ pub(crate) const fn as_u32(self) -> u32 {
+ self.0
+ }
+
+ pub(crate) fn from_number(value: f64) -> Option<Self> {
+ if !value.is_finite() || value.fract() != 0.0 || !(1.0..=(u32::MAX as f64)).contains(&value)
+ {
+ return None;
+ }
+ Some(Self(value as u32))
+ }
+}
+
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum CallbackRegistrationKind {
+ ResizeObserver,
+ PerformanceObserver,
+}
+
+/// V8-traced callback and conversion-time context anchors, temporarily read
+/// from the API object's private slots. The registry retains none of them.
+pub(crate) struct CallbackResidence<'s> {
+ id: CallbackRegistrationId,
+ callback: v8::Local<'s, v8::Object>,
+ relevant_global: v8::Local<'s, v8::Object>,
+ incumbent_global: v8::Local<'s, v8::Object>,
+}
+
+impl<'s> CallbackResidence<'s> {
+ pub(crate) fn from_parts(
+ id: CallbackRegistrationId,
+ callback: v8::Local<'s, v8::Object>,
+ relevant_global: v8::Local<'s, v8::Object>,
+ incumbent_global: v8::Local<'s, v8::Object>,
+ ) -> Self {
+ Self {
+ id,
+ callback,
+ relevant_global,
+ incumbent_global,
+ }
+ }
+
+ pub(crate) fn into_parts(
+ self,
+ ) -> (
+ CallbackRegistrationId,
+ v8::Local<'s, v8::Object>,
+ v8::Local<'s, v8::Object>,
+ v8::Local<'s, v8::Object>,
+ ) {
+ (
+ self.id,
+ self.callback,
+ self.relevant_global,
+ self.incumbent_global,
+ )
+ }
+}
+
+#[derive(Clone, Copy)]
+enum RegistrationIdentity {
+ Window {
+ observer: Option<WindowExecutionContextIdentity>,
+ callback: Option<WindowExecutionContextIdentity>,
+ },
+ Worker,
+}
+
+#[derive(Clone)]
+struct CallbackBinding {
+ kind: CallbackRegistrationKind,
+ observer: Rc<v8::Weak<v8::Object>>,
+ // This binding contains only weak owner references, never a V8 Context
+ // root. It does not keep a callback-observer cycle alive.
+ execution: Rc<CommonRuntimeBinding>,
+ identity: RegistrationIdentity,
+}
+
+impl CallbackBinding {
+ fn is_current(&self, scope: &mut v8::PinScope<'_, '_>) -> bool {
+ match self.identity {
+ RegistrationIdentity::Window { observer, callback } => {
+ let Some(host_ptr) = self.execution.window_host_ptr() else {
+ return false;
+ };
+ // The binding verifies the original host's backing lifetime.
+ // No host borrow or registry borrow survives into author JS.
+ let host = unsafe { &*host_ptr };
+ observer.is_some_and(|identity| {
+ host.window_execution_context_identity_is_current(identity)
+ }) && callback.is_some_and(|identity| {
+ host.window_execution_context_identity_is_current(identity)
+ })
+ }
+ RegistrationIdentity::Worker => {
+ let context = scope.get_current_context();
+ context
+ .get_slot::<CommonRuntimeBinding>()
+ .is_some_and(|binding| Rc::ptr_eq(&binding, &self.execution))
+ && self.execution.worker_can_deliver_task()
+ && !scope.is_execution_terminating()
+ }
+ }
+ }
+
+ fn is_owned_by(&self, owner: WindowExecutionContextOwner) -> bool {
+ self.window_identities()
+ .into_iter()
+ .flatten()
+ .any(|identity| identity.owner() == owner)
+ }
+
+ fn belongs_to_context_token(&self, token: RuntimeObservableContextToken) -> bool {
+ self.window_identities()
+ .into_iter()
+ .flatten()
+ .any(|identity| identity.realm_token() == token)
+ }
+
+ fn window_identities(&self) -> [Option<WindowExecutionContextIdentity>; 2] {
+ match self.identity {
+ RegistrationIdentity::Window { observer, callback } => [observer, callback],
+ RegistrationIdentity::Worker => [None, None],
+ }
+ }
+}
+
+#[derive(Default)]
+struct CallbackRegistryState {
+ next_id: u32,
+ bindings: HashMap<CallbackRegistrationId, CallbackBinding>,
+ // Activation order is distinct from construction order. Disconnect
+ // removes the root; observing again appends it to the registered set.
+ active: IndexMap<CallbackRegistrationId, Rc<v8::Global<v8::Object>>>,
+}
+
+/// A weak identity table plus the explicitly active PerformanceObserver roots.
+/// Callback values remain V8-traced. Native finalizers use a weak reference to
+/// this table, avoiding raw host pointers and independent callback GC roots.
+#[derive(Default)]
+pub(crate) struct CallbackRegistry {
+ state: Rc<RefCell<CallbackRegistryState>>,
+}
+
+impl CallbackRegistry {
+ pub(crate) fn register<'s>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ observer: v8::Local<'s, v8::Object>,
+ callback: WebIdlCallbackFunction,
+ kind: CallbackRegistrationKind,
+ ) -> Option<CallbackResidence<'s>> {
+ let context = scope.get_current_context();
+ let execution = context.get_slot::<CommonRuntimeBinding>()?;
+ let (runtime, owner) = execution.resolve_owner(context)?;
+ if !Rc::ptr_eq(&runtime.callbacks.state, &self.state) {
+ return None;
+ }
+ let observer_context = observer.get_creation_context(scope)?;
+ let relevant_context = callback.relevant_context(scope);
+ let identity = match owner {
+ RuntimeExecutionContext::Window(host_ptr) => {
+ let host = unsafe { &*host_ptr };
+ RegistrationIdentity::Window {
+ observer: host
+ .window_execution_context_identity_for_v8_context(scope, observer_context),
+ callback: host
+ .window_execution_context_identity_for_v8_context(scope, relevant_context),
+ }
+ }
+ RuntimeExecutionContext::Worker => {
+ if observer_context != context || relevant_context != context {
+ return None;
+ }
+ RegistrationIdentity::Worker
+ }
+ };
+ let callback_value = v8::Local::<v8::Object>::try_from(callback.value(scope)).ok()?;
+ let relevant_global = relevant_context.global(scope);
+ let incumbent_global = callback.incumbent_context(scope).global(scope);
+ // Create weak handles outside the registry borrow: V8 may run native
+ // finalizers during allocations, including another binding's cleanup.
+ let observer_weak = Rc::new(v8::Weak::new(scope, observer));
+ let id = {
+ let mut state = self.state.borrow_mut();
+ state.next_id = state
+ .next_id
+ .checked_add(1)
+ .expect("callback registration id space exhausted");
+ let id = CallbackRegistrationId(state.next_id);
+ let replaced = state.bindings.insert(
+ id,
+ CallbackBinding {
+ kind,
+ observer: observer_weak,
+ execution,
+ identity,
+ },
+ );
+ assert!(replaced.is_none(), "callback registration ID was reused");
+ id
+ };
+ let state = Rc::downgrade(&self.state);
+ crate::v8_finalizer::track_context_owned_v8_finalizer(scope, observer, move || {
+ if let Some(state) = state.upgrade() {
+ let retired = {
+ let mut state = state.borrow_mut();
+ (state.bindings.remove(&id), state.active.shift_remove(&id))
+ };
+ drop(retired);
+ }
+ });
+ Some(CallbackResidence::from_parts(
+ id,
+ callback_value,
+ relevant_global,
+ incumbent_global,
+ ))
+ }
+
+ fn lookup(
+ &self,
+ scope: &mut v8::PinScope<'_, '_>,
+ id: CallbackRegistrationId,
+ observer: v8::Local<'_, v8::Object>,
+ kind: CallbackRegistrationKind,
+ ) -> Option<CallbackBinding> {
+ let binding = self.state.borrow().bindings.get(&id)?.clone();
+ if binding.kind != kind || binding.observer.to_local(scope)? != observer {
+ return None;
+ }
+ Some(binding)
+ }
+
+ pub(crate) fn is_current(
+ &self,
+ scope: &mut v8::PinScope<'_, '_>,
+ id: CallbackRegistrationId,
+ observer: v8::Local<'_, v8::Object>,
+ kind: CallbackRegistrationKind,
+ ) -> bool {
+ self.lookup(scope, id, observer, kind)
+ .is_some_and(|binding| binding.is_current(scope))
+ }
+
+ pub(crate) fn prepare<'s>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ observer: v8::Local<'s, v8::Object>,
+ kind: CallbackRegistrationKind,
+ residence: CallbackResidence<'s>,
+ ) -> Option<PreparedWebIdlCallbackExecution> {
+ let binding = self.lookup(scope, residence.id, observer, kind)?;
+ if !binding.is_current(scope) {
+ return None;
+ }
+ let relevant = residence.relevant_global.get_creation_context(scope)?;
+ let incumbent = residence.incumbent_global.get_creation_context(scope)?;
+ let callback = PreparedWebIdlCallbackFunction::try_new(
+ scope,
+ residence.callback,
+ relevant,
+ incumbent,
+ )?;
+ match binding.identity {
+ RegistrationIdentity::Window {
+ observer,
+ callback: callback_identity,
+ } => PreparedWebIdlCallbackExecution::window(
+ scope,
+ callback,
+ binding.execution.window_host_ptr()?,
+ Some(observer?),
+ callback_identity?,
+ ),
+ RegistrationIdentity::Worker => {
+ let context = observer.get_creation_context(scope)?;
+ PreparedWebIdlCallbackExecution::worker(scope, callback, context)
+ }
+ }
+ }
+
+ pub(crate) fn activate_performance_observer(
+ &self,
+ scope: &mut v8::PinScope<'_, '_>,
+ id: CallbackRegistrationId,
+ observer: v8::Local<'_, v8::Object>,
+ ) -> bool {
+ if !self.is_current(
+ scope,
+ id,
+ observer,
+ CallbackRegistrationKind::PerformanceObserver,
+ ) {
+ return false;
+ }
+ let root = Rc::new(v8::Global::new(scope, observer));
+ {
+ let mut state = self.state.borrow_mut();
+ // A native cleanup during V8 allocation may have retired the
+ // registration. Never leave an active root without its binding.
+ if !state.bindings.contains_key(&id) {
+ return false;
+ }
+ state.active.entry(id).or_insert_with(|| Rc::clone(&root));
+ }
+ true
+ }
+
+ pub(crate) fn deactivate_performance_observer(
+ &self,
+ scope: &mut v8::PinScope<'_, '_>,
+ id: CallbackRegistrationId,
+ observer: v8::Local<'_, v8::Object>,
+ ) {
+ if self
+ .lookup(
+ scope,
+ id,
+ observer,
+ CallbackRegistrationKind::PerformanceObserver,
+ )
+ .is_some()
+ {
+ let retired = self.state.borrow_mut().active.shift_remove(&id);
+ drop(retired);
+ }
+ }
+
+ pub(crate) fn active_performance_observers<'s>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ ) -> Vec<v8::Local<'s, v8::Object>> {
+ let roots: Vec<_> = self.state.borrow().active.values().map(Rc::clone).collect();
+ let context = scope.get_current_context();
+ roots
+ .iter()
+ .map(|root| v8::Local::new(scope, root.as_ref()))
+ .filter(|observer| observer.get_creation_context(scope) == Some(context))
+ .collect()
+ }
+
+ pub(crate) fn retire_execution_context_owner(
+ &self,
+ owner: WindowExecutionContextOwner,
+ ) -> usize {
+ self.retire_bindings(|binding| binding.is_owned_by(owner))
+ }
+
+ pub(crate) fn retire_context_token(&self, token: RuntimeObservableContextToken) -> usize {
+ self.retire_bindings(|binding| binding.belongs_to_context_token(token))
+ }
+
+ fn retire_bindings(&self, mut retire: impl FnMut(&CallbackBinding) -> bool) -> usize {
+ let retired = {
+ let mut state = self.state.borrow_mut();
+ let ids: Vec<_> = state
+ .bindings
+ .iter()
+ .filter_map(|(id, binding)| retire(binding).then_some(*id))
+ .collect();
+ ids.into_iter()
+ .map(|id| (state.bindings.remove(&id), state.active.shift_remove(&id)))
+ .collect::<Vec<_>>()
+ };
+ retired.len()
+ }
+
+ pub(super) fn clear_for_context_teardown(&self) {
+ let retired = {
+ let mut state = self.state.borrow_mut();
+ (
+ std::mem::take(&mut state.bindings),
+ std::mem::take(&mut state.active),
+ )
+ };
+ drop(retired);
+ }
+
+ #[cfg(test)]
+ pub(crate) fn len(&self) -> usize {
+ self.state.borrow().bindings.len()
+ }
+}
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.rs
index c937a7194..86252cb27 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
@@ -1,29 +1,22 @@
-//! Registration and callback residence adapters for PerformanceObserver.
-//!
-//! Window retains exact Realm bindings and active roots in ObserverStore;
-//! Worker retains active observers on its global. Neither backend changes the
-//! timeline's batching algorithm or owns a second callback invocation path.
+//! PerformanceObserver's private callback residence and common registration.
+//! The timeline owns batching; the common runtime owns identity lookup,
+//! activation and cleanup for both Window and Worker.
-use moli_webidl_callback::{PreparedWebIdlCallbackFunction, WebIdlCallbackFunction};
+use std::rc::Rc;
+
+use moli_webidl_callback::WebIdlCallbackFunction;
use super::*;
-use crate::common_runtime::{CommonRuntimeBinding, RuntimeExecutionContext};
-use crate::observer_runtime::{ObserverCallbackId, ObserverCallbackResidence};
-use crate::util::{get_private_value, set_private_value};
+use crate::common_runtime::{
+ CallbackRegistrationId, CallbackRegistrationKind, CallbackResidence, CommonRuntimeState,
+};
+use crate::util::get_private_value;
use crate::webidl_callback_execution::PreparedWebIdlCallbackExecution;
-enum RegistrationEnvironment {
- Window {
- host_ptr: *mut JsContextHost,
- callback_id: ObserverCallbackId,
- },
- Worker,
-}
-
pub(super) struct PerformanceObserverRegistration<'s> {
observer: v8::Local<'s, v8::Object>,
- environment: RegistrationEnvironment,
- binding: std::rc::Rc<CommonRuntimeBinding>,
+ id: CallbackRegistrationId,
+ common: Rc<CommonRuntimeState>,
}
pub(super) fn register_performance_observer_callback<'s>(
@@ -36,19 +29,17 @@ pub(super) fn register_performance_observer_callback<'s>(
v8::Local<'s, v8::Object>,
v8::Local<'s, v8::Object>,
)> {
- let (_, owner) = CommonRuntimeBinding::from_scope(scope)?;
- if let RuntimeExecutionContext::Window(host_ptr) = owner {
- 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));
- }
- 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);
- // Zero is outside ObserverCallbackId's valid range. Worker registration is
- // tied to the observer's creation context rather than a Window binding.
- Some((0, value, relevant, incumbent))
+ let common = CommonRuntimeState::from_scope(scope)?;
+ let (id, callback, relevant, incumbent) = common
+ .callbacks
+ .register(
+ scope,
+ observer,
+ callback,
+ CallbackRegistrationKind::PerformanceObserver,
+ )?
+ .into_parts();
+ Some((id.as_u32(), callback, relevant, incumbent))
}
impl<'s> PerformanceObserverRegistration<'s> {
@@ -58,109 +49,38 @@ impl<'s> PerformanceObserverRegistration<'s> {
) -> Option<Self> {
let id = get_private_value(scope, observer, PERFORMANCE_OBSERVER_CALLBACK_ID_SLOT)?
.number_value(scope)?;
- let (binding, owner) = CommonRuntimeBinding::from_scope(scope)?;
- let environment = match owner {
- 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
- }
- };
Some(Self {
observer,
- environment,
- binding,
+ id: CallbackRegistrationId::from_number(id)?,
+ common: CommonRuntimeState::from_scope(scope)?,
})
}
pub(super) fn is_current(&self, scope: &mut v8::PinScope<'s, '_>) -> bool {
- match self.environment {
- RegistrationEnvironment::Window {
- host_ptr,
- callback_id,
- } => crate::observer_runtime::callback_is_current(host_ptr, callback_id),
- RegistrationEnvironment::Worker => {
- self.binding.worker_can_deliver_task() && !scope.is_execution_terminating()
- }
- }
+ self.common.callbacks.is_current(
+ scope,
+ self.id,
+ self.observer,
+ CallbackRegistrationKind::PerformanceObserver,
+ )
}
pub(super) fn activate(&self, scope: &mut v8::PinScope<'s, '_>) -> bool {
- match self.environment {
- RegistrationEnvironment::Window {
- host_ptr,
- callback_id,
- } => {
- // ObserverStore owns the active root so disconnect and exact
- // Realm retirement release it along with the binding.
- crate::observer_runtime::activate_performance_observer_callback(
- scope,
- host_ptr,
- callback_id,
- self.observer,
- )
- }
- RegistrationEnvironment::Worker => {
- if !self.is_current(scope) {
- return false;
- }
- push_object_to_global_registry(
- scope,
- PERFORMANCE_OBSERVER_REGISTRY_SLOT,
- self.observer,
- );
- true
- }
- }
+ self.common
+ .callbacks
+ .activate_performance_observer(scope, self.id, self.observer)
}
pub(super) fn deactivate(&self, scope: &mut v8::PinScope<'s, '_>) {
- match self.environment {
- RegistrationEnvironment::Window {
- host_ptr,
- callback_id,
- } => {
- crate::observer_runtime::deactivate_performance_observer_callback(
- host_ptr,
- callback_id,
- );
- }
- RegistrationEnvironment::Worker => {
- let Some(registry) = global_queue_array(scope, PERFORMANCE_OBSERVER_REGISTRY_SLOT)
- else {
- return;
- };
- let retained: Vec<_> = (0..registry.length())
- .filter_map(|index| registry.get_index(scope, index))
- .filter(|value| !value.strict_equals(self.observer.into()))
- .collect();
- let registry = v8::Array::new_with_elements(scope, &retained);
- let global = scope.get_current_context().global(scope);
- set_private_value(
- scope,
- global,
- PERFORMANCE_OBSERVER_REGISTRY_SLOT,
- registry.into(),
- );
- }
- }
+ self.common
+ .callbacks
+ .deactivate_performance_observer(scope, self.id, self.observer);
}
pub(super) fn prepare_delivery(
&self,
scope: &mut v8::PinScope<'s, '_>,
) -> Option<PreparedWebIdlCallbackExecution> {
- if !self.is_current(scope) {
- return None;
- }
- // Read callback and both conversion-time context anchors once for
- // either environment. These private values remain traced by V8.
let object = |scope: &mut v8::PinScope<'s, '_>, slot| {
get_private_value(scope, self.observer, slot)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
@@ -168,28 +88,13 @@ impl<'s> PerformanceObserverRegistration<'s> {
let callback = object(scope, PERFORMANCE_OBSERVER_CALLBACK_VALUE_SLOT)?;
let relevant = object(scope, PERFORMANCE_OBSERVER_CALLBACK_RELEVANT_GLOBAL_SLOT)?;
let incumbent = object(scope, PERFORMANCE_OBSERVER_CALLBACK_INCUMBENT_GLOBAL_SLOT)?;
- match self.environment {
- RegistrationEnvironment::Window {
- host_ptr,
- callback_id,
- } => {
- let residence = ObserverCallbackResidence::from_parts(
- callback_id,
- callback,
- relevant,
- incumbent,
- );
- crate::observer_runtime::prepare_callback(scope, host_ptr, residence)
- }
- RegistrationEnvironment::Worker => {
- let context = self.observer.get_creation_context(scope)?;
- let relevant = relevant.get_creation_context(scope)?;
- let incumbent = incumbent.get_creation_context(scope)?;
- let callback =
- PreparedWebIdlCallbackFunction::try_new(scope, callback, relevant, incumbent)?;
- PreparedWebIdlCallbackExecution::worker(scope, callback, context)
- }
- }
+ let residence = CallbackResidence::from_parts(self.id, callback, relevant, incumbent);
+ self.common.callbacks.prepare(
+ scope,
+ self.observer,
+ CallbackRegistrationKind::PerformanceObserver,
+ residence,
+ )
}
}
@@ -204,17 +109,7 @@ 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>> {
- let Some((_, owner)) = CommonRuntimeBinding::from_scope(scope) else {
- return Vec::new();
- };
- if let RuntimeExecutionContext::Window(host_ptr) = owner {
- 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();
- };
- (0..registry.length())
- .filter_map(|index| registry.get_index(scope, index))
- .filter_map(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .collect()
+ CommonRuntimeState::from_scope(scope)
+ .map(|common| common.callbacks.active_performance_observers(scope))
+ .unwrap_or_default()
}
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
index 2e47581cc..a916ff403 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
@@ -116,9 +116,6 @@ struct PerformanceObserverConstructorDeclaration {
#[derive(Default, WebApiObject)]
#[webapi(fragment)]
struct PerformanceObserverRuntimeStateDeclaration {
- #[webapi(slot = PERFORMANCE_OBSERVER_REGISTRY_SLOT, init = "array")]
- registry: (),
-
#[webapi(slot = PERFORMANCE_OBSERVER_QUEUE_SLOT, init = "array")]
queue: (),
}
diff --git a/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs b/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs
index 197758ab3..c277b2d33 100644
--- a/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/resize_observer_runtime.rs
@@ -1,6 +1,8 @@
mod entry;
use super::*;
-use crate::observer_runtime::ObserverCallbackId;
+use crate::common_runtime::{
+ CallbackRegistrationId, CallbackRegistrationKind, CallbackResidence, CommonRuntimeState,
+};
use crate::util::{get_private_value, serialize_v8_iter_array, set_private_value};
use crate::web_api_interfaces;
use crate::webidl;
@@ -110,10 +112,17 @@ pub(super) fn resize_observer_constructor_callback<'s>(
let Some(parsed) = webidl::parse_args::<ResizeObserverConstructorArgs>(scope, &args) else {
return;
};
- let host_ptr = context_host_ptr_from_global_bridge(scope)
- .expect("ResizeObserver constructor must execute in a Window realm");
- let registered_callback =
- crate::observer_runtime::register_callback(scope, host_ptr, args.this(), parsed.callback);
+ let common = CommonRuntimeState::from_scope(scope)
+ .expect("ResizeObserver constructor must have a common runtime");
+ let registered_callback = common
+ .callbacks
+ .register(
+ scope,
+ args.this(),
+ parsed.callback,
+ CallbackRegistrationKind::ResizeObserver,
+ )
+ .expect("ResizeObserver callback registration should succeed");
let (callback_id, callback, relevant_global, incumbent_global) =
registered_callback.into_parts();
ResizeObserverObjectDeclaration::new(
@@ -264,12 +273,15 @@ fn resize_observer_flush_callback<'s>(
let Some(callback_residence) = resize_observer_callback_residence(scope, observer) else {
return;
};
- let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
+ let Some(common) = CommonRuntimeState::from_scope(scope) else {
return;
};
- let Some(callback) =
- crate::observer_runtime::prepare_callback(scope, host_ptr, callback_residence)
- else {
+ let Some(callback) = common.callbacks.prepare(
+ scope,
+ observer,
+ CallbackRegistrationKind::ResizeObserver,
+ callback_residence,
+ ) else {
let pending_targets = v8::Array::new(scope, 0);
set_resize_observer_pending_targets(scope, observer, pending_targets);
return;
@@ -630,15 +642,15 @@ fn set_resize_observer_pending_targets(
fn resize_observer_callback_id<'s>(
scope: &mut v8::PinScope<'s, '_>,
observer: v8::Local<'s, v8::Object>,
-) -> Option<ObserverCallbackId> {
+) -> Option<CallbackRegistrationId> {
let value = resize_observer_slot_value(scope, observer, RESIZE_OBSERVER_CALLBACK_ID_SLOT)?;
- ObserverCallbackId::from_number(value.number_value(scope)?)
+ CallbackRegistrationId::from_number(value.number_value(scope)?)
}
fn resize_observer_callback_residence<'s>(
scope: &mut v8::PinScope<'s, '_>,
observer: v8::Local<'s, v8::Object>,
-) -> Option<crate::observer_runtime::ObserverCallbackResidence<'s>> {
+) -> Option<CallbackResidence<'s>> {
let callback_id = resize_observer_callback_id(scope, observer)?;
let callback = resize_observer_slot_value(scope, observer, RESIZE_OBSERVER_CALLBACK_VALUE_SLOT)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
@@ -654,14 +666,12 @@ fn resize_observer_callback_residence<'s>(
RESIZE_OBSERVER_CALLBACK_INCUMBENT_GLOBAL_SLOT,
)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- Some(
- crate::observer_runtime::ObserverCallbackResidence::from_parts(
- callback_id,
- callback,
- relevant_global,
- incumbent_global,
- ),
- )
+ Some(CallbackResidence::from_parts(
+ callback_id,
+ callback,
+ relevant_global,
+ incumbent_global,
+ ))
}
fn resize_observer_scheduled<'s>(
@@ -696,18 +706,22 @@ fn queue_resize_observer_delivery<'s>(
let Some(callback_id) = resize_observer_callback_id(scope, observer) else {
return;
};
- let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
+ let Some(common) = CommonRuntimeState::from_scope(scope) else {
return;
};
- if !crate::observer_runtime::callback_is_current(host_ptr, callback_id) {
+ if !common.callbacks.is_current(
+ scope,
+ callback_id,
+ observer,
+ CallbackRegistrationKind::ResizeObserver,
+ ) {
let pending_targets = v8::Array::new(scope, 0);
set_resize_observer_pending_targets(scope, observer, pending_targets);
return;
}
set_resize_observer_scheduled(scope, observer, true);
push_object_to_global_queue(scope, RESIZE_OBSERVER_QUEUE_SLOT, observer);
- let host = unsafe { &mut *host_ptr };
- schedule_host_callback(scope, host, resize_observer_flush_callback);
+ schedule_scope_callback(scope, resize_observer_flush_callback, None);
}
pub(crate) fn queue_resize_observer_checks(scope: &mut v8::PinScope<'_, '_>) {
diff --git a/moli-renderer-v8/src/context_bootstrap/shared/slots.rs b/moli-renderer-v8/src/context_bootstrap/shared/slots.rs
index 2032bd8f1..3b5fc3b99 100644
--- a/moli-renderer-v8/src/context_bootstrap/shared/slots.rs
+++ b/moli-renderer-v8/src/context_bootstrap/shared/slots.rs
@@ -129,8 +129,6 @@ pub(in crate::context_bootstrap) const PERFORMANCE_OBSERVER_ACTIVE_SLOT: &str =
"__moliPerformanceObserverActive";
pub(in crate::context_bootstrap) const PERFORMANCE_OBSERVER_SCHEDULED_SLOT: &str =
"__moliPerformanceObserverScheduled";
-pub(in crate::context_bootstrap) const PERFORMANCE_OBSERVER_REGISTRY_SLOT: &str =
- "__moliPerformanceObserverRegistry";
pub(in crate::context_bootstrap) const PERFORMANCE_OBSERVER_QUEUE_SLOT: &str =
"__moliPerformanceObserverQueue";
pub(in crate::context_bootstrap) const PERFORMANCE_OBSERVER_SUPPORTED_ENTRY_TYPES_SLOT: &str =
diff --git a/moli-renderer-v8/src/observer_runtime/callback.rs b/moli-renderer-v8/src/observer_runtime/callback.rs
index 80cb3751b..0c4ebda5c 100644
--- a/moli-renderer-v8/src/observer_runtime/callback.rs
+++ b/moli-renderer-v8/src/observer_runtime/callback.rs
@@ -5,13 +5,7 @@
//! both realm identities beside the Web IDL callback-function value. A
//! delivery is valid only while both identities are current.
-use std::{
- cell::RefCell,
- collections::HashMap,
- rc::{Rc, Weak},
-};
-
-use moli_webidl_callback::{PreparedWebIdlCallbackFunction, WebIdlCallbackFunction};
+use moli_webidl_callback::WebIdlCallbackFunction;
use crate::{
native_bridge::{
@@ -67,253 +61,3 @@ impl ObserverCallback {
|| self.callback.belongs_to_context_token(context_token)
}
}
-
-/// Stable, renderer-local identity for one observer callback residence.
-///
-/// ResizeObserver and PerformanceObserver keep their API-specific pending
-/// queues and V8-traced callback/context values on their JS objects. This ID
-/// binds those private values to the exact observer and callback Window
-/// identities without making Rust a permanent GC root.
-#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
-pub(crate) struct ObserverCallbackId(u32);
-
-impl ObserverCallbackId {
- pub(crate) const fn as_u32(self) -> u32 {
- self.0
- }
-
- pub(crate) fn from_number(value: f64) -> Option<Self> {
- if !value.is_finite() || value.fract() != 0.0 || !(1.0..=(u32::MAX as f64)).contains(&value)
- {
- return None;
- }
- Some(Self(value as u32))
- }
-}
-
-pub(super) struct ObserverCallbackBinding {
- observer_identity: Option<WindowExecutionContextIdentity>,
- callback_identity: Option<WindowExecutionContextIdentity>,
- // PerformanceObserver's registered-observer set keeps an actively
- // observing wrapper alive. ResizeObserver does not use this root. Exact
- // Realm retirement or disconnect removes it before the V8 cycle can be
- // collected.
- active_performance_observer: Option<Rc<v8::Global<v8::Object>>>,
-}
-
-impl ObserverCallbackBinding {
- pub(super) fn new(
- scope: &mut v8::PinScope<'_, '_>,
- host: &JsContextHost,
- observer: v8::Local<'_, v8::Object>,
- callback: &WebIdlCallbackFunction,
- ) -> Self {
- let observer_identity = observer.get_creation_context(scope).and_then(|context| {
- host.window_execution_context_identity_for_v8_context(scope, context)
- });
- let callback_context = callback.relevant_context(scope);
- let callback_identity =
- host.window_execution_context_identity_for_v8_context(scope, callback_context);
- Self {
- observer_identity,
- callback_identity,
- active_performance_observer: None,
- }
- }
-
- fn is_current(&self, host: &JsContextHost) -> bool {
- self.observer_identity
- .is_some_and(|identity| host.window_execution_context_identity_is_current(identity))
- && self
- .callback_identity
- .is_some_and(|identity| host.window_execution_context_identity_is_current(identity))
- }
-
- fn is_owned_by(&self, owner: WindowExecutionContextOwner) -> bool {
- self.observer_identity
- .is_some_and(|identity| identity.owner() == owner)
- || self
- .callback_identity
- .is_some_and(|identity| identity.owner() == owner)
- }
-
- fn belongs_to_context_token(&self, context_token: RuntimeObservableContextToken) -> bool {
- self.observer_identity
- .is_some_and(|identity| identity.realm_token() == context_token)
- || self
- .callback_identity
- .is_some_and(|identity| identity.realm_token() == context_token)
- }
-}
-
-#[derive(Default)]
-struct ObserverCallbackRegistryState {
- next_id: u32,
- bindings: HashMap<ObserverCallbackId, ObserverCallbackBinding>,
-}
-
-/// Shared owner-local identity registry for observer APIs whose batching and
-/// callback values live on their JavaScript objects.
-///
-/// The `Rc<RefCell<_>>` is deliberate: a V8 weak finalizer must be able to
-/// release the small identity binding after the observer becomes unreachable,
-/// without retaining a raw `JsContextHost` pointer. The registry never roots
-/// the callback or observer, so callback↔observer cycles remain V8-collectable.
-#[derive(Clone, Default)]
-pub(super) struct ObserverCallbackRegistry {
- state: Rc<RefCell<ObserverCallbackRegistryState>>,
-}
-
-impl ObserverCallbackRegistry {
- #[cfg(test)]
- pub(super) fn len(&self) -> usize {
- self.state.borrow().bindings.len()
- }
-
- pub(super) fn register(&self, binding: ObserverCallbackBinding) -> ObserverCallbackId {
- let mut state = self.state.borrow_mut();
- state.next_id = state
- .next_id
- .checked_add(1)
- .expect("observer callback id space exhausted");
- let id = ObserverCallbackId(state.next_id);
- let replaced = state.bindings.insert(id, binding);
- assert!(
- replaced.is_none(),
- "observer callback binding identities must not be reused"
- );
- id
- }
-
- pub(super) fn prepare<'s>(
- &self,
- scope: &mut v8::PinScope<'s, '_>,
- host: &JsContextHost,
- id: ObserverCallbackId,
- callback: v8::Local<'s, v8::Object>,
- relevant_global: v8::Local<'s, v8::Object>,
- incumbent_global: v8::Local<'s, v8::Object>,
- ) -> Option<PreparedWebIdlCallbackExecution> {
- let (observer_identity, callback_identity) = {
- let state = self.state.borrow();
- let binding = state.bindings.get(&id)?;
- if !binding.is_current(host) {
- return None;
- }
- (binding.observer_identity, binding.callback_identity)
- };
- let relevant_context = relevant_global.get_creation_context(scope)?;
- let incumbent_context = incumbent_global.get_creation_context(scope)?;
- let callback = PreparedWebIdlCallbackFunction::try_new(
- scope,
- callback,
- relevant_context,
- incumbent_context,
- )?;
- PreparedWebIdlCallbackExecution::window(
- scope,
- callback,
- std::ptr::from_ref(host).cast_mut(),
- Some(observer_identity?),
- callback_identity?,
- )
- }
-
- pub(super) fn is_current(&self, host: &JsContextHost, id: ObserverCallbackId) -> bool {
- self.state
- .borrow()
- .bindings
- .get(&id)
- .is_some_and(|binding| binding.is_current(host))
- }
-
- pub(super) fn activate_performance_observer<'s>(
- &self,
- scope: &mut v8::PinScope<'s, '_>,
- host: &JsContextHost,
- id: ObserverCallbackId,
- observer: v8::Local<'s, v8::Object>,
- ) -> bool {
- // Build the V8 root before borrowing the registry. A GC/finalizer must
- // never reenter the same RefCell while an activation mutably borrows it.
- let observer = Rc::new(v8::Global::new(scope, observer));
- let mut state = self.state.borrow_mut();
- let Some(binding) = state.bindings.get_mut(&id) else {
- return false;
- };
- if !binding.is_current(host) {
- return false;
- }
- binding.active_performance_observer = Some(observer);
- true
- }
-
- pub(super) fn deactivate_performance_observer(&self, id: ObserverCallbackId) -> bool {
- let observer = self
- .state
- .borrow_mut()
- .bindings
- .get_mut(&id)
- .and_then(|binding| binding.active_performance_observer.take());
- observer.is_some()
- }
-
- pub(super) fn active_performance_observers<'s>(
- &self,
- scope: &mut v8::PinScope<'s, '_>,
- ) -> Vec<v8::Local<'s, v8::Object>> {
- let observers: Vec<_> = self
- .state
- .borrow()
- .bindings
- .values()
- .filter_map(|binding| binding.active_performance_observer.as_ref().map(Rc::clone))
- .collect();
- observers
- .iter()
- .map(|observer| v8::Local::new(scope, observer.as_ref()))
- .collect()
- }
-
- pub(super) fn retire_execution_context_owner(
- &self,
- owner: WindowExecutionContextOwner,
- ) -> usize {
- self.retire_bindings(|binding| binding.is_owned_by(owner))
- }
-
- pub(super) fn retire_context_token(
- &self,
- context_token: RuntimeObservableContextToken,
- ) -> usize {
- self.retire_bindings(|binding| binding.belongs_to_context_token(context_token))
- }
-
- fn retire_bindings(
- &self,
- mut should_retire: impl FnMut(&ObserverCallbackBinding) -> bool,
- ) -> usize {
- let retired = {
- let mut state = self.state.borrow_mut();
- let ids: Vec<_> = state
- .bindings
- .iter()
- .filter_map(|(id, binding)| should_retire(binding).then_some(*id))
- .collect();
- ids.into_iter()
- .filter_map(|id| state.bindings.remove(&id))
- .collect::<Vec<_>>()
- };
- retired.len()
- }
-
- pub(super) fn finalizer_cleanup(&self, id: ObserverCallbackId) -> impl FnOnce() + 'static {
- let state = Rc::downgrade(&self.state);
- move || {
- if let Some(state) = Weak::upgrade(&state) {
- let retired = state.borrow_mut().bindings.remove(&id);
- drop(retired);
- }
- }
- }
-}
diff --git a/moli-renderer-v8/src/observer_runtime/dom_access.rs b/moli-renderer-v8/src/observer_runtime/dom_access.rs
index 5d8276be9..5ec5b6e28 100644
--- a/moli-renderer-v8/src/observer_runtime/dom_access.rs
+++ b/moli-renderer-v8/src/observer_runtime/dom_access.rs
@@ -3,7 +3,6 @@ use std::ptr::NonNull;
use crate::{
dom::native::{DomHost, DomMutationEffects, NativeNodeId},
native_bridge::{JsContextHost, RuntimeObservableContextToken, WindowExecutionContextOwner},
- webidl_callback_execution::PreparedWebIdlCallbackExecution,
};
use moli_webidl_callback::WebIdlCallbackFunction;
@@ -11,7 +10,7 @@ use super::{
IntersectionMutationPlan, IntersectionObserverOptions, MutationObserverOptions,
ObserverMutationPlan, ObserverStore, build_intersection_entries_array,
build_mutation_records_array,
- callback::{ObserverCallback, ObserverCallbackBinding, ObserverCallbackId},
+ callback::ObserverCallback,
intersection::{self, IntersectionCheckBatch},
invoke_intersection_deliveries, invoke_mutation_deliveries, node_is_intersection_root,
node_is_intersection_target,
@@ -19,138 +18,6 @@ use super::{
target_is_intersection_observable,
};
-/// V8-traced values for one callback plus the exact identity binding that
-/// authorizes their use.
-///
-/// Keeping these fields together prevents observer APIs from swapping
-/// relevant/incumbent context anchors when preparing a delivery.
-pub(crate) struct ObserverCallbackResidence<'s> {
- id: ObserverCallbackId,
- callback: v8::Local<'s, v8::Object>,
- relevant_global: v8::Local<'s, v8::Object>,
- incumbent_global: v8::Local<'s, v8::Object>,
-}
-
-impl<'s> ObserverCallbackResidence<'s> {
- pub(crate) fn from_parts(
- id: ObserverCallbackId,
- callback: v8::Local<'s, v8::Object>,
- relevant_global: v8::Local<'s, v8::Object>,
- incumbent_global: v8::Local<'s, v8::Object>,
- ) -> Self {
- Self {
- id,
- callback,
- relevant_global,
- incumbent_global,
- }
- }
-
- pub(crate) fn into_parts(
- self,
- ) -> (
- ObserverCallbackId,
- v8::Local<'s, v8::Object>,
- v8::Local<'s, v8::Object>,
- v8::Local<'s, v8::Object>,
- ) {
- (
- self.id,
- self.callback,
- self.relevant_global,
- self.incumbent_global,
- )
- }
-}
-
-pub(crate) fn register_callback<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- host_ptr: *mut JsContextHost,
- observer: v8::Local<'s, v8::Object>,
- callback: WebIdlCallbackFunction,
-) -> ObserverCallbackResidence<'s> {
- let mut access = ObserverHostAccess::new(host_ptr);
- let binding =
- access.read(|host| ObserverCallbackBinding::new(scope, host, observer, &callback));
- let registry = access.store(|store| store.callback_registry.clone());
- let id = registry.register(binding);
- let callback_value = callback.value(scope);
- let relevant_global = callback.relevant_context(scope).global(scope);
- // Preserve the exact conversion-time incumbent context rather than
- // rediscovering it from the callback object.
- let incumbent_global = callback.incumbent_context(scope).global(scope);
- let callback = v8::Local::<v8::Object>::try_from(callback_value)
- .expect("a Web IDL callback function must be an object");
- crate::v8_finalizer::track_context_owned_v8_finalizer(
- scope,
- observer,
- registry.finalizer_cleanup(id),
- );
- ObserverCallbackResidence {
- id,
- callback,
- relevant_global,
- incumbent_global,
- }
-}
-
-pub(crate) fn prepare_callback<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- host_ptr: *mut JsContextHost,
- residence: ObserverCallbackResidence<'s>,
-) -> Option<PreparedWebIdlCallbackExecution> {
- let ObserverCallbackResidence {
- id,
- callback,
- relevant_global,
- incumbent_global,
- } = residence;
- let mut access = ObserverHostAccess::new(host_ptr);
- let registry = access.store(|store| store.callback_registry.clone());
- access
- .read(|host| registry.prepare(scope, host, id, callback, relevant_global, incumbent_global))
-}
-
-pub(crate) fn callback_is_current(host_ptr: *mut JsContextHost, id: ObserverCallbackId) -> bool {
- let mut access = ObserverHostAccess::new(host_ptr);
- let registry = access.store(|store| store.callback_registry.clone());
- access.read(|host| registry.is_current(host, id))
-}
-
-pub(crate) fn activate_performance_observer_callback<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- host_ptr: *mut JsContextHost,
- id: ObserverCallbackId,
- observer: v8::Local<'s, v8::Object>,
-) -> bool {
- let mut access = ObserverHostAccess::new(host_ptr);
- let registry = access.store(|store| store.callback_registry.clone());
- access.read(|host| registry.activate_performance_observer(scope, host, id, observer))
-}
-
-pub(crate) fn deactivate_performance_observer_callback(
- host_ptr: *mut JsContextHost,
- id: ObserverCallbackId,
-) -> bool {
- let registry = ObserverHostAccess::new(host_ptr).store(|store| store.callback_registry.clone());
- registry.deactivate_performance_observer(id)
-}
-
-pub(crate) fn active_performance_observer_callbacks<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- host_ptr: *mut JsContextHost,
-) -> Vec<v8::Local<'s, v8::Object>> {
- let registry = ObserverHostAccess::new(host_ptr).store(|store| store.callback_registry.clone());
- registry.active_performance_observers(scope)
-}
-
-#[cfg(test)]
-pub(crate) fn callback_binding_count_for_test(host: &mut JsContextHost) -> usize {
- host.observers_mut(&OBSERVER_STORE_ACCESS)
- .callback_registry
- .len()
-}
-
pub(crate) struct ObserverStoreAccessToken {
_private: (),
}
@@ -394,7 +261,7 @@ pub(crate) fn retire_execution_context_owner(
};
host.dom_host()
.set_mutation_observer_records_enabled(mutation_records_enabled);
- retired
+ retired.saturating_add(host.common.callbacks.retire_execution_context_owner(owner))
}
pub(crate) fn retire_context_token(
@@ -408,7 +275,7 @@ pub(crate) fn retire_context_token(
};
host.dom_host()
.set_mutation_observer_records_enabled(mutation_records_enabled);
- retired
+ retired.saturating_add(host.common.callbacks.retire_context_token(context_token))
}
pub(super) fn observe_intersection_target(
diff --git a/moli-renderer-v8/src/observer_runtime/mod.rs b/moli-renderer-v8/src/observer_runtime/mod.rs
index c334bb92c..e586b5d11 100644
--- a/moli-renderer-v8/src/observer_runtime/mod.rs
+++ b/moli-renderer-v8/src/observer_runtime/mod.rs
@@ -5,15 +5,9 @@ mod dom_access;
mod intersection;
mod schedule;
-pub(crate) use callback::ObserverCallbackId;
-#[cfg(test)]
-pub(crate) use dom_access::callback_binding_count_for_test;
pub(crate) use dom_access::{
- ObserverCallbackResidence, ObserverStoreAccessToken, activate_performance_observer_callback,
- active_performance_observer_callbacks, callback_is_current,
- coalesce_child_list_replacement_records, deactivate_performance_observer_callback,
- flush_slotchange_microtask, prepare_callback, queue_intersection_checks,
- queue_mutation_records, register_callback, retire_context_token,
+ ObserverStoreAccessToken, coalesce_child_list_replacement_records, flush_slotchange_microtask,
+ queue_intersection_checks, queue_mutation_records, retire_context_token,
retire_execution_context_owner,
};
@@ -165,7 +159,6 @@ struct IntersectionObserverEntryPrototypeAccessorsDeclaration {
#[derive(Default)]
pub(super) struct ObserverStore {
- callback_registry: callback::ObserverCallbackRegistry,
next_mutation_observer_id: u32,
mutation_observers: HashMap<u32, MutationObserverState>,
mutation_delivery_scheduled: bool,
@@ -812,20 +805,14 @@ impl ObserverStore {
&mut self,
owner: crate::native_bridge::WindowExecutionContextOwner,
) -> usize {
- self.callback_registry
- .retire_execution_context_owner(owner)
- .saturating_add(self.retain_callbacks(|callback| !callback.is_owned_by(owner)))
+ self.retain_callbacks(|callback| !callback.is_owned_by(owner))
}
fn retire_context_token(
&mut self,
context_token: crate::native_bridge::RuntimeObservableContextToken,
) -> usize {
- self.callback_registry
- .retire_context_token(context_token)
- .saturating_add(
- self.retain_callbacks(|callback| !callback.belongs_to_context_token(context_token)),
- )
+ self.retain_callbacks(|callback| !callback.belongs_to_context_token(context_token))
}
fn retain_callbacks(
diff --git a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs
index 2e5875046..158bb272d 100644
--- a/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs
+++ b/moli-renderer-v8/src/script_vm/tests/observer_callbacks.rs
@@ -20,6 +20,65 @@ fn observer_callback_test_vm(url: &str) -> StandaloneScriptVmHarness {
vm
}
+#[test]
+fn common_callback_registry_keeps_active_observers_until_owner_teardown() {
+ let mut vm = new_storage_test_vm("https://performance-observer-active-root.test/");
+ let common = std::rc::Rc::clone(&vm._context_host.borrow().common);
+ vm.eval(
+ r#"
+globalThis.__activeObserverEntries = [];
+new PerformanceObserver(list => {
+ __activeObserverEntries.push(...list.getEntries().map(entry => entry.name));
+}).observe({ type: 'mark' });
+"#,
+ )
+ .expect("register an observer with no independent JS root");
+ vm.renderer_document_isolate_ops()
+ .collect_renderer_document_isolate_garbage()
+ .expect("collect unreachable observer wrappers");
+ assert_eq!(common.callbacks.len(), 1);
+ vm.eval("performance.mark('after-gc')")
+ .expect("deliver to the active observer after GC");
+ assert_eq!(
+ vm.eval("JSON.stringify(__activeObserverEntries)").unwrap(),
+ r#"["after-gc"]"#,
+ );
+ drop(vm);
+ assert_eq!(common.callbacks.len(), 0);
+ assert_eq!(common.finalizer_count(), 0);
+}
+
+#[test]
+fn performance_observer_registration_uses_its_own_global_with_a_foreign_callback_realm() {
+ let mut vm = observer_callback_test_vm("https://performance-observer-global-isolation.test/");
+ vm.eval(
+ r#"
+(() => {
+ const child = __observerCallbackFrame.contentWindow;
+ globalThis.__timelineEntries = { parent: [], child: [], callbackRealms: [] };
+ globalThis.__parentTimelineObserver = new PerformanceObserver(child.Function(
+ 'list',
+ `parent.__timelineEntries.parent.push(...list.getEntries().map(entry => entry.name));
+ parent.__timelineEntries.callbackRealms.push(globalThis === parent.__observerCallbackFrame.contentWindow);`
+ ));
+ globalThis.__childTimelineObserver = new child.PerformanceObserver(list => {
+ __timelineEntries.child.push(...list.getEntries().map(entry => entry.name));
+ __timelineEntries.callbackRealms.push(globalThis === window);
+ });
+ __parentTimelineObserver.observe({ type: 'mark' });
+ __childTimelineObserver.observe({ type: 'mark' });
+ performance.mark('parent-only');
+ child.performance.mark('child-only');
+})()
+"#,
+ )
+ .expect("queue separate global timelines with crossed callback realms");
+ assert_eq!(
+ vm.eval("JSON.stringify(__timelineEntries)").unwrap(),
+ r#"{"parent":["parent-only"],"child":["child-only"],"callbackRealms":[true,true]}"#,
+ );
+}
+
#[test]
fn document_preinsert_validation_precedes_mutation_and_adoption() {
let mut vm = observer_callback_test_vm("https://document-preinsert.test/");
@@ -300,9 +359,7 @@ fn js_owned_observer_callback_cycles_remain_v8_collectable() {
.expect("JS-owned observer callback cycles should be created");
assert_eq!(created, "256");
assert_eq!(
- crate::observer_runtime::callback_binding_count_for_test(
- &mut vm._context_host.borrow_mut()
- ),
+ vm._context_host.borrow().common.callbacks.len(),
256,
"each unreachable observer must still start with one exact callback identity binding"
);
@@ -315,9 +372,7 @@ fn js_owned_observer_callback_cycles_remain_v8_collectable() {
.expect("renderer isolate GC should complete");
assert_eq!(
- crate::observer_runtime::callback_binding_count_for_test(
- &mut vm._context_host.borrow_mut()
- ),
+ vm._context_host.borrow().common.callbacks.len(),
0,
"a Rust callback registry must not root an unreachable callback-observer cycle"
);
diff --git a/moli-renderer-v8/src/script_vm/tests/performance_observer_contract.rs b/moli-renderer-v8/src/script_vm/tests/performance_observer_contract.rs
index 552b29404..66917ff00 100644
--- a/moli-renderer-v8/src/script_vm/tests/performance_observer_contract.rs
+++ b/moli-renderer-v8/src/script_vm/tests/performance_observer_contract.rs
@@ -1,5 +1,19 @@
use super::*;
+#[test]
+fn performance_observer_delivery_follows_registration_order_after_reobserve() {
+ let mut vm = new_storage_test_vm("https://performance-observer-registration-order.test/");
+ let source = format!(
+ "({}).then(result => globalThis.__registrationOrder = result, error => globalThis.__registrationOrder = {{ error: String(error) }});",
+ include_str!("../../../tests/fixtures/performance-observer-registration-order.js"),
+ );
+ vm.eval(&source).expect("queue registered observers");
+ assert_eq!(
+ vm.eval("JSON.stringify(__registrationOrder)").unwrap(),
+ r#"["second:initial","first:initial","first:reobserved","second:reobserved"]"#,
+ );
+}
+
#[test]
fn performance_observer_delivery_preserves_batches_and_reentrant_registration() {
let mut vm = new_storage_test_vm("https://performance-observer-delivery.test/");
diff --git a/moli-renderer-v8/src/worker/thread/tests/callback_execution.rs b/moli-renderer-v8/src/worker/thread/tests/callback_execution.rs
index a8356d9f3..d97f4332c 100644
--- a/moli-renderer-v8/src/worker/thread/tests/callback_execution.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/callback_execution.rs
@@ -1,5 +1,26 @@
use super::*;
+#[tokio::test]
+async fn worker_performance_observer_delivery_follows_registration_order_after_reobserve() {
+ ensure_v8();
+ let source = format!(
+ "({}).then(result => {{ postMessage(result); close(); }}, error => {{ postMessage({{ error: String(error) }}); close(); }});",
+ include_str!("../../../../tests/fixtures/performance-observer-registration-order.js"),
+ );
+ let mut handle = spawn_worker(
+ source,
+ "test://performance-observer-registration-order".into(),
+ );
+ let message = timeout(TIMEOUT, handle.recv())
+ .await
+ .expect("registered observer delivery timed out")
+ .expect("worker closed before reporting registration order");
+ assert_eq!(
+ expect_post_json(message),
+ r#"["second:initial","first:initial","first:reobserved","second:reobserved"]"#,
+ );
+}
+
#[tokio::test]
async fn worker_webidl_callback_execution_preserves_api_exception_policies() {
ensure_v8();
diff --git a/moli-renderer-v8/tests/fixtures/performance-observer-registration-order.js b/moli-renderer-v8/tests/fixtures/performance-observer-registration-order.js
new file mode 100644
index 000000000..f2f922104
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/performance-observer-registration-order.js
@@ -0,0 +1,27 @@
+(async () => {
+ const events = [];
+ let acknowledge;
+ let remaining;
+ const callback = label => list => {
+ events.push(...list.getEntries().map(entry => label + ':' + entry.name));
+ if (--remaining === 0) acknowledge();
+ };
+ const first = new PerformanceObserver(callback('first'));
+ const second = new PerformanceObserver(callback('second'));
+ const batch = async (name, observers) => {
+ first.disconnect();
+ second.disconnect();
+ const delivered = new Promise(resolve => acknowledge = resolve);
+ remaining = observers.length;
+ for (const observer of observers) observer.observe({ type: 'mark' });
+ // Updating an existing registration must preserve its position.
+ observers[0].observe({ type: 'mark' });
+ performance.mark(name);
+ await delivered;
+ };
+ await batch('initial', [second, first]);
+ await batch('reobserved', [first, second]);
+ first.disconnect();
+ second.disconnect();
+ return events;
+})()