fix(runtime): complete document replacements across Page owners

Retain the exact open/close action made by another Page and wake its lifecycle owner. Coalesce consecutive replacements without letting an unrelated action consume an older admission.

Resolve event callbacks through their own Context runtime binding so lifecycle listeners from other Page hosts are invoked and report exceptions in the correct Window.

Cover real HTTP popup replacement from root, iframe, popup and self, later close and repeated open/close, plus stale admission and coalescing authority.

Validation: cargo fmt --all; full workspace all-targets/all-features clippy -D warnings; cargo nextest run --no-fail-fast (22,989 passed, 17 existing skips, 32 threads, zero retries).
This commit is contained in:
ldm0
2026-11-21 20:03:36 +08:00
parent a57d612f65
commit 97235c59f8
15 changed files with 481 additions and 64 deletions
@@ -4,6 +4,7 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
};
mod document_close;
mod document_open;
mod history_traversal;
mod lifecycle;
@@ -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 = "<!doctype html><script src='/document-close-owner.js'></script><script>installDocumentCloseSource();</script>";
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("<!doctype html><body>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;
}
+97
View File
@@ -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('<!doctype html><body>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;
}
}
+6 -1
View File
@@ -147,7 +147,12 @@ impl CommonRuntimeBinding {
pub(crate) fn from_scope(
scope: &mut v8::PinScope<'_, '_>,
) -> Option<(Rc<Self>, 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<Self>, RuntimeExecutionContext)> {
let binding = context.get_slot::<Self>()?;
let (_, owner) = binding.resolve_owner(context)?;
Some((binding, owner))
+16 -33
View File
@@ -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<v8::Local<'s, v8::Object>>,
arguments: &[v8::Local<'s, v8::Value>],
) -> Option<v8::Global<v8::Value>> {
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,
@@ -728,18 +728,51 @@ impl PageScriptHost {
.map(RendererDocumentLifecycleJournalHandle::identity)
}
pub(super) fn foreign_document_replacement_action_snapshot(
&self,
scope: &mut v8::PinScope<'_, '_>,
) -> Option<crate::runtime::DocumentReplacementLifecycleActionSnapshot> {
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<crate::runtime::DocumentReplacementLifecycleActionSnapshot>,
) {
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);
}
}
@@ -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<crate::resource_initiator::CallbackInitiator>,
relevant_identity: Option<WindowExecutionContextIdentity>,
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<v8::Local<'s, v8::Object>>,
) -> 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::<CommonRuntimeBinding>().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<WindowExecutionContextIdentity> {
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,
})
}
@@ -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")]
@@ -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<RendererDocumentLifecycleDriveAdmission>,
pub(super) ready_admission: Option<RendererDocumentLifecycleDriveAdmission>,
}
#[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<RendererDocumentLifecycleTransition>,
document_replacement_drive_admission: Option<RendererDocumentLifecycleDriveAdmissionState>,
foreign_document_replacement_action: Option<Box<ForeignDocumentReplacementAction>>,
owner_wake: Option<crate::page_task_queue::RendererOwnerWakeSender>,
}
#[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<DocumentReplacementLifecycleActionSnapshot> {
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() {
+2 -2
View File
@@ -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,
@@ -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<DocumentLifecycleTurnOutcome>) {
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,
@@ -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<Entry> PageTurnScheduler<Entry> {
) -> Option<PageTurnClass> {
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<Entry> PageTurnScheduler<Entry> {
) -> Option<PageTurnClass> {
let selected = if matches!(
document_lifecycle,
DocumentLifecycleClassReadiness::RunnableContinuation
DocumentLifecycleClassReadiness::ReadyReplacementAction
| DocumentLifecycleClassReadiness::RunnableContinuation
| DocumentLifecycleClassReadiness::ReadyMainParserScriptContinuation
) {
PageTurnClass::DocumentLifecycle
@@ -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<crate::runtime::RendererDocumentLifecycleDriveAdmission>,
ready_admission: Option<crate::runtime::RendererDocumentLifecycleDriveAdmission>,
}
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(
@@ -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.
///
@@ -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))
}