refactor(renderer): unify child Window realm state

This commit is contained in:
ldm0
2026-11-21 19:22:34 +08:00
parent 841433abec
commit ef6aa544a6
19 changed files with 354 additions and 55 deletions
+5 -2
View File
@@ -474,11 +474,14 @@ pub(crate) use self::notification_runtime::{
build_notification_object_from_snapshot, notification_get_options_tag,
notification_options_payload,
};
#[cfg(test)]
pub(crate) use self::performance_runtime::bind_window_performance_seed;
pub(crate) use self::performance_runtime::{
FetchResourceTiming, ResourcePerformanceEntry, bind_document_performance,
bind_window_performance_seed, current_performance_time_origin,
bind_window_document_performance, current_performance_time_origin,
increment_performance_event_count, project_document_lifecycle_timing,
record_resource_performance_entry, run_resource_timing_buffer_full_task,
project_window_document_lifecycle_timing, record_resource_performance_entry,
run_resource_timing_buffer_full_task,
};
use self::range_live::{
update_live_ranges_for_character_data_edit, update_live_ranges_for_character_data_reset,
@@ -76,7 +76,12 @@ pub(super) use marks_measures::{
pub(crate) use moli_webapi::performance::observer::finalize_performance_observer_realm_bindings;
pub(super) use resource_buffer::resource_timing_dropped_entries_count;
pub(crate) use resource_buffer::run_resource_timing_buffer_full_task;
pub(crate) use window_state::{bind_document_performance, bind_window_performance_seed};
#[cfg(test)]
pub(crate) use window_state::bind_window_performance_seed;
pub(crate) use window_state::{
bind_document_performance, bind_window_document_performance,
project_window_document_lifecycle_timing,
};
pub(super) use window_state::{
build_window_performance_for_receiver, ensure_current_window_performance,
finish_window_performance_materialization, install_default_window_performance_seed,
@@ -29,11 +29,41 @@ pub(crate) fn bind_document_performance<'s>(
window: v8::Local<'s, v8::Object>,
timing: crate::document_runtime::DocumentTimingSnapshot,
) -> Result<()> {
bind_window_performance_seed(scope, window, "navigate", timing.time_origin)?;
super::install::project_window_lifecycle_timing(scope, window, timing.lifecycle, false);
bind_window_document_performance(scope, window, "navigate", timing)
}
pub(crate) fn bind_window_document_performance<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
navigation_type: &str,
timing: crate::document_runtime::DocumentTimingSnapshot,
) -> Result<()> {
bind_window_performance_seed(scope, window, navigation_type, timing.time_origin)?;
project_window_document_lifecycle_timing(scope, window, timing, false);
Ok(())
}
pub(crate) fn project_window_document_lifecycle_timing<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
timing: crate::document_runtime::DocumentTimingSnapshot,
notify_observers: bool,
) {
let Some(context) = window.get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let window = context.global(scope);
if time_origin_seed_value(scope, window) == Some(timing.time_origin) {
super::install::project_window_lifecycle_timing(
scope,
window,
timing.lifecycle,
notify_observers,
);
}
}
pub(crate) fn bind_window_performance_seed<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
+1 -1
View File
@@ -30,7 +30,7 @@ mod security_policy;
#[path = "stylesheet_runtime/mod.rs"]
mod stylesheet_runtime;
mod timing;
pub(crate) use timing::{DocumentLifecycleTiming, DocumentTimingSnapshot};
pub(crate) use timing::{DocumentLifecycleTiming, DocumentTiming, DocumentTimingSnapshot};
#[cfg(test)]
pub(crate) use mutation_commands::ParserPostStepRuntimeWorkForTest;
+21 -11
View File
@@ -19,8 +19,8 @@ pub(crate) struct DocumentTimingSnapshot {
/// The Document records lifecycle facts even when it has no JavaScript realm.
/// Performance objects only project these timestamps; materializing a wrapper
/// must neither restart the clock nor record/replay a lifecycle event.
#[derive(Debug)]
pub(super) struct DocumentTiming {
#[derive(Debug, Clone)]
pub(crate) struct DocumentTiming {
time_origin: f64,
started: Instant,
lifecycle: [Option<f64>; 4],
@@ -46,26 +46,36 @@ impl DocumentRuntime {
}
pub(crate) fn document_timing_snapshot(&self) -> DocumentTimingSnapshot {
DocumentTimingSnapshot {
time_origin: self.timing.time_origin,
lifecycle: self.timing.lifecycle,
}
self.timing.snapshot()
}
pub(crate) fn record_lifecycle_timing(
&mut self,
phase: DocumentLifecycleTiming,
) -> DocumentTimingSnapshot {
self.timing.record(phase)
}
}
impl DocumentTiming {
pub(crate) fn snapshot(&self) -> DocumentTimingSnapshot {
DocumentTimingSnapshot {
time_origin: self.time_origin,
lifecycle: self.lifecycle,
}
}
pub(crate) fn record(&mut self, phase: DocumentLifecycleTiming) -> DocumentTimingSnapshot {
let index = phase as usize;
if self.timing.lifecycle[index].is_none() {
let previous = self.timing.lifecycle[..index]
if self.lifecycle[index].is_none() {
let previous = self.lifecycle[..index]
.iter()
.flatten()
.copied()
.fold(0.0, f64::max);
self.timing.lifecycle[index] =
Some((self.timing.started.elapsed().as_secs_f64() * 1000.0).max(previous + 0.001));
self.lifecycle[index] =
Some((self.started.elapsed().as_secs_f64() * 1000.0).max(previous + 0.001));
}
self.document_timing_snapshot()
self.snapshot()
}
}
@@ -11,7 +11,7 @@ use crate::{
dispatch_pagehide_for_runtime_owner, dispatch_unload_for_runtime_owner,
},
detached_event_target::dispatch_detached_simple_event,
document_runtime::DomHandle,
document_runtime::{DocumentLifecycleTiming, DomHandle},
dom::native::DocumentReadyState,
frame_owner_model::{
FrameDocumentCompleteLifecycleAction, FrameDocumentDescendantLoadCompletion,
@@ -725,6 +725,12 @@ impl PageScriptHost {
crate::native_bridge::WindowDocumentOwner::Frame(action.owner()),
);
}
self.record_child_document_lifecycle_timing(
scope,
child_handle,
action.owner(),
DocumentLifecycleTiming::DomContentLoadedStart,
);
let event_dispatched = self
.child_browsing_context_document_wrapper(scope, child_handle)
.is_some_and(|document| {
@@ -738,6 +744,12 @@ impl PageScriptHost {
false,
)
});
self.record_child_document_lifecycle_timing(
scope,
child_handle,
action.owner(),
DocumentLifecycleTiming::DomContentLoadedEnd,
);
if self
.frame_owner_store
.child_document_task_owner_is_current(child_handle, action.owner())
@@ -6,8 +6,8 @@ use super::{
};
use crate::{
context_bootstrap::{
WINDOW_NAME_SLOT, bind_current_child_window_document, bind_window_navigator_identity_seed,
bind_window_performance_seed, install_navigation_bootstrap_entry_for_holder,
WINDOW_NAME_SLOT, bind_current_child_window_document, bind_window_document_performance,
bind_window_navigator_identity_seed, install_navigation_bootstrap_entry_for_holder,
reset_window_location_history_navigation_runtime_state, set_window_origin_runtime_state,
sync_window_location_history_navigation_runtime_surface,
},
@@ -53,11 +53,11 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn initialize_ch
bind_frame_element(host, scope, global, init.handle);
bind_navigation(scope, global, &snapshot)?;
set_window_origin_runtime_state(scope, global, &snapshot.origin)?;
bind_window_performance_seed(
bind_window_document_performance(
scope,
global,
&snapshot.navigation_type,
snapshot.performance_time_origin,
snapshot.performance_timing,
)?;
let document = host
.child_browsing_context_document_wrapper(scope, init.handle)
@@ -110,11 +110,11 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn rebind_child_
bind_frame_element(host, scope, global, rebind.handle);
bind_navigation(scope, global, &snapshot)?;
set_window_origin_runtime_state(scope, global, &snapshot.origin)?;
bind_window_performance_seed(
bind_window_document_performance(
scope,
global,
&snapshot.navigation_type,
snapshot.performance_time_origin,
snapshot.performance_timing,
)?;
bind_materialized_child_window_indexed_db_factory(scope, global, rebind.handle);
let document = host
@@ -48,7 +48,7 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) struct ChildWind
pub(super) window_name: String,
pub(super) navigation_seed: NavigationHistoryEntrySeed,
pub(super) navigation_type: String,
pub(super) performance_time_origin: f64,
pub(super) performance_timing: crate::document_runtime::DocumentTimingSnapshot,
pub(super) policy: DocumentPolicyContainer,
}
@@ -28,7 +28,7 @@ pub(super) fn capture_child_window_realm_snapshot(
window_name: entry.window_name().to_owned(),
navigation_seed: entry.committed_navigation_entry_seed(),
navigation_type: entry.performance_navigation_type().to_owned(),
performance_time_origin: entry.performance_time_origin_millis(),
performance_timing: entry.document_performance_timing(),
policy: entry.document_policy_container_snapshot(),
};
@@ -2,7 +2,7 @@ use super::super::PageScriptHost;
use super::document_slots::sync_child_document_window_slots;
use crate::{
context_bootstrap::{
bind_window_performance_seed, install_navigation_entry_view_for_holder,
bind_window_document_performance, install_navigation_entry_view_for_holder,
reset_window_location_history_navigation_runtime_state, set_window_origin_runtime_state,
sync_window_location_history_navigation_runtime_surface, window_location_href,
},
@@ -103,12 +103,14 @@ impl PageScriptHost {
}
install_navigation_entry_view_for_holder(scope, wrapper, &visible_state.entry_seed);
let performance_navigation_type = self.child_performance_navigation_type(handle);
let _ = bind_window_performance_seed(
scope,
wrapper,
&performance_navigation_type,
self.child_performance_time_origin(handle),
);
if let Some(timing) = self.child_document_performance_timing(handle) {
let _ = bind_window_document_performance(
scope,
wrapper,
&performance_navigation_type,
timing,
);
}
bind_materialized_child_window_indexed_db_factory(scope, wrapper, handle);
let document = self
.child_browsing_context_document_wrapper(scope, handle)
@@ -167,12 +169,14 @@ impl PageScriptHost {
);
install_navigation_entry_view_for_holder(scope, wrapper, &entry_seed);
let performance_navigation_type = self.child_performance_navigation_type(handle);
let _ = bind_window_performance_seed(
scope,
wrapper,
&performance_navigation_type,
self.child_performance_time_origin(handle),
);
if let Some(timing) = self.child_document_performance_timing(handle) {
let _ = bind_window_document_performance(
scope,
wrapper,
&performance_navigation_type,
timing,
);
}
sync_window_location_history_navigation_runtime_surface(scope, wrapper);
}
}
@@ -1513,11 +1513,37 @@ impl PageScriptHost {
.to_owned()
}
pub(crate) fn child_performance_time_origin(&self, handle: DomHandle) -> f64 {
pub(crate) fn child_document_performance_timing(
&self,
handle: DomHandle,
) -> Option<crate::document_runtime::DocumentTimingSnapshot> {
self.child_browsing_contexts
.get(&handle)
.map(|entry| entry.performance_time_origin_millis())
.unwrap_or_else(moli_time::unix_epoch_millis)
.map(|entry| entry.document_performance_timing())
}
pub(in crate::native_bridge::context_host) fn record_child_document_lifecycle_timing(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
owner: crate::frame_owner_model::FrameDocumentTaskOwner,
phase: crate::document_runtime::DocumentLifecycleTiming,
) {
if !self
.frame_owner_store
.child_document_task_owner_is_current(handle, owner)
{
return;
}
let Some(entry) = self.child_browsing_contexts.get_mut(&handle) else {
return;
};
let timing = entry.record_document_lifecycle_timing(phase);
if let Some(window) = self.existing_child_browsing_context_window_wrapper(scope, handle) {
crate::context_bootstrap::project_window_document_lifecycle_timing(
scope, window, timing, true,
);
}
}
}
@@ -7,7 +7,10 @@ use super::{
PageScriptHost, child_documents::CompletedFrameOwnerResourceTiming,
};
use crate::{
document_runtime::{DocumentPolicyContainer, DocumentSandboxPolicy, DomHandle},
document_runtime::{
DocumentLifecycleTiming, DocumentPolicyContainer, DocumentSandboxPolicy, DocumentTiming,
DocumentTimingSnapshot, DomHandle,
},
frame_owner_model::{
ChildFrameOwnerSnapshot, FrameDocumentTaskOwner, FrameId, FrameRealmId, FrameScriptJob,
FrameScriptJobKind,
@@ -69,16 +72,12 @@ pub(super) struct ChildBrowsingContextEntry {
pub(super) type ChildDocumentPolicyContainer = DocumentPolicyContainer;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct ChildPerformanceTimeOrigin(u64);
#[derive(Debug, Clone)]
pub(super) struct ChildPerformanceTimeOrigin(DocumentTiming);
impl ChildPerformanceTimeOrigin {
pub(super) fn now() -> Self {
Self(moli_time::unix_epoch_millis().to_bits())
}
pub(super) fn as_millis(self) -> f64 {
f64::from_bits(self.0)
Self(DocumentTiming::default())
}
}
@@ -843,12 +842,19 @@ impl ChildBrowsingContextEntry {
.unwrap_or("navigate")
}
pub(super) fn performance_time_origin_millis(&self) -> f64 {
self.performance_time_origin.as_millis()
pub(super) fn performance_time_origin(&self) -> ChildPerformanceTimeOrigin {
self.performance_time_origin.clone()
}
pub(super) fn performance_time_origin(&self) -> ChildPerformanceTimeOrigin {
self.performance_time_origin
pub(super) fn document_performance_timing(&self) -> DocumentTimingSnapshot {
self.performance_time_origin.0.snapshot()
}
pub(super) fn record_document_lifecycle_timing(
&mut self,
phase: DocumentLifecycleTiming,
) -> DocumentTimingSnapshot {
self.performance_time_origin.0.record(phase)
}
pub(super) fn reset_performance_time_origin(&mut self) {
@@ -4,7 +4,10 @@ use crate::{
construct_original_event, construct_original_page_transition_event,
navigate_child_meta_refresh,
},
document_runtime::{DocumentRuntime, DomHandle, EventTargetHandle, MetaRefreshNavigation},
document_runtime::{
DocumentLifecycleTiming, DocumentRuntime, DomHandle, EventTargetHandle,
MetaRefreshNavigation,
},
frame_owner_model::{
FrameDocumentLoadDeliveryAction, FrameDocumentLoadDeliveryPhase,
FrameDocumentLoadDeliveryProgress,
@@ -389,7 +392,19 @@ impl PageScriptHost {
self.abort_and_requeue_child_load_delivery(action);
return ChildFrameLoadDeliveryPhaseResult::without_callback(None);
};
self.record_child_document_lifecycle_timing(
scope,
handle,
action.owner(),
DocumentLifecycleTiming::LoadStart,
);
self.dispatch_child_window_event(scope, handle, "load", event);
self.record_child_document_lifecycle_timing(
scope,
handle,
action.owner(),
DocumentLifecycleTiming::LoadEnd,
);
let progress = self
.frame_owner_store
.finish_current_child_document_load_delivery(action);
@@ -1141,6 +1141,61 @@ fn performance_navigation_timing_updates_at_load_event_end() {
);
}
#[test]
fn performance_navigation_lifecycle_timestamps_are_write_once_per_navigation() {
let mut vm = new_storage_test_vm("https://performance-navigation-write-once.test/");
vm.dispatch_document_lifecycle_event("DOMContentLoaded")
.expect("first DOMContentLoaded should update navigation timing");
vm.dispatch_window_load_event()
.expect("first load should update navigation timing");
vm.eval(
r#"
globalThis.__initialNavigationLifecycleTiming = (() => {
const navigation = performance.getEntriesByType("navigation")[0];
return [
navigation.domInteractive,
navigation.domContentLoadedEventStart,
navigation.domContentLoadedEventEnd,
navigation.domComplete,
navigation.loadEventStart,
navigation.loadEventEnd
];
})();
"#,
)
.expect("initial navigation lifecycle timing should be captured");
vm.dispatch_document_lifecycle_event("DOMContentLoaded")
.expect("repeated DOMContentLoaded should remain dispatchable");
vm.dispatch_window_load_event()
.expect("repeated load should remain dispatchable");
assert_eq!(
vm.eval(
r#"
(() => {
const navigation = performance.getEntriesByType("navigation")[0];
const current = [
navigation.domInteractive,
navigation.domContentLoadedEventStart,
navigation.domContentLoadedEventEnd,
navigation.domComplete,
navigation.loadEventStart,
navigation.loadEventEnd
];
return current.every(
(value, index) =>
value === globalThis.__initialNavigationLifecycleTiming[index]
);
})()
"#,
)
.expect("repeated navigation lifecycle timing should be compared"),
"true"
);
}
#[test]
fn materialized_legacy_performance_timing_uses_integer_milliseconds() {
const TIME_ORIGIN: f64 = 1_700_000_000_000.75;
@@ -1823,3 +1823,123 @@ fn html_constructor_proxy_handlers_ignore_inherited_get_traps() {
"#).expect("HTML constructor Proxy trap lookup should stay internal");
assert_eq!(result, "ok");
}
#[tokio::test]
async fn child_navigation_performance_name_updates_after_iframe_src_change() {
const HOST: &str = "child-navigation-performance.test";
let server = StaticHttpServer::spawn_with_bodies(vec![
include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/lightpanda/upstream/navigation-timing/resources/blank_page_green.html"
))
.to_owned(),
include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/lightpanda/upstream/navigation-timing/resources/blank_page_yellow.html"
))
.to_owned(),
])
.await;
let parent_url = server.url_for_host(HOST, "/page.html");
let loader = static_http_loader([server.resolve_entry(HOST)]);
let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);
vm.eval(
r#"
(() => {
globalThis.__childNavigationLoadCount = 0;
const frame = document.createElement("iframe");
globalThis.__childNavigationFrame = frame;
frame.onload = () => {
globalThis.__childNavigationLoadCount++;
};
frame.src = "/src/browser/tests/navigation-timing/resources/blank_page_green.html";
(document.body || document.documentElement || document).appendChild(frame);
})()
"#,
)
.expect("child navigation performance setup should evaluate");
let loads_before_initial_dispatch = vm
.eval("String(globalThis.__childNavigationLoadCount)")
.expect("initial child navigation load count should evaluate");
assert_eq!(loads_before_initial_dispatch, "0");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(globalThis.__childNavigationLoadCount)",
"1",
"initial child navigation performance load",
)
.await;
let first = vm
.eval(
r#"
(() => {
const frame = __childNavigationFrame;
const entry = frame.contentWindow.performance.getEntriesByType("navigation")[0];
const timing = frame.contentWindow.performance.timing;
return [
entry.name === frame.contentWindow.location.href,
entry.name.endsWith("/blank_page_green.html"),
globalThis.__childNavigationLoadCount,
timing.domInteractive > timing.navigationStart,
timing.loadEventStart >= timing.domInteractive,
timing.loadEventEnd >= timing.loadEventStart,
frame.contentWindow.performance.now() >=
timing.loadEventEnd - timing.navigationStart
].join(":");
})()
"#,
)
.expect("first child navigation performance probe should evaluate");
let lifecycle_timing = vm.eval(r#"JSON.stringify((() => {
const p = __childNavigationFrame.contentWindow.performance;
const n = p.getEntriesByType('navigation')[0];
return {timeOrigin:p.timeOrigin,now:p.now(),legacy:{navigationStart:p.timing.navigationStart,domInteractive:p.timing.domInteractive,loadEventStart:p.timing.loadEventStart,loadEventEnd:p.timing.loadEventEnd},navigation:{domInteractive:n.domInteractive,domContentLoadedEventStart:n.domContentLoadedEventStart,domContentLoadedEventEnd:n.domContentLoadedEventEnd,loadEventStart:n.loadEventStart,loadEventEnd:n.loadEventEnd}};
})())"#).expect("native child lifecycle values should be observable");
assert_eq!(
first, "true:true:1:true:true:true:true",
"native lifecycle timing: {lifecycle_timing}"
);
vm.eval(
r#"__childNavigationFrame.src = "/src/browser/tests/navigation-timing/resources/blank_page_yellow.html";"#,
)
.expect("second child navigation should queue");
let loads_before_second_dispatch = vm
.eval("String(globalThis.__childNavigationLoadCount)")
.expect("second child navigation pre-HostLoad load count should evaluate");
assert_eq!(loads_before_second_dispatch, "1");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(globalThis.__childNavigationLoadCount)",
"2",
"second child navigation performance load",
)
.await;
let result = vm
.eval(
r#"
(() => {
const frame = __childNavigationFrame;
const entry = frame.contentWindow.performance.getEntriesByType("navigation")[0];
return [
entry.name === frame.contentWindow.location.href,
entry.name.endsWith("/blank_page_yellow.html"),
globalThis.__childNavigationLoadCount
].join(":");
})()
"#,
)
.expect("second child navigation performance probe should evaluate");
assert_eq!(result, "true:true:2");
assert_eq!(
server.finish_targets().await,
vec![
"/src/browser/tests/navigation-timing/resources/blank_page_green.html",
"/src/browser/tests/navigation-timing/resources/blank_page_yellow.html",
]
);
}
@@ -0,0 +1,3 @@
<!doctype html>
<script>parent.postMessage("form navigation", "*");</script>
form navigation
@@ -0,0 +1,6 @@
<!doctype html>
<html>
<body>
<div id="target"></div>
</body>
</html>
@@ -0,0 +1,2 @@
<!doctype html>
<html><body>green</body></html>
@@ -0,0 +1,2 @@
<!doctype html>
<html><body>yellow</body></html>