diff --git a/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation.rs b/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation.rs
index 72aaa6ba8ca..6a4a3226920 100644
--- a/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation.rs
+++ b/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation.rs
@@ -4,6 +4,7 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
};
+mod document_close;
mod document_open;
mod history_traversal;
mod lifecycle;
diff --git a/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation/document_close.rs b/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation/document_close.rs
new file mode 100644
index 00000000000..9cde4e9c5d6
--- /dev/null
+++ b/moli-protocol/src/domains/page/tests/same_document_history/popup_network_navigation/document_close.rs
@@ -0,0 +1,48 @@
+use super::*;
+
+#[tokio::test(flavor = "multi_thread")]
+async fn document_close_completes_the_target_page_owner_lifecycle() {
+ const SCRIPT: &str = include_str!("../../../../../../tests/fixtures/document-close-owner.js");
+ const SOURCE: &str = "";
+ run_history_test(async {
+ for source in ["root", "iframe", "popup", "self"] {
+ for operation in ["same-turn", "later-close", "reopen"] {
+ let routes = axum::Router::new()
+ .route(
+ "/close-source",
+ axum::routing::get(|| async { axum::response::Html(SOURCE) }),
+ )
+ .route(
+ "/close-target",
+ axum::routing::get(|| async {
+ axum::response::Html("
Target")
+ }),
+ )
+ .route(
+ "/document-close-owner.js",
+ axum::routing::get(|| async {
+ (
+ [(axum::http::header::CONTENT_TYPE, "text/javascript")],
+ SCRIPT,
+ )
+ }),
+ );
+ let mut page = SameDocumentPage::with_routes(routes).await;
+ let result = page
+ .evaluate(&format!(
+ "{SCRIPT}\ndocumentCloseOwner(location.origin, {source:?}, {operation:?})"
+ ))
+ .await;
+ assert!(
+ result["checks"]
+ .as_object()
+ .unwrap()
+ .values()
+ .all(|value| value == &json!(true)),
+ "{result}"
+ );
+ }
+ }
+ })
+ .await;
+}
diff --git a/moli-protocol/tests/fixtures/document-close-owner.js b/moli-protocol/tests/fixtures/document-close-owner.js
new file mode 100644
index 00000000000..c3e5435c95d
--- /dev/null
+++ b/moli-protocol/tests/fixtures/document-close-owner.js
@@ -0,0 +1,97 @@
+function installDocumentCloseSource() {
+ addEventListener('message', event => {
+ if (event.data?.tag !== 'document-close-owner-command') return;
+ const controller = opener || parent;
+ const target = event.data.self ? globalThis : controller.__documentCloseOwnerTarget;
+ const result = performDocumentClose(target, event.data.operation);
+ controller.postMessage({tag: 'document-close-owner-result', result}, '*');
+ });
+}
+
+function performDocumentClose(target, operation) {
+ const doc = target.document;
+ if (operation !== 'close') {
+ doc.open();
+ if (target === globalThis) installDocumentCloseSource();
+ doc.write('replacement');
+ target.__documentCloseOwnerEvents = [];
+ const note = event => target.__documentCloseOwnerEvents.push(event.type + ':' + doc.readyState);
+ doc.addEventListener('readystatechange', note);
+ doc.addEventListener('DOMContentLoaded', note);
+ target.addEventListener('load', note);
+ }
+ if (operation === 'reopen') {
+ doc.close();
+ return performDocumentClose(target, 'same-turn');
+ }
+ if (operation !== 'open') doc.close();
+ return {readyState: doc.readyState, sameDocument: doc === target.document};
+}
+
+async function documentCloseOwner(base, sourceKind, operation) {
+ const pause = () => new Promise(resolve => setTimeout(resolve, 5));
+ const ready = async (win, url) => {
+ const deadline = performance.now() + 2000;
+ while (win.location.href !== url || win.document.readyState !== 'complete') {
+ if (performance.now() > deadline) throw Error('initial page did not load: ' + win.location.href);
+ await pause();
+ }
+ };
+ const targetURL = base + (sourceKind === 'self' ? '/close-source' : '/close-target');
+ const target = open(targetURL, 'document-close-owner-target');
+ let source;
+ let frame;
+ try {
+ await ready(target, targetURL);
+ const original = target.document;
+ globalThis.__documentCloseOwnerTarget = target;
+ if (sourceKind === 'iframe') {
+ frame = document.createElement('iframe');
+ frame.src = base + '/close-source';
+ document.body.appendChild(frame);
+ source = frame.contentWindow;
+ } else if (sourceKind === 'popup') source = open(base + '/close-source');
+ else if (sourceKind === 'self') source = target;
+ if (source && source !== target) await ready(source, base + '/close-source');
+ async function invoke(command) {
+ if (!source) return performDocumentClose(target, command);
+ const response = new Promise(resolve => {
+ function receive(event) {
+ if (event.source === source && event.data?.tag === 'document-close-owner-result') {
+ removeEventListener('message', receive);
+ resolve(event.data.result);
+ }
+ }
+ addEventListener('message', receive);
+ });
+ source.postMessage({tag: 'document-close-owner-command', operation: command,
+ self: source === target}, '*');
+ return response;
+ }
+ let opened;
+ if (operation === 'later-close') {
+ opened = await invoke('open');
+ await pause();
+ }
+ const closed = await invoke(operation === 'later-close' ? 'close' : operation);
+ const deadline = performance.now() + 2000;
+ while (target.document.readyState !== 'complete' && performance.now() < deadline) await pause();
+ const expected = ['readystatechange:interactive', 'DOMContentLoaded:interactive',
+ 'readystatechange:complete', 'load:complete'];
+ const facts = {opened, closed, state: target.document.readyState,
+ sameDocument: target.document === original, text: target.document.body?.textContent,
+ events: [...target.__documentCloseOwnerEvents]};
+ return {sourceKind, operation, facts, checks: {
+ completes: facts.state === 'complete',
+ events: JSON.stringify(facts.events) === JSON.stringify(expected),
+ documentRetained: facts.sameDocument && closed.sameDocument,
+ writtenContent: facts.text === 'replacement',
+ openWaitsForClose: !opened || opened.readyState === 'loading'
+ }};
+ } finally {
+ if (frame) frame.remove();
+ else if (source && source !== target) source.close();
+ target.close();
+ delete globalThis.__documentCloseOwnerTarget;
+ }
+}
diff --git a/moli-renderer-v8/src/common_runtime.rs b/moli-renderer-v8/src/common_runtime.rs
index 1f43a0ad1b9..720a912c6d6 100644
--- a/moli-renderer-v8/src/common_runtime.rs
+++ b/moli-renderer-v8/src/common_runtime.rs
@@ -147,7 +147,12 @@ impl CommonRuntimeBinding {
pub(crate) fn from_scope(
scope: &mut v8::PinScope<'_, '_>,
) -> Option<(Rc, RuntimeExecutionContext)> {
- let context = scope.get_current_context();
+ Self::from_context(scope.get_current_context())
+ }
+
+ pub(crate) fn from_context(
+ context: v8::Local<'_, v8::Context>,
+ ) -> Option<(Rc, RuntimeExecutionContext)> {
let binding = context.get_slot::()?;
let (_, owner) = binding.resolve_owner(context)?;
Some((binding, owner))
diff --git a/moli-renderer-v8/src/host/events.rs b/moli-renderer-v8/src/host/events.rs
index fc66eaf04a1..72a9af36c77 100644
--- a/moli-renderer-v8/src/host/events.rs
+++ b/moli-renderer-v8/src/host/events.rs
@@ -504,7 +504,6 @@ pub(crate) fn invoke_prepared_event_callback<'s>(
.schedule_dom_debugger_event_listener_pause_for_target(event_type, target);
invoke_prepared_event_callback_with_receiver(
scope,
- host_ptr,
event_type,
callback_name,
callback,
@@ -514,10 +513,8 @@ pub(crate) fn invoke_prepared_event_callback<'s>(
)
}
-#[allow(clippy::too_many_arguments)]
fn invoke_prepared_event_callback_with_receiver<'s>(
scope: &mut v8::PinScope<'s, '_>,
- host_ptr: *mut PageScriptHost,
event_type: &(impl EventTypeKey + ?Sized),
callback_name: &str,
callback: crate::native_bridge::PreparedEventCallback,
@@ -525,23 +522,11 @@ fn invoke_prepared_event_callback_with_receiver<'s>(
current_event: Option>,
arguments: &[v8::Local<'s, v8::Value>],
) -> Option> {
+ let callback_host = callback.relevant_host();
let relevant_identity = callback.relevant_identity();
- let invocation = CallbackInvocation::new(
- callback.callback(scope),
- receiver,
- callback.relevant_context(scope),
- callback.incumbent_context(scope),
- callback.is_callable(),
- "handleEvent",
- arguments,
- current_event,
- )
- .with_execution_context_currentness(host_ptr, relevant_identity);
- let invocation = if let Some(initiator) = callback.resource_initiator() {
- invocation.with_resource_initiator(initiator.clone())
- } else {
- invocation
- };
+ let invocation = callback
+ .invocation(scope, receiver, arguments, current_event)
+ .with_execution_context_currentness(callback_host, relevant_identity);
CallbackInvoker::invoke_event_and_then(
scope,
"event listener",
@@ -554,7 +539,7 @@ fn invoke_prepared_event_callback_with_receiver<'s>(
CallbackInvocationOutcome::Threw(report) => {
report_event_callback_exception(
scope,
- host_ptr,
+ callback_host,
event_type,
relevant_identity,
None,
@@ -585,19 +570,17 @@ pub(crate) fn invoke_prepared_before_unload_event_handler<'s>(
};
let _dom_debugger_pause = unsafe { &*host_ptr }
.schedule_dom_debugger_event_listener_pause_for_target(event_type, target);
+ let callback_host = callback.relevant_host();
let relevant_identity = callback.relevant_identity();
let arguments = [view.event.into()];
- let invocation = CallbackInvocation::new(
- callback.callback(scope),
- view.receiver,
- callback.relevant_context(scope),
- callback.incumbent_context(scope),
- callback.is_callable(),
- "handleEvent",
- &arguments,
- (!invocation_target_in_shadow_tree).then_some(view.event),
- )
- .with_execution_context_currentness(host_ptr, relevant_identity);
+ let invocation = callback
+ .invocation(
+ scope,
+ view.receiver,
+ &arguments,
+ (!invocation_target_in_shadow_tree).then_some(view.event),
+ )
+ .with_execution_context_currentness(callback_host, relevant_identity);
CallbackInvoker::invoke_event_and_then(
scope,
"event listener",
@@ -640,7 +623,7 @@ pub(crate) fn invoke_prepared_before_unload_event_handler<'s>(
if let Some(report) = conversion_report {
report_event_callback_exception(
scope,
- host_ptr,
+ callback_host,
event_type,
relevant_identity,
None,
@@ -651,7 +634,7 @@ pub(crate) fn invoke_prepared_before_unload_event_handler<'s>(
CallbackInvocationOutcome::Threw(report) => {
report_event_callback_exception(
scope,
- host_ptr,
+ callback_host,
event_type,
relevant_identity,
None,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs
index b156ef3a689..47559a259bd 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -728,18 +728,51 @@ impl PageScriptHost {
.map(RendererDocumentLifecycleJournalHandle::identity)
}
+ pub(super) fn foreign_document_replacement_action_snapshot(
+ &self,
+ scope: &mut v8::PinScope<'_, '_>,
+ ) -> Option {
+ let lifecycle = self.root_document_lifecycle.as_ref()?;
+ let entry_context = scope.get_entered_or_microtask_context();
+ let entry_host = crate::util::context_host_ptr_from_context_slot(entry_context)?;
+ if std::ptr::eq(entry_host, self) {
+ return None;
+ }
+ Some(
+ lifecycle.document_replacement_action_snapshot(
+ self.document_replacement_parser_is_blocked(),
+ ),
+ )
+ }
+
+ pub(super) fn publish_foreign_document_replacement_action(
+ &self,
+ before: Option,
+ ) {
+ if let Some(before) = before
+ && let Some(lifecycle) = &self.root_document_lifecycle
+ {
+ lifecycle.publish_foreign_document_replacement_action(
+ before,
+ self.document_replacement_parser_is_blocked(),
+ );
+ }
+ }
+
pub(crate) fn open_root_document(scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut Self) {
- let (owner, descendant_count_before, document) = {
+ let (owner, descendant_count_before, document, foreign_action) = {
let host = unsafe { &*host_ptr };
(
host.current_main_document_task_owner(),
host.child_browsing_contexts.len(),
host.document_handle(),
+ host.foreign_document_replacement_action_snapshot(scope),
)
};
Self::drop_child_browsing_context_subtree_with_window_realm(scope, host_ptr, document);
if unsafe { &*host_ptr }.current_main_document_task_owner() == owner {
unsafe { &mut *host_ptr }.commit_root_document_open(scope, descendant_count_before);
+ unsafe { &*host_ptr }.publish_foreign_document_replacement_action(foreign_action);
}
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs b/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs
index c171506f9d8..f16a7be37c5 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/event_callbacks.rs
@@ -1,4 +1,5 @@
use super::{PageScriptHost, WindowExecutionContextIdentity, WindowExecutionContextOwner};
+use crate::common_runtime::{CommonRuntimeBinding, RuntimeExecutionContext};
use crate::event_type::EventTypeKey;
use moli_webidl_callback::{PreparedWebIdlCallbackInterface, WebIdlCallbackInterface};
use std::collections::{HashMap, HashSet};
@@ -27,6 +28,7 @@ pub(crate) struct PreparedEventCallback {
kind: EventCallbackKind,
resource_initiator: Option,
relevant_identity: Option,
+ relevant_host: *mut PageScriptHost,
}
pub(crate) struct WindowErrorReportingScope {
@@ -44,6 +46,35 @@ impl Drop for WindowErrorReportingScope {
}
impl PreparedEventCallback {
+ pub(crate) fn invocation<'s, 'a>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ receiver: v8::Local<'s, v8::Value>,
+ arguments: &'a [v8::Local<'s, v8::Value>],
+ current_event: Option>,
+ ) -> crate::callback_invocation::CallbackInvocation<'s, 'a> {
+ let invocation = crate::callback_invocation::CallbackInvocation::new(
+ self.callback(scope),
+ receiver,
+ self.relevant_context(scope),
+ self.incumbent_context(scope),
+ self.is_callable(),
+ "handleEvent",
+ arguments,
+ current_event,
+ );
+ let invocation = if let Some(initiator) = self.resource_initiator() {
+ invocation.with_resource_initiator(initiator.clone())
+ } else {
+ invocation
+ };
+ if self.kind == EventCallbackKind::Handler {
+ invocation.with_legacy_event_handler()
+ } else {
+ invocation
+ }
+ }
+
pub(crate) fn callback<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
@@ -75,6 +106,10 @@ impl PreparedEventCallback {
self.relevant_identity
}
+ pub(crate) fn relevant_host(&self) -> *mut PageScriptHost {
+ self.relevant_host
+ }
+
pub(crate) fn is_callable(&self) -> bool {
self.callback.callable_at_conversion()
}
@@ -112,6 +147,31 @@ impl EventCallbackRegistry {
}
impl PageScriptHost {
+ fn event_callback_host_for_context(
+ &self,
+ context: v8::Local<'_, v8::Context>,
+ ) -> Option<*mut Self> {
+ // Bare V8 test contexts have no renderer binding. An installed but
+ // disconnected binding, however, must never fall back to this target.
+ if context.get_slot::().is_none() {
+ return Some(std::ptr::from_ref(self).cast_mut());
+ }
+ match CommonRuntimeBinding::from_context(context)?.1 {
+ RuntimeExecutionContext::Window(host) => Some(host),
+ RuntimeExecutionContext::Worker => None,
+ }
+ }
+
+ fn event_callback_identity_for_context(
+ &self,
+ scope: &mut v8::PinScope<'_, '_>,
+ context: v8::Local<'_, v8::Context>,
+ ) -> Option {
+ let host_ptr = self.event_callback_host_for_context(context)?;
+ let host = unsafe { &*host_ptr };
+ host.window_execution_context_identity_for_v8_context(scope, context)
+ }
+
pub(crate) fn enter_window_error_reporting_scope(
&mut self,
owner: WindowExecutionContextOwner,
@@ -372,12 +432,20 @@ impl PageScriptHost {
kind: EventCallbackKind,
) -> EventCallbackId {
let relevant_context = callback.relevant_context(scope);
- let relevant_identity =
- self.window_execution_context_identity_for_v8_context(scope, relevant_context);
+ // A stored non-callable handler has no invocation realm. Its value
+ // remains on the target when the object's creation realm retires.
+ let has_callback_realm =
+ kind != EventCallbackKind::Handler || callback.callable_at_conversion();
+ let registration_identity = has_callback_realm
+ .then(|| self.window_execution_context_identity_for_v8_context(scope, relevant_context))
+ .flatten();
+ let relevant_identity = has_callback_realm
+ .then(|| self.event_callback_identity_for_context(scope, relevant_context))
+ .flatten();
#[cfg(test)]
let incumbent_identity = {
let incumbent_context = callback.incumbent_context(scope);
- self.window_execution_context_identity_for_v8_context(scope, incumbent_context)
+ self.event_callback_identity_for_context(scope, incumbent_context)
};
let id = self.event_callbacks.allocate_id();
let previous = self.event_callbacks.records.insert(
@@ -387,7 +455,7 @@ impl PageScriptHost {
kind,
resource_initiator: None,
relevant_identity,
- registration_identity: relevant_identity,
+ registration_identity,
#[cfg(test)]
incumbent_identity,
},
@@ -489,13 +557,19 @@ impl PageScriptHost {
{
return None;
}
+ let relevant_context = record.callback.relevant_context(scope);
+ let relevant_host = self.event_callback_host_for_context(relevant_context)?;
+ if record.relevant_identity.is_some_and(|identity| {
+ !unsafe { &*relevant_host }.window_execution_context_identity_is_current(identity)
+ }) {
+ return None;
+ }
Some(PreparedEventCallback {
callback: record.callback.prepare(scope),
kind: record.kind,
resource_initiator: record.resource_initiator.clone(),
- relevant_identity: record
- .relevant_identity
- .filter(|identity| self.window_execution_context_identity_is_current(*identity)),
+ relevant_identity: record.relevant_identity,
+ relevant_host,
})
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
index c76a8b04de5..05db7e0de87 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
@@ -1180,8 +1180,10 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
) {
+ let foreign_action = self.foreign_document_replacement_action_snapshot(scope);
self.close_root_document_parser_stream(scope, host_ptr);
self.sync_pending_document_style_sources();
+ self.publish_foreign_document_replacement_action(foreign_action);
}
#[cfg(feature = "devtools")]
diff --git a/moli-renderer-v8/src/runtime/document_lifecycle.rs b/moli-renderer-v8/src/runtime/document_lifecycle.rs
index f10a530991e..2b2f0c65d28 100644
--- a/moli-renderer-v8/src/runtime/document_lifecycle.rs
+++ b/moli-renderer-v8/src/runtime/document_lifecycle.rs
@@ -249,6 +249,18 @@ pub(crate) struct RendererDocumentLifecycleDriveAdmission {
pub(crate) to: RendererDocumentLifecycleIdentity,
}
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) struct DocumentReplacementLifecycleActionSnapshot {
+ pub(super) pending_admission: Option,
+ pub(super) ready_admission: Option,
+}
+
+#[derive(Debug)]
+struct ForeignDocumentReplacementAction {
+ before: DocumentReplacementLifecycleActionSnapshot,
+ admission: RendererDocumentLifecycleDriveAdmission,
+}
+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RendererDocumentLifecycleDriveAdmissionState {
Pending(RendererDocumentLifecycleDriveAdmission),
@@ -308,6 +320,8 @@ pub(crate) struct RendererDocumentLifecycleJournal {
next_document_open_start_reason: RendererLifecycleStartReason,
pending_document_open_error: Option,
document_replacement_drive_admission: Option,
+ foreign_document_replacement_action: Option>,
+ owner_wake: Option,
}
#[derive(Clone, Debug)]
@@ -326,6 +340,84 @@ impl RendererDocumentLifecycleJournalHandle {
self.0.borrow().current_snapshot.into()
}
+ pub(crate) fn bind_owner_wake(
+ &self,
+ owner_wake: crate::page_task_queue::RendererOwnerWakeSender,
+ ) {
+ let mut journal = self.0.borrow_mut();
+ if let Some(existing) = &journal.owner_wake {
+ assert_eq!(existing.token(), owner_wake.token());
+ }
+ journal.owner_wake = Some(owner_wake);
+ }
+
+ pub(crate) fn document_replacement_action_snapshot(
+ &self,
+ parser_is_blocked: bool,
+ ) -> DocumentReplacementLifecycleActionSnapshot {
+ let pending_admission = self.pending_document_replacement_drive_admission();
+ DocumentReplacementLifecycleActionSnapshot {
+ pending_admission,
+ ready_admission: pending_admission.filter(|_| !parser_is_blocked),
+ }
+ }
+
+ /// Transfer the exact mutation made by another Page's running script.
+ /// Consecutive open/close calls coalesce at the producing boundary; the
+ /// owner wake merely advertises this retained action, never a rescan.
+ pub(crate) fn publish_foreign_document_replacement_action(
+ &self,
+ before: DocumentReplacementLifecycleActionSnapshot,
+ parser_is_blocked: bool,
+ ) {
+ let after = self.document_replacement_action_snapshot(parser_is_blocked);
+ let Some(admission) = after.pending_admission else {
+ return;
+ };
+ if before == after {
+ return;
+ }
+ let owner_wake = {
+ let mut journal = self.0.borrow_mut();
+ let before = match journal.foreign_document_replacement_action.take() {
+ Some(previous) if before.pending_admission == Some(previous.admission) => {
+ previous.before
+ }
+ _ => before,
+ };
+ journal.foreign_document_replacement_action =
+ Some(Box::new(ForeignDocumentReplacementAction {
+ before,
+ admission,
+ }));
+ journal.owner_wake.clone()
+ };
+ if let Some(owner_wake) = owner_wake {
+ owner_wake.signal_document_lifecycle_turn();
+ }
+ }
+
+ pub(crate) fn has_foreign_document_replacement_action(&self) -> bool {
+ self.0
+ .borrow()
+ .foreign_document_replacement_action
+ .is_some()
+ }
+
+ pub(crate) fn take_foreign_document_replacement_action(
+ &self,
+ ) -> Option {
+ let mut journal = self.0.borrow_mut();
+ let action = journal.foreign_document_replacement_action.take()?;
+ (journal.document_replacement_drive_admission
+ == Some(RendererDocumentLifecycleDriveAdmissionState::Pending(
+ action.admission,
+ ))
+ && journal.identity() == action.admission.to
+ && journal.current_snapshot.terminated.is_none())
+ .then_some(action.before)
+ }
+
pub(crate) fn bind_output_journal(&self, output_journal: super::RendererTurnOutputJournal) {
let mut journal = self.0.borrow_mut();
if let Some(existing) = &journal.output_journal {
@@ -582,6 +674,8 @@ impl RendererDocumentLifecycleJournal {
next_document_open_start_reason: RendererLifecycleStartReason::ExplicitDocumentOpen,
pending_document_open_error: None,
document_replacement_drive_admission: None,
+ foreign_document_replacement_action: None,
+ owner_wake: None,
}
}
@@ -963,6 +1057,7 @@ impl RendererDocumentLifecycleJournal {
}
let document_id = self.next_document_id;
self.next_document_id = document_id.successor();
+ self.foreign_document_replacement_action = None;
let document = RendererDocumentToken::with_id(self.frame.page_id, document_id);
self.start_lifecycle(
document,
@@ -1123,6 +1218,61 @@ mod tests {
RendererDocumentLifecycleJournal::new_initial_at(PageId::new_for_testing(7), 10)
}
+ #[test]
+ fn foreign_replacements_coalesce_before_an_unconsumed_ready_admission() {
+ let journal = RendererDocumentLifecycleJournalHandle(Rc::new(RefCell::new(journal())));
+ let (wake_tx, mut wake_rx) = tokio::sync::mpsc::unbounded_channel();
+ let token = super::super::RendererPageToken::new_for_testing(PageId::new_for_testing(7));
+ journal.bind_owner_wake(crate::page_task_queue::RendererOwnerWakeSender::new(
+ wake_tx, token,
+ ));
+ let initial = journal.document_replacement_action_snapshot(false);
+ for _ in 0..2 {
+ let before_open = journal.document_replacement_action_snapshot(false);
+ journal.did_open_document();
+ journal.publish_foreign_document_replacement_action(before_open, true);
+ let before_close = journal.document_replacement_action_snapshot(true);
+ journal.publish_foreign_document_replacement_action(before_close, false);
+ }
+ assert!(matches!(
+ wake_rx.try_recv().unwrap(),
+ crate::page_task_queue::RendererOwnerWake::Page {
+ token: actual,
+ source: crate::page_task_queue::RendererOwnerWakeSource::Runtime(
+ super::super::RendererOwnerRuntimeActivitySource::DocumentLifecycleTurn,
+ ),
+ } if actual == token
+ ));
+ assert_eq!(
+ journal.take_foreign_document_replacement_action(),
+ Some(initial)
+ );
+ assert!(journal.take_foreign_document_replacement_action().is_none());
+ assert_eq!(journal.identity().epoch, RendererLifecycleEpoch(3));
+ }
+
+ #[test]
+ fn foreign_replacement_cannot_consume_a_later_local_admission() {
+ let journal = RendererDocumentLifecycleJournalHandle(Rc::new(RefCell::new(journal())));
+ let before = journal.document_replacement_action_snapshot(false);
+ journal.did_open_document();
+ journal.publish_foreign_document_replacement_action(before, false);
+ let first = journal
+ .pending_document_replacement_drive_admission()
+ .unwrap();
+ assert!(journal.activate_document_replacement_drive_admission(first));
+ journal.did_open_document();
+ let second = journal
+ .pending_document_replacement_drive_admission()
+ .unwrap();
+ assert_ne!(first, second);
+ assert!(journal.take_foreign_document_replacement_action().is_none());
+ assert_eq!(
+ journal.pending_document_replacement_drive_admission(),
+ Some(second)
+ );
+ }
+
#[test]
#[should_panic(expected = "renderer lifecycle Document id overflow")]
fn lifecycle_document_id_allocator_rejects_overflow() {
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index 46b79a9d344..7e5af8ea6e3 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -312,8 +312,8 @@ pub use self::browser_context_runtime::{
RendererServiceWorkerMainResourceFetch,
};
pub(crate) use self::document_lifecycle::{
- RendererDocumentLifecycleDriveAdmission, RendererDocumentLifecycleJournalHandle,
- RendererDocumentLifecycleTransition,
+ DocumentReplacementLifecycleActionSnapshot, RendererDocumentLifecycleDriveAdmission,
+ RendererDocumentLifecycleJournalHandle, RendererDocumentLifecycleTransition,
};
pub use self::document_lifecycle::{
RendererDocumentLifecycleEvent, RendererDocumentLifecycleEventKind,
diff --git a/moli-renderer-v8/src/runtime/owner_local_store/bound.rs b/moli-renderer-v8/src/runtime/owner_local_store/bound.rs
index 8176c6a1d7f..9d9fe2f195a 100644
--- a/moli-renderer-v8/src/runtime/owner_local_store/bound.rs
+++ b/moli-renderer-v8/src/runtime/owner_local_store/bound.rs
@@ -874,6 +874,13 @@ pub(super) fn select_page_scheduler_turn(
document_lifecycle_owner_turn_is_runnable,
has_ready_main_parser_script_continuation,
);
+ if entry
+ .page_vm()
+ .document_lifecycle
+ .has_foreign_document_replacement_action()
+ {
+ document_lifecycle = DocumentLifecycleClassReadiness::ReadyReplacementAction;
+ }
let has_lifecycle_dom_task = task_sources.has_queued_document_lifecycle_dom_task(|owner| {
entry
.page_vm()
@@ -882,7 +889,8 @@ pub(super) fn select_page_scheduler_turn(
if has_lifecycle_dom_task
&& !matches!(
document_lifecycle,
- DocumentLifecycleClassReadiness::RunnableContinuation
+ DocumentLifecycleClassReadiness::ReadyReplacementAction
+ | DocumentLifecycleClassReadiness::RunnableContinuation
| DocumentLifecycleClassReadiness::ReadyMainParserScriptContinuation
)
{
@@ -1019,15 +1027,27 @@ pub(in crate::runtime) async fn advance_page_owner_one_turn_via_local_task(
.await
}
-/// Execute at most one action from the exact-Document lifecycle resident.
-/// A missing resident is an idle stale-wake outcome; this helper never binds
-/// a page wake to whichever Document happens to be current.
+/// Execute one retained foreign replacement action or one exact-Document
+/// lifecycle continuation. A wake alone cannot install a new resident.
pub(in crate::runtime) async fn advance_document_lifecycle_one_page_turn_via_local_task(
local_executor: JsLocalExecutor,
entry: LivePageEntry,
) -> (LivePageEntry, Result) {
run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {
Box::pin(async move {
+ if let Some(snapshot) = entry
+ .page_vm()
+ .document_lifecycle
+ .take_foreign_document_replacement_action()
+ {
+ let (page_vm, pending) = entry.page_vm_and_document_lifecycle_turn_mut();
+ return Ok(page_vm
+ .reconcile_document_replacement_lifecycle_after_owner_action(snapshot, pending)
+ .await?
+ .unwrap_or_else(|| {
+ DocumentLifecycleTurnOutcome::idle(DocumentLifecycleTurnAction::None)
+ }));
+ }
let Some(document) = entry.pending_document_lifecycle_identity() else {
return Ok(DocumentLifecycleTurnOutcome::idle(
DocumentLifecycleTurnAction::None,
diff --git a/moli-renderer-v8/src/runtime/page_turn_scheduler.rs b/moli-renderer-v8/src/runtime/page_turn_scheduler.rs
index 64b8ea70be6..c7fc4766a9b 100644
--- a/moli-renderer-v8/src/runtime/page_turn_scheduler.rs
+++ b/moli-renderer-v8/src/runtime/page_turn_scheduler.rs
@@ -77,6 +77,8 @@ pub(super) enum DocumentLifecycleClassReadiness {
/// The DOM source owns the admitted event. Only its FIFO head may run.
QueuedDomTask,
Available,
+ /// Another Page produced an exact replacement action for this owner.
+ ReadyReplacementAction,
RunnableContinuation,
ReadyMainParserScriptContinuation,
}
@@ -223,7 +225,8 @@ impl PageTurnScheduler {
) -> Option {
if matches!(
document_lifecycle,
- DocumentLifecycleClassReadiness::RunnableContinuation
+ DocumentLifecycleClassReadiness::ReadyReplacementAction
+ | DocumentLifecycleClassReadiness::RunnableContinuation
| DocumentLifecycleClassReadiness::ReadyMainParserScriptContinuation
) {
return Some(self.record_selected_turn_class(PageTurnClass::DocumentLifecycle));
@@ -275,7 +278,8 @@ impl PageTurnScheduler {
) -> Option {
let selected = if matches!(
document_lifecycle,
- DocumentLifecycleClassReadiness::RunnableContinuation
+ DocumentLifecycleClassReadiness::ReadyReplacementAction
+ | DocumentLifecycleClassReadiness::RunnableContinuation
| DocumentLifecycleClassReadiness::ReadyMainParserScriptContinuation
) {
PageTurnClass::DocumentLifecycle
diff --git a/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs b/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs
index 25370a4ae31..9b22183389e 100644
--- a/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/document_lifecycle_turn.rs
@@ -12,7 +12,10 @@ use anyhow::Result;
use crate::PageVmInitStage;
use crate::local_executor::is_on_named_owner_execution_lane_for;
use crate::page_task_queue::PostParsePageOwnedWork;
-use crate::runtime::{RendererDocumentLifecycleIdentity, RendererDocumentLifecycleWaitOutcome};
+use crate::runtime::{
+ DocumentReplacementLifecycleActionSnapshot, RendererDocumentLifecycleIdentity,
+ RendererDocumentLifecycleWaitOutcome,
+};
use crate::script_vm::PostParseLifecycleAdvance;
use super::super::document_lifecycle_turn::{
@@ -20,12 +23,6 @@ use super::super::document_lifecycle_turn::{
};
use super::{PageVm, renderer_document_lifecycle_milestone_for_stage};
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(in crate::runtime) struct DocumentReplacementLifecycleActionSnapshot {
- pending_admission: Option,
- ready_admission: Option,
-}
-
impl PageVm {
pub(in crate::runtime) fn ready_document_replacement_lifecycle_admission(
&self,
@@ -43,12 +40,12 @@ impl PageVm {
pub(in crate::runtime) fn document_replacement_lifecycle_action_snapshot(
&self,
) -> DocumentReplacementLifecycleActionSnapshot {
- DocumentReplacementLifecycleActionSnapshot {
- pending_admission: self
- .document_lifecycle
- .pending_document_replacement_drive_admission(),
- ready_admission: self.ready_document_replacement_lifecycle_admission(),
- }
+ self.document_lifecycle
+ .document_replacement_action_snapshot(
+ self.vm()
+ .document_runtime
+ .document_replacement_parser_is_blocked(),
+ )
}
pub(in crate::runtime) fn has_blocked_document_replacement_lifecycle_admission(
diff --git a/moli-renderer-v8/src/runtime/page_vm/javascript_navigation_lifecycle.rs b/moli-renderer-v8/src/runtime/page_vm/javascript_navigation_lifecycle.rs
index 1a4640adc90..2ccb2c1d138 100644
--- a/moli-renderer-v8/src/runtime/page_vm/javascript_navigation_lifecycle.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/javascript_navigation_lifecycle.rs
@@ -23,8 +23,8 @@ use super::super::document_lifecycle_turn::{
DocumentLifecycleNavigationTiming, DocumentLifecycleTurnAction, DocumentLifecycleTurnOutcome,
PendingDocumentLifecycleTurn,
};
-use super::document_lifecycle_turn::DocumentReplacementLifecycleActionSnapshot;
use super::{PageVm, renderer_document_lifecycle_milestone_for_stage};
+use crate::runtime::DocumentReplacementLifecycleActionSnapshot;
/// The durable lifecycle fact left after one `javascript:` URL finishes.
///
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index fd270c7f489..6d8cacba407 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -1529,6 +1529,9 @@ impl PageVmRuntimeHooks {
);
self.document_lifecycle = Some(journal.clone());
self.document_lifecycle_install = PageVmDocumentLifecycleInstall::ReuseOrCreateInitial;
+ if let Some(owner_wake) = self.owner_wake() {
+ journal.bind_owner_wake(owner_wake);
+ }
Ok((journal, identity))
}