fix(history): preserve traversal settlement and owner-scoped cancellation

This commit is contained in:
ldm0
2026-11-22 02:01:54 +08:00
parent 6a0cb4a177
commit 5f8dafebfa
12 changed files with 103 additions and 40 deletions
@@ -539,7 +539,9 @@ async fn assert_joint_history_precommit(mode: &str) {
"resolve" | "attach" => (json!(["top0", "a0", "/a0", 4, 4, 1]), 1, 4),
"attach-single" => (json!(["top0", "a1", "/a1", 4, 4, 0]), 2, 4),
"reject" => (json!(["top1", "a1", "/a1", 4, 4, 0]), 3, 4),
"stop-pagehide" => (json!(["top1", "a1", "/a1", 4, 4, 1]), 3, 4),
// pagehide runs at document commit, after admission has completed.
// Chromium also completes this traversal when pagehide calls stop().
"stop-pagehide" => (json!(["top0", "a0", "/a0", 4, 4, 1]), 1, 4),
"replace-participant" => (json!(["top1", null, "/successor", 5, 5, 1]), 4, 5),
_ => (json!(["top1", "a1", "/a1", 1, 1, 0]), 0, 1),
};
@@ -259,7 +259,7 @@ async fn joint_history_traversal_precommit_rejection_aborts_the_whole_step() {
}
#[tokio::test(flavor = "multi_thread")]
async fn joint_history_traversal_stop_during_pagehide_cancels_after_precommit() {
async fn joint_history_traversal_stop_during_pagehide_preserves_accepted_commit() {
assert_joint_history_precommit("stop-pagehide").await;
}
@@ -184,6 +184,7 @@ fn stop_navigation_for_window<'s>(
pub(crate) enum NavigationCancellationReason {
WindowStop,
WindowClose,
/// Native retirement has already invalidated and extracted traversal
/// admissions; their JS settlement belongs to the owning ScriptVm.
LocalWindowRetirement,
@@ -200,7 +201,10 @@ pub(crate) fn inform_about_canceled_navigation_for_window<'s>(
let _ = cancel_active_navigation_event(scope, navigation);
cancel_active_intercepted_same_document_navigation(scope, navigation);
cancel_active_cross_document_navigation(scope, navigation, None);
if matches!(reason, NavigationCancellationReason::WindowStop) {
if matches!(
reason,
NavigationCancellationReason::WindowStop | NavigationCancellationReason::WindowClose
) {
cancel_pending_precommit_history_traversal(scope, navigation);
}
cancel_pending_precommit_same_document_navigation(scope, navigation);
@@ -223,7 +227,7 @@ pub(super) fn clear_pending_cross_document_navigation_for_window<'s>(
host.child_browsing_context_has_pending_cross_document_traversal(handle)
}
Some(OwnerDispatchScope::LightweightPopup(popup_id)) => {
host.lightweight_popup_has_pending_cross_document_traversal(popup_id)
host.lightweight_popup_has_pending_history_traversal(popup_id)
}
_ => false,
}
@@ -30,7 +30,6 @@ use super::navigation_window::{
navigation_document_has_disabled_entries, navigation_document_is_active,
should_dispatch_hash_change, window_location_for_holder, window_navigation_for_holder,
};
use super::*;
use crate::script_cleanup::ScriptExecutionScope;
#[allow(clippy::too_many_arguments)]
@@ -214,10 +213,8 @@ fn finish_cross_document_navigation_error<'s>(
let committed_resolver = transition_resolver
.filter(|resolver| navigation_transition_matches_resolver(scope, navigation, *resolver))
.and_then(|_| take_navigation_transition_committed_resolver(scope, navigation));
if let Some(signal) = outcome.signal
&& let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
{
unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);
if let Some(signal) = outcome.signal {
crate::native_bridge::abort::abort_signal(scope, signal, error);
}
finish_navigation_error_events(scope, navigation, error, href);
if let Some(resolver) = committed_resolver {
@@ -398,18 +398,15 @@ pub(super) fn cancel_active_cross_document_navigation<'s>(
);
clear_active_cross_document_navigation(scope, navigation);
let owner = super::navigation_window::runtime_window_owner(scope, navigation);
// Retire only this Window's load before abort listeners can start a successor.
super::navigation_cancellation::clear_pending_cross_document_navigation_for_window(
scope, owner,
);
let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
// Remove the old load before abort listeners can start a successor.
unsafe { &mut *host_ptr }.clear_pending_location_navigation();
if let Some(signal) = get_private_value(scope, data, CROSS_DOCUMENT_PENDING_SIGNAL_SLOT)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
{
crate::native_bridge::abort::abort_signal(scope, signal, error);
}
if let Some(signal) = get_private_value(scope, data, CROSS_DOCUMENT_PENDING_SIGNAL_SLOT)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
{
crate::native_bridge::abort::abort_signal(scope, signal, error);
}
finish_navigation_error_events(scope, navigation, error, &href);
let receiver = v8::undefined(scope).into();
@@ -119,8 +119,31 @@ pub(super) fn execute<'s>(
scope: &mut v8::PinScope<'s, '_>,
plan: JointTraversalPlan<'s>,
initiator_info: Option<v8::Local<'s, v8::Value>>,
results: Vec<PendingNavigationResult>,
mut results: Vec<PendingNavigationResult>,
) {
let mut upcoming_info = None;
if results.is_empty()
&& let Some(target) = plan
.targets
.iter()
.find(|target| target.owner.strict_equals(plan.owner.into()))
&& let Some(entry) = entry_reference(scope, target.history, target.target_index)
&& let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
{
let host = unsafe { &mut *host_ptr };
if let Some(target) = window_task_target_for_runtime_owner(scope, host, target.owner)
&& let Some((info, upcoming)) =
host.take_upcoming_history_traversal_tracker(target, entry.key.as_str())
{
upcoming_info = info;
results = upcoming;
}
}
let initiator_info = initiator_info.or_else(|| {
upcoming_info
.as_ref()
.map(|info| v8::Local::new(scope, info))
});
let captured = capture_participants(scope, &plan).and_then(|participants| {
let host = unsafe { &*context_host_ptr_from_global_bridge(scope)? };
let owner = window_task_target_for_runtime_owner(scope, host, plan.owner)?.owner();
@@ -587,9 +610,14 @@ fn commit(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalA
let applied = prepared
.into_iter()
.map(|(index, entry)| {
let kind = if admission.participants[index].outcome.intercepted {
"other"
} else {
"fragment"
};
(
index,
apply::commit_prepared_history_entry(scope, entry, Some("other")),
apply::commit_prepared_history_entry(scope, entry, Some(kind)),
)
})
.collect::<Vec<_>>();
@@ -31,8 +31,9 @@ pub(super) fn apply_entry(
reject_canceled_history_traversal_results(scope, &traversal.results);
return;
};
// An earlier traversal may have committed this entry after the API call
// selected it. This queued method never starts a navigation of its own.
// Trackers registered before an earlier traversal's navigate event are
// adopted by that traversal. A reentrant call registered during the event
// remains upcoming, and rejects if its queued task finds the entry active.
if !traversal.results.is_empty()
&& let Some(key) = traversal.target_key.as_deref()
&& navigation_current_entry(scope, owner)
@@ -44,7 +45,11 @@ pub(super) fn apply_entry(
"The traversal target is already the active history entry",
"InvalidStateError",
);
super::history_runtime::reject_pending_navigation_results(scope, &traversal.results, error);
super::history_runtime::results::reject_pending_navigation_results(
scope,
&traversal.results,
error,
);
return;
}
let step = traversal.joint_step.or_else(|| {
@@ -136,17 +136,6 @@ impl RendererSessionHistories {
Some((step, delta))
}
pub(crate) fn is_pending_traversal_entry(
&self,
popup: Option<u64>,
context: SessionHistoryContextId,
key: &NavigationHistoryEntryKey,
) -> bool {
self.pending
.get(&popup)
.is_some_and(|pending| pending.remaining.get(&context) == Some(key))
}
pub(crate) fn cancel_traversal_step(
&mut self,
popup: Option<u64>,
@@ -730,6 +730,32 @@ impl PageScriptHost {
.take_pending_navigation_finished_results_for_navigation(scope, navigation)
}
/// Promote the upcoming Navigation API tracker before a classic History
/// traversal dispatches navigate. Calls made by that event's listeners
/// register a new tracker and must not join the ongoing navigation.
pub(crate) fn take_upcoming_history_traversal_tracker(
&mut self,
target: WindowTaskTarget,
key: &str,
) -> Option<(Option<v8::Global<v8::Value>>, Vec<PendingNavigationResult>)> {
let queue = &mut self.history_queue;
for queued in queue.pending_history_traversal_tasks.iter_mut().chain(
queue
.deferred_traversals
.iter_mut()
.map(|(_, queued)| queued),
) {
if let PendingHistoryTraversalAction::SameDocument(pending) = &mut queued.action
&& pending.target == target
&& pending.target_key.as_deref() == Some(key)
&& !pending.results.is_empty()
{
return Some((pending.info.take(), std::mem::take(&mut pending.results)));
}
}
None
}
pub(crate) fn queue_history_traversal_with_result<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
@@ -756,13 +782,14 @@ impl PageScriptHost {
)
.find_map(|queued| match &queued.action {
PendingHistoryTraversalAction::SameDocument(pending)
if pending.target == target && pending.target_key == target_key =>
if pending.target == target
&& pending.target_key == target_key
&& !pending.results.is_empty() =>
{
Some(pending)
}
_ => None,
})
&& !pending.results.is_empty()
{
// Upcoming calls for one key share the original method tracker,
// including its info, even while an earlier traversal blocks it.
@@ -2,7 +2,9 @@ use anyhow::Result;
use super::ScriptVm;
use crate::{
context_bootstrap::inform_about_canceled_navigation_for_window,
context_bootstrap::{
NavigationCancellationReason, inform_about_canceled_navigation_for_window,
},
native_bridge::OwnerDispatchScope,
page_task_queue::RendererPagePopupCloseOwner,
runtime::{AuthorizedCurrentPagePopupClose, RendererDocumentToken},
@@ -45,7 +47,11 @@ impl ScriptVm {
if let (Some(binding), Some(window)) = (binding, window) {
binding.with_current_scope(scope, host_ptr, |scope, _| {
let window = v8::Local::new(scope, &window);
inform_about_canceled_navigation_for_window(scope, window);
inform_about_canceled_navigation_for_window(
scope,
window,
NavigationCancellationReason::WindowClose,
);
unsafe { &mut *host_ptr }
.dispatch_lightweight_popup_document_unload(scope, popup_id);
});
@@ -726,9 +726,12 @@ async fn repeated_traverse_to_reuses_promises_after_history_request() {
const key = navigation.currentEntry.key;
history.pushState(null, "", "#2");
history.back();
const first = navigation.traverseTo(key);
const second = navigation.traverseTo(key);
const first = navigation.traverseTo(key, { info: "first" });
const second = navigation.traverseTo(key, { info: "second" });
globalThis.__lmRepeatedAfterHistory = [];
navigation.addEventListener("navigate", event => {
__lmRepeatedAfterHistory.push(`info:${event.info}`);
});
for (const [label, result] of [["first", first], ["second", second]]) {
result.finished.then(
entry => __lmRepeatedAfterHistory.push(`${label}:${new URL(entry.url).hash}`),
@@ -753,7 +756,7 @@ async fn repeated_traverse_to_reuses_promises_after_history_request() {
assert_eq!(
vm.eval("[location.hash, ...__lmRepeatedAfterHistory].join('|')")
.expect("both callers should finish at their shared destination"),
"#1|first:#1|second:#1"
"#1|info:first|first:#1|second:#1"
);
assert!(
!vm.run_one_history_traversal_executor_turn(&loader)
@@ -65,6 +65,9 @@ async fn history_traversal_retirement_reentry_preserves_reattached_frame_and_sib
const container = document.body || document.documentElement || document;
container.appendChild(frame); container.appendChild(sibling);
globalThis.oldChild = frame.contentWindow;
// Initial about:blank forces pushState to replace; use a real document
// so both Windows participate in the traversal being retired.
oldChild.document.open(); oldChild.document.write('<body>child'); oldChild.document.close();
history.replaceState(0, ''); oldChild.history.replaceState(0, '');
history.pushState(1, ''); oldChild.history.pushState(1, '');
globalThis.log = [];
@@ -137,6 +140,7 @@ async fn history_traversal_retirement_error_can_start_successor_admission() {
r#"
globalThis.frame = document.createElement('iframe');
(document.body || document.documentElement || document).appendChild(frame);
frame.contentDocument.open(); frame.contentDocument.write('<body>child'); frame.contentDocument.close();
history.replaceState(0, ''); frame.contentWindow.history.replaceState(0, '');
history.pushState(1, ''); frame.contentWindow.history.pushState(1, '');
globalThis.gates = []; globalThis.log = [];
@@ -306,6 +310,7 @@ async fn history_traversal_detach_releases_pending_admission_and_ignores_late_ca
globalThis.frame = document.createElement('iframe');
(document.body || document.documentElement || document).appendChild(frame);
globalThis.child = frame.contentWindow;
child.document.open(); child.document.write('<body>child'); child.document.close();
"#,
)
.unwrap();