Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(performance): own resource timing buffer state in workers

ldm08245bfdadc33
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/resource_buffer.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/resource_buffer.rs
index 9415f3570..5781df2e2 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/resource_buffer.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/resource_buffer.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::web_api_interfaces;
use crate::{
- native_bridge::{JsContextHost, ResourceTimingBufferId},
+ native_bridge::{JsContextHost, ResourceTimingBufferId, SharedResourceTimingBufferRegistry},
util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value},
webidl,
};
@@ -48,13 +48,13 @@ pub(super) fn initialize_resource_timing_buffer_state<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
) {
- if resource_timing_buffer_context(scope, performance).is_some() {
+ if resource_timing_buffer_id(scope, performance).is_some() {
return;
}
- let host_ptr = context_host_ptr_from_global_bridge(scope)
- .expect("Performance must be initialized in a renderer context");
- let (buffer_id, finalizer) = unsafe { &mut *host_ptr }
- .create_resource_timing_buffer(DEFAULT_RESOURCE_TIMING_BUFFER_SIZE);
+ let registry = resource_timing_buffer_registry(scope)
+ .expect("Performance must belong to a page or worker context");
+ let (buffer_id, finalizer) =
+ registry.create_resource_timing_buffer(DEFAULT_RESOURCE_TIMING_BUFFER_SIZE);
let id = v8::BigInt::new_from_u64(scope, buffer_id.raw());
set_private_value(
scope,
@@ -112,8 +112,10 @@ fn set_resource_timing_buffer_size_callback<'s>(
return;
};
initialize_resource_timing_buffer_state(scope, performance);
- if let Some((host_ptr, buffer_id)) = resource_timing_buffer_context(scope, performance) {
- unsafe { &*host_ptr }.set_resource_timing_buffer_size_limit(buffer_id, parsed.max_size);
+ if let Some(registry) = resource_timing_buffer_registry(scope)
+ && let Some(buffer_id) = resource_timing_buffer_id(scope, performance)
+ {
+ registry.set_resource_timing_buffer_size_limit(buffer_id, parsed.max_size);
}
rv.set_undefined();
}
@@ -154,6 +156,23 @@ fn resource_timing_buffer_context<'s>(
performance: v8::Local<'s, v8::Object>,
) -> Option<(*mut JsContextHost, ResourceTimingBufferId)> {
let host_ptr = context_host_ptr_from_global_bridge(scope)?;
+ resource_timing_buffer_id(scope, performance).map(|id| (host_ptr, id))
+}
+
+fn resource_timing_buffer_registry(
+ scope: &mut v8::PinScope<'_, '_>,
+) -> Option<SharedResourceTimingBufferRegistry> {
+ if let Some(state) = crate::worker::get_worker_state(scope) {
+ return Some(state.borrow().resource_timing_buffers.clone());
+ }
+ let host_ptr = context_host_ptr_from_global_bridge(scope)?;
+ Some(unsafe { &*host_ptr }.resource_timing_buffer_registry())
+}
+
+fn resource_timing_buffer_id<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ performance: v8::Local<'s, v8::Object>,
+) -> Option<ResourceTimingBufferId> {
let value = get_private_value(
scope,
performance,
@@ -164,7 +183,6 @@ fn resource_timing_buffer_context<'s>(
lossless
.then(|| ResourceTimingBufferId::from_raw(raw))
.flatten()
- .map(|id| (host_ptr, id))
}
fn clear_primary_resource_timings<'s>(
@@ -196,8 +214,10 @@ fn clear_primary_resource_timings<'s>(
PERFORMANCE_ENTRIES_SLOT,
retained.into(),
);
- if let Some((host_ptr, buffer_id)) = resource_timing_buffer_context(scope, performance) {
- unsafe { &*host_ptr }.clear_resource_timing_primary_buffer(buffer_id);
+ if let Some(registry) = resource_timing_buffer_registry(scope)
+ && let Some(buffer_id) = resource_timing_buffer_id(scope, performance)
+ {
+ registry.clear_resource_timing_primary_buffer(buffer_id);
}
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
index 8c943928c..aff2dc02c 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -69,7 +69,7 @@ use std::{
use url::Url;
use widestring::U16String;
-use self::resource_timing::SharedResourceTimingBufferRegistry;
+pub(crate) use self::resource_timing::SharedResourceTimingBufferRegistry;
mod activity;
mod bridge_install;
diff --git a/moli-renderer-v8/src/native_bridge/context_host/resource_timing.rs b/moli-renderer-v8/src/native_bridge/context_host/resource_timing.rs
index 3103c3d59..27e0bcfc2 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/resource_timing.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/resource_timing.rs
@@ -66,11 +66,13 @@ impl ResourceTimingBufferRegistry {
}
}
+// A page host and each worker own separate registries. Performance objects keep
+// only an opaque id; their context-owned finalizers release the native state.
#[derive(Clone)]
-pub(super) struct SharedResourceTimingBufferRegistry(Rc<RefCell<ResourceTimingBufferRegistry>>);
+pub(crate) struct SharedResourceTimingBufferRegistry(Rc<RefCell<ResourceTimingBufferRegistry>>);
impl SharedResourceTimingBufferRegistry {
- pub(super) fn new() -> Self {
+ pub(crate) fn new() -> Self {
Self(Rc::new(RefCell::new(
ResourceTimingBufferRegistry::default(),
)))
@@ -90,18 +92,14 @@ impl ResourceTimingBufferFinalizer {
}
}
-impl JsContextHost {
+impl SharedResourceTimingBufferRegistry {
pub(crate) fn create_resource_timing_buffer(
- &mut self,
+ &self,
size_limit: u32,
) -> (ResourceTimingBufferId, ResourceTimingBufferFinalizer) {
- let id = self
- .resource_timing_buffers
- .0
- .borrow_mut()
- .insert(size_limit);
+ let id = self.0.borrow_mut().insert(size_limit);
let finalizer = ResourceTimingBufferFinalizer {
- registry: Rc::downgrade(&self.resource_timing_buffers.0),
+ registry: Rc::downgrade(&self.0),
id,
};
(id, finalizer)
@@ -112,17 +110,23 @@ impl JsContextHost {
id: ResourceTimingBufferId,
size_limit: u32,
) {
- if let Some(state) = self
- .resource_timing_buffers
- .0
- .borrow_mut()
- .buffers
- .get_mut(&id)
- {
+ if let Some(state) = self.0.borrow_mut().buffers.get_mut(&id) {
state.size_limit = size_limit;
}
}
+ pub(crate) fn clear_resource_timing_primary_buffer(&self, id: ResourceTimingBufferId) {
+ if let Some(state) = self.0.borrow_mut().buffers.get_mut(&id) {
+ state.current_size = 0;
+ }
+ }
+}
+
+impl JsContextHost {
+ pub(crate) fn resource_timing_buffer_registry(&self) -> SharedResourceTimingBufferRegistry {
+ self.resource_timing_buffers.clone()
+ }
+
pub(crate) fn resource_timing_buffer_can_add_immediately(
&self,
id: ResourceTimingBufferId,
@@ -159,18 +163,6 @@ impl JsContextHost {
}
}
- pub(crate) fn clear_resource_timing_primary_buffer(&self, id: ResourceTimingBufferId) {
- if let Some(state) = self
- .resource_timing_buffers
- .0
- .borrow_mut()
- .buffers
- .get_mut(&id)
- {
- state.current_size = 0;
- }
- }
-
pub(crate) fn mark_resource_timing_buffer_full_task_pending(
&self,
id: ResourceTimingBufferId,
@@ -275,16 +267,41 @@ mod tests {
}
#[test]
- fn registry_ids_are_nonzero_and_finalizer_removes_state() {
- let shared = SharedResourceTimingBufferRegistry::new();
- let id = shared.0.borrow_mut().insert(250);
- assert_ne!(id.raw(), 0);
- let finalizer = ResourceTimingBufferFinalizer {
- registry: Rc::downgrade(&shared.0),
- id,
- };
+ fn buffer_configuration_and_finalization_stay_with_the_owning_registry() {
+ let first = SharedResourceTimingBufferRegistry::new();
+ let second = SharedResourceTimingBufferRegistry::new();
+ let (first_id, first_finalizer) = first.create_resource_timing_buffer(1);
+ let (second_id, second_finalizer) = second.create_resource_timing_buffer(250);
+ assert_ne!(first_id.raw(), 0);
+ assert_eq!(first_id, second_id, "ids are local to each owner");
+
+ {
+ let mut registry = first.0.borrow_mut();
+ let state = registry.buffers.get_mut(&first_id).unwrap();
+ state.current_size = 1;
+ state.full_task_pending = true;
+ }
+ let borrowed = first.clone();
+ borrowed.set_resource_timing_buffer_size_limit(first_id, 2);
+ borrowed.clear_resource_timing_primary_buffer(first_id);
+ {
+ let registry = first.0.borrow();
+ let state = registry.buffers.get(&first_id).unwrap();
+ assert_eq!(state.size_limit, 2);
+ assert_eq!(state.current_size, 0);
+ assert!(
+ state.full_task_pending,
+ "clearing must retain the pending task"
+ );
+ assert!(state.can_add_to_primary());
+ assert!(!state.can_add_immediately());
+ }
+ assert_eq!(second.0.borrow().buffers[&second_id].size_limit, 250);
- finalizer.finalize();
- assert!(!shared.0.borrow().buffers.contains_key(&id));
+ first_finalizer.finalize();
+ assert!(!first.0.borrow().buffers.contains_key(&first_id));
+ assert!(second.0.borrow().buffers.contains_key(&second_id));
+ second_finalizer.finalize();
+ assert!(second.0.borrow().buffers.is_empty());
}
}
diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs
index 9906555fb..b37fda9a8 100644
--- a/moli-renderer-v8/src/native_bridge/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/mod.rs
@@ -9,7 +9,7 @@ mod current_input;
pub(crate) use context_host::{
JsContextHost, JsContextHostPageTaskCapabilities, MouseReleaseFollowUp,
PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner,
- caller_can_access_window,
+ SharedResourceTimingBufferRegistry, caller_can_access_window,
};
pub(crate) use current_input::{
CurrentInputEvent, CurrentInputEventScope, InputNavigationPolicy, navigation_policy_from_event,
diff --git a/moli-renderer-v8/src/worker/global_scope/state.rs b/moli-renderer-v8/src/worker/global_scope/state.rs
index a33396eeb..bcb86cd6e 100644
--- a/moli-renderer-v8/src/worker/global_scope/state.rs
+++ b/moli-renderer-v8/src/worker/global_scope/state.rs
@@ -17,6 +17,9 @@ impl WorkerGlobalState {
pub(crate) struct WorkerGlobalState {
/// Components shared with Window runtimes, owned by this Worker run.
pub(crate) common: Rc<crate::common_runtime::CommonRuntimeState>,
+ /// Resource Timing capacity and overflow state belongs to this worker,
+ /// independently from its creator's Window or any other worker.
+ pub(crate) resource_timing_buffers: crate::native_bridge::SharedResourceTimingBufferRegistry,
/// 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/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rs
index 07cc93917..807e59668 100644
--- a/moli-renderer-v8/src/worker/thread/mod.rs
+++ b/moli-renderer-v8/src/worker/thread/mod.rs
@@ -1623,6 +1623,7 @@ async fn worker_main(
.map(|client| client.client_id);
let state = Rc::new(RefCell::new(WorkerGlobalState {
common: Rc::new(crate::common_runtime::CommonRuntimeState::default()),
+ resource_timing_buffers: crate::native_bridge::SharedResourceTimingBufferRegistry::new(),
parent_tx: parent_tx.clone(),
worker_wake_tx,
termination_requested: Arc::clone(&termination_requested),
diff --git a/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_and_fetch_lifecycle.rs b/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_and_fetch_lifecycle.rs
index ffab584b4..5ecb75425 100644
--- a/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_and_fetch_lifecycle.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/lifecycle/worker_and_fetch_lifecycle.rs
@@ -1,5 +1,42 @@
use super::*;
+#[tokio::test]
+async fn worker_resource_timing_buffer_configuration_does_not_require_a_window() {
+ ensure_v8();
+ for iteration in 0..2 {
+ let mut handle = spawn_worker(
+ r#"
+ const handler = () => {};
+ performance.onresourcetimingbufferfull = handler;
+ performance.mark("before");
+ performance.setResourceTimingBufferSize(1);
+ performance.clearResourceTimings();
+ performance.setResourceTimingBufferSize(100);
+ performance.mark("after");
+ postMessage(JSON.stringify({
+ marks: performance.getEntriesByType("mark").map(entry => entry.name),
+ resources: performance.getEntriesByType("resource").length,
+ sameHandler: performance.onresourcetimingbufferfull === handler
+ }));
+ "#
+ .into(),
+ format!("test://worker-resource-timing-buffer-{iteration}"),
+ );
+ let message = timeout(TIMEOUT, handle.recv())
+ .await
+ .expect("timed out waiting for worker resource buffer configuration")
+ .expect("worker closed before resource buffer configuration completed");
+ match message {
+ WorkerToParentMessage::Post(payload) => assert_eq!(
+ stringify_payload(&payload),
+ r#""{\"marks\":[\"before\",\"after\"],\"resources\":0,\"sameHandler\":true}""#,
+ ),
+ other => panic!("unexpected worker resource buffer result: {other:?}"),
+ }
+ handle.terminate_and_join();
+ }
+}
+
#[tokio::test]
async fn dedicated_worker_agent_allows_blocking_atomics_wait() {
ensure_v8();