diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 29b86ae4a61..51af6b619f0 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -127,12 +127,14 @@ mod shared_event_targets; pub(crate) use shared_event_targets::resolve_event_target; #[cfg(test)] pub(crate) use shared_event_targets::{bind_dispatch_target, bind_shared_target}; +mod session_history_traversal; mod world_wrappers; #[cfg(test)] pub(crate) use navigator_runtime::{ materialized_navigator_subobject_keys, navigator_storage_wrapper_diagnostics, }; pub(crate) use session_history::prune_joint_session_history; +pub(crate) use session_history_traversal::finish_without_document_commit as finish_joint_history_without_document_commit; mod notification_runtime; mod observer_template; mod opfs; diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs index fc8fc4c366e..d3cc006d143 100644 --- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs +++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs @@ -78,6 +78,12 @@ pub(crate) fn update_history_for_document_open<'s>( let _ = entries.set_index(scope, index, entry.into()); set_history_entries(scope, history, entries); sync_navigation_current_entry_from_history_entry(scope, window, entry); + super::session_history::commit( + scope, + window, + entry, + moli_page_types::SessionHistoryCommit::Replace, + ); sync_navigation_entry_seed_from_owner(scope, window); if let Some(navigation) = window_navigation_for_holder(scope, window) { dispatch_navigation_currententrychange(scope, navigation, Some(previous), Some("replace")); diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs index 849778f8ae6..f8c64bf6326 100644 --- a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs +++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs @@ -115,6 +115,15 @@ pub(in crate::context_bootstrap) fn commit_prepared_history_entry<'s>( applied } +pub(in crate::context_bootstrap) fn finish_history_entry_commit<'s>( + scope: &mut v8::PinScope<'s, '_>, + applied: &AppliedHistoryEntry<'s>, +) { + let key = + super::super::session_history::entry_reference(scope, applied.entry).map(|entry| entry.key); + super::super::session_history_traversal::finish_entry(scope, applied.owner, key.as_ref()); +} + pub(in crate::context_bootstrap) fn dispatch_history_entry_currententrychange<'s>( scope: &mut v8::PinScope<'s, '_>, applied: &AppliedHistoryEntry<'s>, diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs index aba74e4fbe3..eab78739a2b 100644 --- a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs +++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs @@ -137,6 +137,7 @@ pub(in crate::context_bootstrap) fn route_history_traversal_task( return; }; let results = match &queued.action { + crate::native_bridge::PendingHistoryTraversalAction::ByDelta { .. } => &[], crate::native_bridge::PendingHistoryTraversalAction::SameDocument(traversal) => { traversal.results.as_slice() } @@ -155,7 +156,7 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal( scope: &mut v8::PinScope<'_, '_>, host: &mut PageScriptHost, traversal: PendingHistoryTraversal, -) { +) -> bool { let plan = history_traversal_target_window(scope, host, traversal.target).and_then(|owner| { // A joint traversal is identified by its stable step. queue_plan uses // the initiating realm's current entry only as an admission anchor; @@ -182,13 +183,14 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal( let Some(plan) = plan else { let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError"); reject_pending_navigation_results(scope, &traversal.results, error); - return; + return false; }; let info = traversal .info .as_ref() .map(|value| v8::Local::new(scope, value)); super::super::navigation_traversal_coordinator::execute(scope, plan, info, traversal.results); + true } pub(in crate::context_bootstrap) fn prepare_history_participant<'s>( @@ -271,11 +273,10 @@ pub(in crate::context_bootstrap) fn finish_history_participant<'s>( return; }; let (error, result) = if outcome.intercepted { - if let Some(event) = outcome.precommit_event { - run_navigation_precommit_deferred_handlers(scope, event) - } else { - (outcome.intercept_error, outcome.intercept_result) - } + outcome.precommit_event.map_or( + (outcome.intercept_error, outcome.intercept_result), + |event| run_navigation_precommit_deferred_handlers(scope, event), + ) } else { (None, None) }; diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs index 059fa39b1d8..6bc41ea19e9 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs @@ -33,8 +33,8 @@ use super::navigation_result::{ }; use super::navigation_traversal_execution::queue_navigation_traversal_with_result; use super::navigation_traversal_plan::{ - NavigationTraversalPlan, history_delta_traversal_plan, navigation_delta_traversal_plan, - navigation_index_traversal_plan, + HistoryDeltaTraversalPlan, NavigationTraversalPlan, history_delta_traversal_target, + navigation_delta_traversal_plan, navigation_index_traversal_plan, }; use super::navigation_window::{ navigation_can_update_current_entry, navigation_document_is_active, @@ -540,64 +540,7 @@ fn history_traverse<'s>( history: v8::Local<'s, v8::Object>, delta: i64, ) { - let Some(plan) = history_delta_traversal_plan(scope, history, delta) else { - queue_browser_owned_top_level_history_traversal(scope, history, delta); - return; - }; - let source_owner = runtime_window_owner(scope, history); - if let Some(source_handle) = - super::navigation_window::child_browsing_context_handle_for_runtime_owner( - scope, - source_owner, - ) - && plan.targets.iter().any(|target| { - super::location_navigation::sandbox_blocks_ancestor_or_top_navigation_from_source( - scope, - source_handle, - target.owner, - ) - }) - { - return; - } - super::navigation_traversal_coordinator::queue_plan(scope, plan); -} - -fn queue_browser_owned_top_level_history_traversal<'s>( - scope: &mut v8::PinScope<'s, '_>, - history: v8::Local<'s, v8::Object>, - delta: i64, -) { - let owner = runtime_window_owner(scope, history); - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { - return; - }; - let host = unsafe { &mut *host_ptr }; - let binding = super::session_history::binding(scope, host, owner); - if binding.popup.is_some() { - return; - } - // Failure to project a browser-owned entry and an out-of-range delta - // both reach this fallback. Only the former may supersede a navigation. - let model = host.session_histories.get_mut(binding.popup).clone(); - let source = host - .pending_joint_history_step(&model) - .unwrap_or_else(|| model.current_step()); - if model.step_by_delta_from(source, delta).is_none() { - return; - } - let top_owner = super::navigation_window::runtime_top_window_owner(scope, owner); - if let Some(source_handle) = - super::navigation_window::child_browsing_context_handle_for_runtime_owner(scope, owner) - && super::location_navigation::sandbox_blocks_ancestor_or_top_navigation_from_source( - scope, - source_handle, - top_owner, - ) - { - return; - } - host.record_pending_top_level_history_traversal(delta); + super::navigation_traversal_execution::queue_history_traversal_by_delta(scope, history, delta); } pub(crate) fn queue_top_level_history_traversal_by_delta( @@ -608,13 +551,15 @@ pub(crate) fn queue_top_level_history_traversal_by_delta( let Some(history) = window_history_for_holder(scope, global) else { return false; }; - let Some(plan) = history_delta_traversal_plan(scope, history, delta) else { + let Some(HistoryDeltaTraversalPlan::Traverse(plan)) = + history_delta_traversal_target(scope, history, delta, None) + else { return false; }; if plan.has_cross_document_root(scope) { return false; } - super::navigation_traversal_coordinator::queue_plan(scope, plan); + history_traverse(scope, history, delta); true } diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs index 3c97cbb66d1..f343ae9f185 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs @@ -5,21 +5,19 @@ use super::navigation_activation::{ navigation_transition_matches_resolver, precommit_transition_resolver_from_event, take_navigation_transition_committed_resolver, }; -use super::navigation_entry::{history_entries, history_index, navigation_current_entry}; +use super::navigation_entry::{history_entries, navigation_current_entry}; use super::navigation_events::{ NavigationDispatchOutcome, dispatch_beforeunload_for_runtime_owner, dispatch_navigation_traverse_event_with_outcome, }; use super::navigation_result::navigation_dom_exception; use super::navigation_seed::history_entry_seed_for_traversal; -use super::navigation_traversal_execution::{ - TraversalTarget, queue_history_traversal_without_result, -}; +use super::navigation_traversal_execution::TraversalTarget; use super::navigation_traversal_plan::JointTraversalPlan; use super::navigation_window::{ child_browsing_context_handle_for_runtime_owner, navigation_document_has_opaque_origin, - navigation_document_is_active, window_history_for_holder, window_location_for_holder, - window_navigation_for_holder, window_task_target_for_runtime_owner, + navigation_document_is_active, window_location_for_holder, window_navigation_for_holder, + window_task_target_for_runtime_owner, }; use crate::document_runtime::DomHandle; use crate::native_bridge::history_traversal::{ @@ -30,28 +28,6 @@ use crate::native_bridge::{NavigationHistoryEntrySeed, PendingNavigationResult}; use crate::util::context_host_ptr_from_global_bridge; use moli_session_history::SessionHistoryEntry; -pub(super) fn queue_plan<'s>(scope: &mut v8::PinScope<'s, '_>, mut plan: JointTraversalPlan<'s>) { - // Root Document replacement belongs to the browser/popup loader. - if let Some(index) = plan.cross_document_root_index(scope) { - queue_history_traversal_without_result(scope, plan.targets.remove(index)); - return; - } - let Some(history) = window_history_for_holder(scope, plan.owner) else { - return; - }; - let index = history_index(scope, history); - queue_history_traversal_without_result( - scope, - TraversalTarget { - owner: plan.owner, - history, - current_index: index, - target_index: index, - joint_step: Some(plan.step()), - }, - ); -} - fn entry_reference<'s>( scope: &mut v8::PinScope<'s, '_>, history: v8::Local<'s, v8::Object>, @@ -149,6 +125,7 @@ pub(super) fn execute<'s>( let Some((participants, execution_owner)) = captured else { let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError"); results::reject_pending_navigation_results(scope, &results, error); + super::session_history_traversal::cancel_step(scope, plan.owner, plan.step()); return; }; let mut admission = PendingHistoryTraversalAdmission { @@ -225,6 +202,26 @@ pub(super) fn execute<'s>( ); return; } + if let Some((url, _)) = history_entry_seed_for_traversal( + scope, + target.owner, + target.current_index, + target.target_index, + ) && let Some(navigation) = navigation + { + let results = if target.owner.strict_equals(plan.owner.into()) { + admission.results.as_slice() + } else { + &[] + }; + super::navigation_result::track_cross_document_traversal_navigation( + scope, + navigation, + outcome.signal, + url.as_str(), + results, + ); + } if let Some(promise) = outcome.precommit_result { precommit.push(promise); } @@ -284,7 +281,11 @@ fn validate<'s>( if !admission.active.get() || !navigation_document_is_active(scope, owner) { return None; } - let targets = super::session_history::project_traversal(scope, owner, &admission.plan)?; + let targets = super::navigation_traversal_plan::project_traversal_participants( + scope, + owner, + &admission.plan, + )?; if targets.len() != admission.participants.len() { return None; } @@ -407,6 +408,8 @@ fn settle_aborted_admission<'s>( if !results_rejected { results::reject_pending_navigation_results(scope, &admission.results, error); } + let owner = v8::Local::new(scope, &admission.initiator); + super::session_history_traversal::cancel_step(scope, owner, admission.plan.target_step()); } pub(super) fn cancel_pending<'s>( @@ -489,6 +492,7 @@ struct CrossDocumentParticipant<'s> { } fn commit(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalAdmission) { + let _execution = crate::script_cleanup::ScriptExecutionScope::enter(scope); for participant in &admission.participants { if let Some(event) = &participant.outcome.event { let event = v8::Local::new(scope, event); @@ -588,6 +592,12 @@ fn commit(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalA moli_page_types::SessionHistoryUpdateKind::Traverse { delta }, ); } + for (_, entry) in &applied { + apply::finish_history_entry_commit(scope, entry); + } + if targets.is_empty() { + super::session_history_traversal::finish_entry(scope, owner, None); + } let finished = traversal::finished_resolver_array(scope, &admission.results); let resolved_entry = navigation_current_entry(scope, owner) .map(Into::into) diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs index ed0ec571ab8..289492ba1c9 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs @@ -1,7 +1,5 @@ -use super::history_runtime::{ - history_traversal_target_window, reject_pending_navigation_results, - route_history_traversal_task, -}; +use super::history_runtime::results::reject_pending_navigation_results; +use super::history_runtime::{history_traversal_target_window, route_history_traversal_task}; use super::navigation_entry::history_entries; use super::navigation_events::{ NavigationDispatchOutcome, dispatch_beforeunload_for_runtime_owner, @@ -39,6 +37,15 @@ pub(super) fn queue_navigation_traversal_with_result<'s>( traversal_target_entry(scope, &target) .and_then(|entry| super::session_history::step_for_entry(scope, target.owner, &entry)) }); + if target.joint_step.is_some_and(|step| { + !super::session_history::traversal_is_allowed(scope, target.owner, step) + }) { + return Some(navigation_rejected_dom_exception_result( + scope, + "The initiator cannot traverse all affected navigables", + "SecurityError", + )); + } let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { return Some(navigation_rejected_dom_exception_result( scope, @@ -112,79 +119,72 @@ pub(super) fn queue_navigation_traversal_with_result<'s>( Some(result) } -pub(super) fn queue_history_traversal_without_result<'s>( +pub(super) fn queue_history_traversal_by_delta<'s>( scope: &mut v8::PinScope<'s, '_>, - mut target: TraversalTarget<'s>, + history: v8::Local<'s, v8::Object>, + delta: i64, ) { - target.joint_step = target.joint_step.or_else(|| { - traversal_target_entry(scope, &target) - .and_then(|entry| super::session_history::step_for_entry(scope, target.owner, &entry)) - }); + let owner = super::navigation_window::runtime_window_owner(scope, history); let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { return; }; let host = unsafe { &mut *host_ptr }; - let Some(exact_target) = window_task_target_for_runtime_owner(scope, host, target.owner) else { + let Some(target) = window_task_target_for_runtime_owner(scope, host, owner) else { return; }; - if let Some((_target_url, mut seed)) = history_entry_seed_for_traversal( - scope, - target.owner, - target.current_index, - target.target_index, - ) { - seed.session_history.target_step = target.joint_step; - super::session_history::capture_for_navigation(scope, target.owner, &mut seed); - if runtime_window_is_global(scope, target.owner) { - let binding = super::session_history::binding(scope, host, target.owner); - let Some(delta) = target - .joint_step - .and_then(|step| host.session_histories.get_mut(binding.popup).delta_to(step)) - else { - return; - }; - host.record_pending_top_level_history_traversal(delta); - return; - } - let target_key = traversal_target_entry(scope, &target) - .map(|entry| entry.borrow().key.as_str().to_owned()); - let receiver_context = target - .history - .get_creation_context(scope) - .unwrap_or_else(|| scope.get_current_context()); - let receiver_scope = &mut v8::ContextScope::new(scope, receiver_context); - if let Some(producer) = host.queue_cross_document_history_traversal( - receiver_scope, - exact_target, - target.target_index, - target_key, - seed, - ) { - route_history_traversal_task(receiver_scope, host, producer); - } - return; - } - let target_entry = traversal_target_entry(scope, &target); - if !traversal_target_entry_still_available(scope, &target, target_entry.as_ref()) { - return; - } - let receiver_context = target - .history + let binding = super::session_history::binding(scope, host, owner); + let step = host.session_histories.get_mut(binding.popup).current_step(); + let context = history .get_creation_context(scope) .unwrap_or_else(|| scope.get_current_context()); - let receiver_scope = &mut v8::ContextScope::new(scope, receiver_context); - let target_key = target_entry.map(|entry| entry.borrow().key.as_str().to_owned()); - if let Some(producer) = host.queue_history_traversal( - receiver_scope, - exact_target, - target.target_index, - target.joint_step, - target_key, - ) { - route_history_traversal_task(receiver_scope, host, producer); + let scope = &mut v8::ContextScope::new(scope, context); + if let Some(producer) = + host.queue_history_traversal_by_delta(scope, target, delta, binding.popup, step) + { + route_history_traversal_task(scope, host, producer); } } +fn apply_history_traversal_by_delta( + scope: &mut v8::PinScope<'_, '_>, + host: &mut PageScriptHost, + exact_target: crate::native_bridge::WindowTaskTarget, + delta: i64, + from: moli_page_types::SessionHistoryStepId, +) { + let Some(owner) = history_traversal_target_window(scope, host, exact_target) else { + return; + }; + let context = owner + .get_creation_context(scope) + .unwrap_or_else(|| scope.get_current_context()); + let scope = &mut v8::ContextScope::new(scope, context); + let Some(history) = window_history_for_holder(scope, owner) else { + return; + }; + use super::navigation_traversal_plan::{ + HistoryDeltaTraversalPlan, history_delta_traversal_target, + }; + let target = match history_delta_traversal_target(scope, history, delta, Some(from)) { + Some(HistoryDeltaTraversalPlan::Traverse(target)) => target, + Some(HistoryDeltaTraversalPlan::Denied) => return, + None => { + let binding = super::session_history::binding(scope, host, owner); + if binding.popup.is_none() + && host.sandbox_allows_history_traversal( + exact_target.dispatch_scope(), + crate::native_bridge::OwnerDispatchScope::Top, + crate::native_bridge::OwnerDispatchScope::Top, + ) + { + host.record_pending_top_level_history_traversal(delta); + } + return; + } + }; + super::session_history_traversal::apply_step(scope, host, exact_target, target.step(), None); +} + fn traversal_target_entry<'s>( scope: &mut v8::PinScope<'s, '_>, target: &TraversalTarget<'s>, @@ -226,12 +226,12 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' scope: &mut v8::PinScope<'s, 'i>, host: &mut PageScriptHost, traversal: PendingCrossDocumentTraversal, -) { +) -> bool { if matches!( traversal.target.dispatch_scope(), crate::native_bridge::OwnerDispatchScope::Child(_) ) { - super::history_runtime::apply_pending_history_traversal( + return super::history_runtime::apply_pending_history_traversal( scope, host, crate::native_bridge::PendingHistoryTraversal { @@ -243,7 +243,6 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' results: traversal.results, }, ); - return; } let Some(target_url) = traversal .seed @@ -253,15 +252,15 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' .map(|entry| entry.url.clone()) else { reject_cross_document_traversal(scope, &traversal); - return; + return false; }; let Some(owner) = history_traversal_target_window(scope, host, traversal.target) else { reject_cross_document_traversal(scope, &traversal); - return; + return false; }; let Some(history) = window_history_for_holder(scope, owner) else { reject_cross_document_traversal(scope, &traversal); - return; + return false; }; if !traversal_target_key_still_available( scope, @@ -270,7 +269,7 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' traversal.target_key.as_deref(), ) { reject_cross_document_traversal(scope, &traversal); - return; + return false; } let info = traversal .info @@ -293,7 +292,7 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' } if !is_current(scope, host) { reject_cross_document_traversal(scope, &traversal); - return; + return false; } let navigation = window_navigation_for_holder(scope, owner); if let Some(navigation) = navigation { @@ -301,7 +300,7 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' } if !is_current(scope, host) { reject_cross_document_traversal(scope, &traversal); - return; + return false; } let outcome = navigation.map_or_else(NavigationDispatchOutcome::proceed, |navigation| { dispatch_navigation_traverse_event_with_outcome( @@ -344,22 +343,23 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' if !closing_popup { reject_cross_document_traversal(scope, &traversal); } - return; + return false; } match dispatch_scope { crate::native_bridge::OwnerDispatchScope::Child(_) => { unreachable!("child traversal uses the coordinator") } crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id) => { - if !host.queue_lightweight_popup_cross_document_traversal( + let queued = host.queue_lightweight_popup_cross_document_traversal( scope, popup_id, &target_url, traversal.seed, - ) && let Some(navigation) = navigation - { + ); + if !queued && let Some(navigation) = navigation { cancel_active_cross_document_navigation(scope, navigation, None); } + queued } crate::native_bridge::OwnerDispatchScope::Top => { unreachable!("top-level traversals are handed off to the browser") @@ -373,11 +373,32 @@ pub(crate) fn apply_authorized_history_traversal_task( action: PendingHistoryTraversalAction, ) { match action { + PendingHistoryTraversalAction::ByDelta { + target, + delta, + position, + } => { + let from = position.borrow().step; + let previous = host.replace_active_history_delta_position(Some(position)); + apply_history_traversal_by_delta(scope, host, target, delta, from); + host.replace_active_history_delta_position(previous); + } PendingHistoryTraversalAction::SameDocument(traversal) => { - super::history_runtime::apply_pending_history_traversal(scope, host, traversal); + super::session_history_traversal::apply_entry(scope, host, traversal); } PendingHistoryTraversalAction::CrossDocument(traversal) => { - apply_pending_cross_document_traversal(scope, host, *traversal); + super::session_history_traversal::apply_entry( + scope, + host, + crate::native_bridge::PendingHistoryTraversal { + joint_step: traversal.seed.session_history.target_step, + target: traversal.target, + target_index: traversal.target_index, + target_key: traversal.target_key, + info: traversal.info, + results: traversal.results, + }, + ); } } } diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs index abc771a4cff..2ccd9366cce 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs @@ -17,6 +17,45 @@ pub(super) struct JointTraversalPlan<'s> { pub(super) targets: Vec>, } +pub(super) fn project_traversal_participants<'s>( + scope: &mut v8::PinScope<'s, '_>, + owner: v8::Local<'s, v8::Object>, + core: &moli_session_history::SessionHistoryTraversalPlan, +) -> Option>> { + let mut targets = super::session_history::project_traversal(scope, owner, core)?; + let host = unsafe { &mut *crate::util::context_host_ptr_from_global_bridge(scope)? }; + let replacing = targets + .iter() + .filter_map(|target| { + super::navigation_seed::history_entry_seed_for_traversal( + scope, + target.owner, + target.current_index, + target.target_index, + )?; + super::navigation_window::runtime_window_dispatch_scope(scope, target.owner) + }) + .collect::>(); + targets.retain(|target| { + let Some(mut dispatch) = + super::navigation_window::runtime_window_dispatch_scope(scope, target.owner) + else { + return false; + }; + while let crate::native_bridge::OwnerDispatchScope::Child(handle) = dispatch { + let Some(parent) = host.owner_dispatch_scope_for_node(handle) else { + break; + }; + if replacing.contains(&parent) { + return false; + } + dispatch = parent; + } + true + }); + Some(targets) +} + impl<'s> JointTraversalPlan<'s> { pub(super) fn resolve( scope: &mut v8::PinScope<'s, '_>, @@ -24,7 +63,7 @@ impl<'s> JointTraversalPlan<'s> { step: moli_session_history::SessionHistoryStepId, ) -> Option { let core = super::session_history::plan_traversal(scope, owner, step)?; - let targets = super::session_history::project_traversal(scope, owner, &core)?; + let targets = project_traversal_participants(scope, owner, &core)?; Some(Self { core, owner, @@ -167,26 +206,29 @@ pub(super) fn navigation_index_traversal_plan<'s>( })) } -pub(super) fn history_delta_traversal_plan<'s>( +pub(super) enum HistoryDeltaTraversalPlan<'s> { + Denied, + Traverse(JointTraversalPlan<'s>), +} + +pub(super) fn history_delta_traversal_target<'s>( scope: &mut v8::PinScope<'s, '_>, history: v8::Local<'s, v8::Object>, delta: i64, -) -> Option> { + from: Option, +) -> Option> { let owner = runtime_window_owner(scope, history); let host = unsafe { &mut *crate::util::context_host_ptr_from_global_bridge(scope)? }; let binding = super::session_history::binding(scope, host, owner); - // Further requests made through the outgoing popup Document's History - // are discarded when that Document is replaced. Do not rebase them onto - // the destination's projected history while its resource load waits. - if let Some(popup_id) = binding.popup - && host.lightweight_popup_has_pending_history_traversal(popup_id) - { - return None; + let model = host.session_histories.get_mut(binding.popup); + let step = model.step_by_delta_from(from.unwrap_or_else(|| model.current_step()), delta)?; + // Use the owning Window history even when called from an isolated world. + let owner = + super::session_history::owner_for_context(scope, host, binding.context, binding.popup)?; + if !super::session_history::traversal_is_allowed(scope, owner, step) { + return Some(HistoryDeltaTraversalPlan::Denied); } - let model = host.session_histories.get_mut(binding.popup).clone(); - let source = host - .pending_joint_history_step(&model) - .unwrap_or_else(|| model.current_step()); - let step = model.step_by_delta_from(source, delta)?; - JointTraversalPlan::resolve(scope, owner, step) + Some(HistoryDeltaTraversalPlan::Traverse( + JointTraversalPlan::resolve(scope, owner, step)?, + )) } diff --git a/moli-renderer-v8/src/context_bootstrap/session_history.rs b/moli-renderer-v8/src/context_bootstrap/session_history.rs index d0bcf5c279a..3c6b51019b5 100644 --- a/moli-renderer-v8/src/context_bootstrap/session_history.rs +++ b/moli-renderer-v8/src/context_bootstrap/session_history.rs @@ -110,7 +110,9 @@ pub(super) fn restore<'s>( && let Some(snapshot) = &seed.session_history.traversable { *history = (**snapshot).clone(); - return; + if seed.session_history.commit != SessionHistoryCommit::Traverse { + return; + } } let entry = SessionHistoryEntry { key: NavigationHistoryEntryKey::from_serialized( @@ -118,6 +120,27 @@ pub(super) fn restore<'s>( ), document: snapshot.document_id.clone(), }; + if seed.session_history.commit == SessionHistoryCommit::Traverse + && let Some(step) = seed.session_history.target_step + { + if seed.session_history.admitted_entry.is_none() + && let Some(plan) = plan_traversal(scope, owner, step) + && let Some(delta) = commit_traversal(scope, owner, &plan).filter(|delta| *delta != 0) + { + publish( + scope, + owner, + moli_page_types::SessionHistoryUpdateKind::Traverse { delta }, + ); + } + super::session_history_traversal::finish_entry(scope, owner, Some(&entry.key)); + let root = binding.popup.map_or( + OwnerDispatchScope::Top, + OwnerDispatchScope::LightweightPopup, + ); + unsafe { &mut *host_ptr }.remember_nested_histories(root); + return; + } // The seed may be installed repeatedly while a child navigation loads. // Identity, rather than URL or list shape, makes the commit idempotent. if history.entry(binding.context) == Some(&entry) @@ -173,6 +196,7 @@ pub(crate) fn install_session_history_position( if let Some(entry) = entry { history.attach(SessionHistoryContextId::ROOT, None, entry); } + super::navigation_serialize::publish_top_level_navigation_history(scope, owner); } /// Called after the main realm is admitted. Child realms may be prebootstrapped @@ -398,7 +422,7 @@ pub(super) fn prune_views<'s>( // history includes hidden entries and cannot supply these indices. set_history_entries(scope, history, retained); set_history_index(scope, history, current); - super::navigation_serialize::sync_child_navigation_entry_seed_from_owner(scope, owner); + super::navigation_serialize::sync_navigation_entry_seed_from_owner(scope, owner); } removed } @@ -451,13 +475,6 @@ pub(super) fn project_traversal<'s>( if !entries.contains_key(&SessionHistoryContextId::ROOT) { return None; } - let source = - super::navigation_window::window_task_target_for_runtime_owner(scope, host, owner)? - .dispatch_scope(); - let root = binding.popup.map_or( - OwnerDispatchScope::Top, - OwnerDispatchScope::LightweightPopup, - ); let mut targets = Vec::new(); for (&context, entry) in entries { let Some(owner) = owner_for_context(scope, host, context, binding.popup) else { @@ -479,12 +496,6 @@ pub(super) fn project_traversal<'s>( continue; }; if current_index != target_index { - let target = - super::navigation_window::window_task_target_for_runtime_owner(scope, host, owner)? - .dispatch_scope(); - if !host.sandbox_allows_history_traversal(source, target, root) { - return Some(Vec::new()); - } targets.push(super::navigation_traversal_execution::TraversalTarget { owner, history, @@ -497,6 +508,35 @@ pub(super) fn project_traversal<'s>( Some(targets) } +/// Admission uses the initiating Document's committed sandbox for every affected navigable. +pub(super) fn traversal_is_allowed<'s>( + scope: &mut v8::PinScope<'s, '_>, + owner: v8::Local<'s, v8::Object>, + step: SessionHistoryStepId, +) -> bool { + let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + return false; + }; + let host = unsafe { &mut *host_ptr }; + let source = runtime_window_dispatch_scope(scope, owner).unwrap_or(OwnerDispatchScope::Top); + let binding = binding(scope, host, owner); + let root = binding.popup.map_or( + OwnerDispatchScope::Top, + OwnerDispatchScope::LightweightPopup, + ); + match plan_traversal(scope, owner, step).and_then(|plan| project_traversal(scope, owner, &plan)) + { + Some(targets) => targets.iter().all(|target| { + host.sandbox_allows_history_traversal( + source, + runtime_window_dispatch_scope(scope, target.owner).unwrap_or(root), + root, + ) + }), + None => host.sandbox_allows_history_traversal(source, root, root), + } +} + pub(super) fn commit_traversal<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, @@ -504,9 +544,11 @@ pub(super) fn commit_traversal<'s>( ) -> Option { let host = unsafe { &mut *context_host_ptr_from_global_bridge(scope)? }; let binding = binding(scope, host, owner); - host.session_histories - .get_mut(binding.popup) - .commit_traversal(plan) + let delta = host + .session_histories + .commit_traversal(binding.popup, plan)?; + host.commit_active_history_delta_position(binding.popup, plan.target_step()); + Some(delta) } pub(super) fn publish<'s>( diff --git a/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs b/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs new file mode 100644 index 00000000000..ae0e99e712b --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs @@ -0,0 +1,235 @@ +//! Execution and commit barriers for one traversal of the shared history. +//! The barrier retains task identities, never a second history or cached length. +use super::history_runtime::{ + apply_pending_history_traversal, history_traversal_target_window, route_history_traversal_task, +}; +use super::navigation_entry::{history_entries, history_index}; +use super::navigation_events::dispatch_navigation_entry_dispose; +use super::navigation_seed::history_entry_seed_for_traversal; +use super::navigation_traversal_execution::{ + apply_pending_cross_document_traversal, reject_canceled_history_traversal_results, +}; +use super::navigation_window::{ + runtime_window_is_global, window_history_for_holder, window_task_target_for_runtime_owner, +}; +use super::session_history; +use crate::native_bridge::{ + OwnerDispatchScope, PageScriptHost, PendingCrossDocumentTraversal, PendingHistoryTraversal, + WindowTaskTarget, +}; +use crate::util::context_host_ptr_from_global_bridge; +use moli_session_history::{NavigationHistoryEntryKey, SessionHistoryStepId}; + +pub(super) fn apply_entry( + scope: &mut v8::PinScope<'_, '_>, + host: &mut PageScriptHost, + traversal: PendingHistoryTraversal, +) { + let Some(owner) = history_traversal_target_window(scope, host, traversal.target) else { + reject_canceled_history_traversal_results(scope, &traversal.results); + return; + }; + let step = traversal.joint_step.or_else(|| { + let history = window_history_for_holder(scope, owner)?; + let entries = history_entries(scope, history)?; + let entry = entries.get(traversal.target_index as usize)?; + session_history::step_for_entry(scope, owner, entry) + }); + if let Some(step) = step { + apply_step(scope, host, traversal.target, step, Some(traversal)); + } else { + apply_pending_history_traversal(scope, host, traversal); + } +} + +pub(super) fn apply_step( + scope: &mut v8::PinScope<'_, '_>, + host: &mut PageScriptHost, + source: WindowTaskTarget, + step: SessionHistoryStepId, + method: Option, +) { + let Some(owner) = history_traversal_target_window(scope, host, source) else { + if let Some(method) = method { + reject_canceled_history_traversal_results(scope, &method.results); + } + return; + }; + let plan = session_history::traversal_is_allowed(scope, owner, step) + .then(|| super::navigation_traversal_plan::JointTraversalPlan::resolve(scope, owner, step)) + .flatten(); + let Some(plan) = plan else { + if let Some(method) = method { + reject_canceled_history_traversal_results(scope, &method.results); + } + return; + }; + let binding = session_history::binding(scope, host, owner); + let root = plan.cross_document_root_index(scope); + if let Some(index) = root { + let target = &plan.targets[index]; + if runtime_window_is_global(scope, target.owner) { + let Some(delta) = host.session_histories.get_mut(binding.popup).delta_to(step) else { + return; + }; + if let Some(entry) = history_entries(scope, target.history) + .and_then(|entries| entries.get(target.target_index as usize).cloned()) + { + let key = entry.borrow().key.as_str().to_owned(); + host.top_level_navigation_history() + .select_joint_traversal(key, step); + } + host.record_pending_top_level_history_traversal(delta); + return; + } + } + let targets = plan + .targets + .iter() + .map(|target| { + let entries = history_entries(scope, target.history)?; + let entry = entries.get(target.target_index as usize)?; + let key = entry.borrow().key.clone(); + Some(( + session_history::binding(scope, host, target.owner).context, + key, + )) + }) + .collect::>>(); + let Some(targets) = targets else { + if let Some(method) = method { + reject_canceled_history_traversal_results(scope, &method.results); + } + return; + }; + host.session_histories + .begin_traversal(binding.popup, step, targets); + host.retain_active_history_delta_position(binding.popup); + let accepted = if let Some(index) = root { + let target = &plan.targets[index]; + let pending = window_task_target_for_runtime_owner(scope, host, target.owner).zip( + history_entry_seed_for_traversal( + scope, + target.owner, + target.current_index, + target.target_index, + ), + ); + if let Some((exact, (_url, mut seed))) = pending { + seed.session_history.target_step = Some(step); + let key = history_entries(scope, target.history) + .and_then(|entries| entries.get(target.target_index as usize).cloned()) + .map(|entry| entry.borrow().key.as_str().to_owned()); + let (info, results) = method.map_or_else( + || (None, Vec::new()), + |method| (method.info, method.results), + ); + apply_pending_cross_document_traversal( + scope, + host, + PendingCrossDocumentTraversal { + target: exact, + target_index: target.target_index, + target_key: key, + seed, + info, + results, + }, + ) + } else { + false + } + } else { + let history = + window_history_for_holder(scope, owner).expect("admitted traversal has a history"); + let traversal = method.unwrap_or_else(|| PendingHistoryTraversal { + joint_step: Some(step), + target: source, + target_index: history_index(scope, history), + target_key: None, + info: None, + results: Vec::new(), + }); + apply_pending_history_traversal(scope, host, traversal) + }; + if !accepted { + cancel_step(scope, owner, step); + } +} + +pub(super) fn cancel_step<'s>( + scope: &mut v8::PinScope<'s, '_>, + owner: v8::Local<'s, v8::Object>, + step: SessionHistoryStepId, +) { + let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + return; + }; + let host = unsafe { &mut *host_ptr }; + let binding = session_history::binding(scope, host, owner); + if let Some(current) = host + .session_histories + .cancel_traversal_step(binding.popup, step) + { + finish(scope, host, owner, binding.popup, current); + } +} + +pub(super) fn finish_entry<'s>( + scope: &mut v8::PinScope<'s, '_>, + owner: v8::Local<'s, v8::Object>, + key: Option<&NavigationHistoryEntryKey>, +) { + let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + return; + }; + let host = unsafe { &mut *host_ptr }; + let binding = session_history::binding(scope, host, owner); + if let Some(step) = + host.session_histories + .finish_traversal_entry(binding.popup, binding.context, key) + { + finish(scope, host, owner, binding.popup, step); + } +} + +fn finish<'s>( + scope: &mut v8::PinScope<'s, '_>, + host_ptr: *mut PageScriptHost, + owner: v8::Local<'s, v8::Object>, + popup: Option, + step: SessionHistoryStepId, +) { + for entry in session_history::prune_views(scope, owner) { + dispatch_navigation_entry_dispose(scope, entry); + } + for producer in unsafe { &mut *host_ptr }.finish_pending_history_traversal(popup, step) { + route_history_traversal_task(scope, unsafe { &mut *host_ptr }, producer); + } +} + +pub(crate) fn finish_without_document_commit( + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + owner: OwnerDispatchScope, +) { + let host = unsafe { &mut *host_ptr }; + let popup = host.session_histories.popup_for_owner(owner); + if !host.session_histories.has_pending_traversal(popup) { + return; + } + let context = host.session_histories.context(owner); + if let Some(step) = host + .session_histories + .finish_traversal_entry(popup, context, None) + && let Some(root) = session_history::owner_for_context( + scope, + host, + moli_page_types::SessionHistoryContextId::ROOT, + popup, + ) + { + // A retiring child must never materialize its Window again. + finish(scope, host_ptr, root, popup, step); + } +} diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs index a53400296c4..97d62295522 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs @@ -50,18 +50,23 @@ impl PageScriptHost { self.dispatch_frame_navigation_csp_violation_event_best_effort( scope, handle, &violation, ); + crate::context_bootstrap::finish_joint_history_without_document_commit( + scope, + self, + super::super::OwnerDispatchScope::Child(handle), + ); self.cancel_child_document_navigation_before_load(handle, navigation_load); return Some(ChildDocumentCommitResult::ready(None)); } } if self.child_document_navigation_would_recurse(handle, &bootstrap, initiator) { - self.cancel_child_document_navigation_before_load(handle, navigation_load); - self.sync_existing_child_browsing_context_window_state(scope, handle); crate::context_bootstrap::finish_joint_history_without_document_commit( scope, self, - crate::native_bridge::OwnerDispatchScope::Child(handle), + super::super::OwnerDispatchScope::Child(handle), ); + self.cancel_child_document_navigation_before_load(handle, navigation_load); + self.sync_existing_child_browsing_context_window_state(scope, handle); return Some(ChildDocumentCommitResult::ready(None)); } self.cancel_child_meta_refresh_navigation(handle); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs index f891f391a2d..60457ea7cb4 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs @@ -629,6 +629,11 @@ impl PageScriptHost { }, ); } + crate::context_bootstrap::finish_joint_history_without_document_commit( + scope, + self, + super::super::OwnerDispatchScope::Child(handle), + ); self.clear_child_browsing_context_pending_navigation(handle); if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { entry.restore_navigation_entry_seed_from_committed(); @@ -797,6 +802,11 @@ impl PageScriptHost { }; }; entry.clear_cached_snapshot(); + crate::context_bootstrap::finish_joint_history_without_document_commit( + scope, + self, + super::super::OwnerDispatchScope::Child(handle), + ); self.reject_replaced_service_worker_child_client_navigation( handle, format!("Cannot navigate to URL: {error}"), diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs index 5b9f5560cff..f377796405e 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs @@ -858,6 +858,13 @@ impl PageScriptHost { false, ); } + if unsafe { &*host_ptr }.child_window_retirement_is_current(&retirement) { + crate::context_bootstrap::finish_joint_history_without_document_commit( + scope, + host_ptr, + super::super::OwnerDispatchScope::Child(retirement.handle), + ); + } let host = unsafe { &mut *host_ptr }; if host.child_window_retirement_is_current(&retirement) { host.drop_child_browsing_context_handles(vec![retirement.handle]); diff --git a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs index d84654b90a9..bb35ec40a21 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs @@ -8,9 +8,7 @@ use crate::runtime::{ }; use crate::service_worker_runtime::{ServiceWorkerClientId, ServiceWorkerClientNavigateError}; use moli_fetch::BrowserNavigationRequestKind; -use moli_page_types::{ - NavigationHistoryEntrySeed, NavigationHistoryMutation, SameDocumentHistoryUpdate, -}; +use moli_page_types::{NavigationHistoryEntrySeed, NavigationHistoryMutation}; use url::Url; pub(crate) struct PendingReservedServiceWorkerClient { diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index b618b27b5b9..4f391ac8739 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -2935,6 +2935,11 @@ impl PageScriptHost { let mut classic_script_load_pending = false; match completion.result { Ok(PopupDocumentLoadOutcome::IgnoredNavigation) => { + crate::context_bootstrap::finish_joint_history_without_document_commit( + scope, + self, + super::OwnerDispatchScope::LightweightPopup(popup_id), + ); if let Some(record) = self.lightweight_popup_record_mut(popup_id) { record.location_url = pending.previous_url.clone(); } @@ -3103,6 +3108,11 @@ impl PageScriptHost { error = %error, "lightweight popup document load failed" ); + crate::context_bootstrap::finish_joint_history_without_document_commit( + scope, + self, + super::OwnerDispatchScope::LightweightPopup(popup_id), + ); let Some(current_owner) = self.current_lightweight_popup_document_owner(popup_id) else { return PopupDocumentLoadApplication::Applied { diff --git a/moli-renderer-v8/src/native_bridge/context_host/session_history.rs b/moli-renderer-v8/src/native_bridge/context_host/session_history.rs index e7b5a3f2c64..a0f3974b690 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/session_history.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/session_history.rs @@ -1,5 +1,7 @@ use super::OwnerDispatchScope; -use moli_session_history::{JointSessionHistory, SessionHistoryContextId}; +use moli_session_history::{ + JointSessionHistory, NavigationHistoryEntryKey, SessionHistoryContextId, SessionHistoryStepId, +}; use std::collections::HashMap; /// Each traversable owns one history. Lightweight popup Windows share a V8 @@ -9,6 +11,13 @@ pub(crate) struct RendererSessionHistories { main: JointSessionHistory, popups: HashMap, contexts: HashMap, + pending: HashMap, PendingSessionHistoryTraversal>, +} + +struct PendingSessionHistoryTraversal { + step: SessionHistoryStepId, + committed: bool, + remaining: HashMap, } impl RendererSessionHistories { @@ -27,6 +36,106 @@ impl RendererSessionHistories { .any(|history| history.entry(context) == Some(entry)) } + pub(crate) fn popup_for_owner(&self, owner: OwnerDispatchScope) -> Option { + match owner { + OwnerDispatchScope::Top => None, + OwnerDispatchScope::LightweightPopup(id) => Some(id), + OwnerDispatchScope::Child(_) => { + let context = self.contexts.get(&owner)?; + self.popups.iter().find_map(|(popup, history)| { + (!history.context_entries(*context).is_empty()).then_some(*popup) + }) + } + } + } + + pub(crate) fn has_pending_traversal(&self, popup: Option) -> bool { + self.pending.contains_key(&popup) + } + + pub(crate) fn begin_traversal( + &mut self, + popup: Option, + step: SessionHistoryStepId, + targets: Vec<(SessionHistoryContextId, NavigationHistoryEntryKey)>, + ) { + self.pending.insert( + popup, + PendingSessionHistoryTraversal { + step, + committed: false, + remaining: targets.into_iter().collect(), + }, + ); + } + + pub(crate) fn commit_traversal( + &mut self, + popup: Option, + plan: &moli_session_history::SessionHistoryTraversalPlan, + ) -> Option { + let step = plan.target_step(); + let delta = self.get_mut(popup).commit_traversal(plan)?; + if let Some(pending) = self.pending.get_mut(&popup) + && pending.step == step + { + pending.committed = true; + } + Some(delta) + } + + pub(crate) fn finish_traversal_entry( + &mut self, + popup: Option, + context: SessionHistoryContextId, + key: Option<&NavigationHistoryEntryKey>, + ) -> Option { + let pending = self.pending.get_mut(&popup)?; + if key.is_none_or(|key| pending.remaining.get(&context) == Some(key)) { + pending.remaining.remove(&context); + } + if !pending.remaining.is_empty() { + return None; + } + let pending = self.pending.remove(&popup)?; + Some(if pending.committed { + pending.step + } else { + self.get_mut(popup).current_step() + }) + } + + pub(crate) fn is_pending_traversal_entry( + &self, + popup: Option, + 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, + step: SessionHistoryStepId, + ) -> Option { + if !self + .pending + .get(&popup) + .is_some_and(|pending| pending.step == step) + { + return None; + } + self.cancel_traversal(popup) + } + + pub(crate) fn cancel_traversal(&mut self, popup: Option) -> Option { + self.pending.remove(&popup)?; + Some(self.get_mut(popup).current_step()) + } + pub(crate) fn detach(&mut self, owner: OwnerDispatchScope) { if let Some(context) = self.contexts.remove(&owner) { self.main.detach(context); diff --git a/moli-renderer-v8/src/native_bridge/history_queue.rs b/moli-renderer-v8/src/native_bridge/history_queue.rs index e8984743475..b4effa4f841 100644 --- a/moli-renderer-v8/src/native_bridge/history_queue.rs +++ b/moli-renderer-v8/src/native_bridge/history_queue.rs @@ -7,8 +7,13 @@ use crate::page_task_queue::{ RendererPageHistoryTraversalTaskKind, RendererPageNavigationApiTaskId, RendererPageNavigationApiTaskKind, RendererPageNavigationApiTaskProducer, }; +use moli_page_types::SessionHistoryStepId; use moli_webapi::navigation_values::navigation_result_object; -use std::collections::VecDeque; +use std::{ + cell::RefCell, + collections::{HashMap, VecDeque}, + rc::Rc, +}; const NAVIGATION_LIFECYCLE_TRACE_LIMIT: usize = 128; @@ -71,7 +76,20 @@ pub(crate) struct PendingCrossDocumentTraversal { pub(crate) results: Vec, } +// A burst of classic History calls advances only on traversal commits. A +// synchronous push starts a new burst without retargeting already queued work. +pub(crate) struct HistoryTraversalPosition { + pub(crate) popup: Option, + source_step: SessionHistoryStepId, + pub(crate) step: SessionHistoryStepId, +} + pub(crate) enum PendingHistoryTraversalAction { + ByDelta { + target: WindowTaskTarget, + delta: i64, + position: Rc>, + }, SameDocument(PendingHistoryTraversal), CrossDocument(Box), } @@ -84,6 +102,9 @@ pub(crate) struct QueuedHistoryTraversalTask { } pub(super) struct HistoryQueueState { + in_flight_delta_positions: HashMap, Rc>>, + deferred_traversals: VecDeque<(Option, QueuedHistoryTraversalTask)>, + active_delta_position: Option>>, pending_history_traversal_tasks: VecDeque, next_history_traversal_task_id: RendererPageHistoryTraversalTaskId, pending_microtask_navigation_finished_results: VecDeque, @@ -95,6 +116,9 @@ pub(super) struct HistoryQueueState { impl Default for HistoryQueueState { fn default() -> Self { Self { + active_delta_position: None, + in_flight_delta_positions: HashMap::new(), + deferred_traversals: VecDeque::new(), pending_history_traversal_tasks: VecDeque::new(), next_history_traversal_task_id: RendererPageHistoryTraversalTaskId::first(), pending_microtask_navigation_finished_results: VecDeque::new(), @@ -116,7 +140,8 @@ impl HistoryQueueState { { Some(pending.target_index) } - PendingHistoryTraversalAction::SameDocument(_) + PendingHistoryTraversalAction::ByDelta { .. } + | PendingHistoryTraversalAction::SameDocument(_) | PendingHistoryTraversalAction::CrossDocument(_) => None, }) } @@ -149,7 +174,8 @@ impl HistoryQueueState { { Some(pending) } - PendingHistoryTraversalAction::SameDocument(_) + PendingHistoryTraversalAction::ByDelta { .. } + | PendingHistoryTraversalAction::SameDocument(_) | PendingHistoryTraversalAction::CrossDocument(_) => None, }) { @@ -387,54 +413,200 @@ impl PageScriptHost { .pending_history_traversal_target_index(target) } - pub(crate) fn pending_joint_history_step( - &self, - history: &moli_session_history::JointSessionHistory, - ) -> Option { - self.history_queue - .pending_history_traversal_tasks - .iter() - .rev() - .find_map(|queued| { - let step = match &queued.action { - PendingHistoryTraversalAction::SameDocument(pending) => pending.joint_step, - PendingHistoryTraversalAction::CrossDocument(pending) => { - pending.seed.session_history.target_step - } - }?; - history.entries_at(step).map(|_| step) - }) - } - - pub(crate) fn queue_history_traversal<'s>( + pub(crate) fn queue_history_traversal_by_delta<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, target: WindowTaskTarget, - target_index: u32, - joint_step: Option, - target_key: Option, + delta: i64, + popup: Option, + source_step: SessionHistoryStepId, ) -> Option { let execution_context = self.current_runtime_window_execution_context_identity(scope)?; let relevant_context = self.current_runtime_window_execution_context_binding(scope)?; - let sender = self.page_history_traversal_sender(); - let task_id = self.history_queue.queue_history_traversal( - execution_context, - relevant_context, - target, - target_index, - joint_step, - target_key, - None, - None, - )?; - Some(sender.bind_task( + let previous = self + .history_queue + .pending_history_traversal_tasks + .iter() + .rev() + .filter_map(|queued| match &queued.action { + PendingHistoryTraversalAction::ByDelta { position, .. } => Some(position), + _ => None, + }) + .chain( + self.history_queue + .deferred_traversals + .iter() + .rev() + .filter_map(|(_, queued)| match &queued.action { + PendingHistoryTraversalAction::ByDelta { position, .. } => Some(position), + _ => None, + }), + ) + .chain(self.history_queue.in_flight_delta_positions.get(&popup)) + .chain(self.history_queue.active_delta_position.as_ref()) + .find(|position| { + let position = position.borrow(); + position.popup == popup + && (position.source_step == source_step || position.step == source_step) + }); + let position = previous.cloned().unwrap_or_else(|| { + Rc::new(RefCell::new(HistoryTraversalPosition { + popup, + source_step, + step: source_step, + })) + }); + if self.session_histories.has_pending_traversal(popup) { + self.history_queue + .in_flight_delta_positions + .entry(popup) + .or_insert_with(|| Rc::clone(&position)); + } + let task_id = self.history_queue.next_history_traversal_task_id; + self.history_queue.next_history_traversal_task_id = task_id + .checked_next() + .expect("history-traversal task id overflow"); + self.history_queue + .pending_history_traversal_tasks + .push_back(QueuedHistoryTraversalTask { + task_id, + execution_context, + relevant_context, + action: PendingHistoryTraversalAction::ByDelta { + target, + delta, + position, + }, + }); + Some(self.page_history_traversal_sender().bind_task( execution_context, target, task_id, - RendererPageHistoryTraversalTaskKind::SameDocument, + RendererPageHistoryTraversalTaskKind::ByDelta, )) } + pub(crate) fn replace_active_history_delta_position( + &mut self, + position: Option>>, + ) -> Option>> { + std::mem::replace(&mut self.history_queue.active_delta_position, position) + } + + pub(crate) fn commit_active_history_delta_position( + &mut self, + popup: Option, + step: SessionHistoryStepId, + ) { + if let Some(position) = &self.history_queue.active_delta_position + && position.borrow().popup == popup + { + position.borrow_mut().step = step; + } + } + + pub(crate) fn retain_active_history_delta_position(&mut self, popup: Option) { + let current = self.session_histories.get_mut(popup).current_step(); + let position = self + .history_queue + .active_delta_position + .as_ref() + .or_else(|| { + // Navigation API work can precede a classic delta in the queue. + // That delta must follow the API traversal's actual commit too. + self.history_queue + .pending_history_traversal_tasks + .iter() + .find_map(|queued| { + let PendingHistoryTraversalAction::ByDelta { position, .. } = + &queued.action + else { + return None; + }; + let source = position.borrow(); + (source.popup == popup + && (source.source_step == current || source.step == current)) + .then_some(position) + }) + }) + .cloned(); + if let Some(position) = position { + self.history_queue + .in_flight_delta_positions + .insert(popup, position); + } + } + + pub(crate) fn defer_pending_history_traversal_task( + &mut self, + queued: QueuedHistoryTraversalTask, + ) -> Option { + let popup = match &queued.action { + PendingHistoryTraversalAction::ByDelta { position, .. } => position.borrow().popup, + PendingHistoryTraversalAction::SameDocument(traversal) => self + .session_histories + .popup_for_owner(traversal.target.dispatch_scope()), + PendingHistoryTraversalAction::CrossDocument(traversal) => self + .session_histories + .popup_for_owner(traversal.target.dispatch_scope()), + }; + if self.session_histories.has_pending_traversal(popup) { + self.history_queue + .deferred_traversals + .push_back((popup, queued)); + None + } else { + Some(queued) + } + } + + pub(crate) fn finish_pending_history_traversal( + &mut self, + popup: Option, + step: SessionHistoryStepId, + ) -> Vec { + self.commit_active_history_delta_position(popup, step); + if let Some(position) = self.history_queue.in_flight_delta_positions.remove(&popup) { + position.borrow_mut().step = step; + } + let mut producers = Vec::new(); + let mut retained = VecDeque::new(); + while let Some((root, mut queued)) = self.history_queue.deferred_traversals.pop_front() { + if root != popup { + retained.push_back((root, queued)); + continue; + } + let (target, kind) = match &queued.action { + PendingHistoryTraversalAction::ByDelta { target, .. } => { + (*target, RendererPageHistoryTraversalTaskKind::ByDelta) + } + PendingHistoryTraversalAction::SameDocument(t) => { + (t.target, RendererPageHistoryTraversalTaskKind::SameDocument) + } + PendingHistoryTraversalAction::CrossDocument(t) => ( + t.target, + RendererPageHistoryTraversalTaskKind::CrossDocument, + ), + }; + queued.task_id = self.history_queue.next_history_traversal_task_id; + self.history_queue.next_history_traversal_task_id = queued + .task_id + .checked_next() + .expect("history-traversal task id overflow"); + producers.push(self.page_history_traversal_sender().bind_task( + queued.execution_context, + target, + queued.task_id, + kind, + )); + self.history_queue + .pending_history_traversal_tasks + .push_back(queued); + } + self.history_queue.deferred_traversals = retained; + producers + } + pub(crate) fn queue_microtask_navigation_finished_result<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, @@ -591,38 +763,6 @@ impl PageScriptHost { Some((result, producer)) } - pub(crate) fn queue_cross_document_history_traversal<'s>( - &mut self, - scope: &mut v8::PinScope<'s, '_>, - target: WindowTaskTarget, - target_index: u32, - target_key: Option, - seed: NavigationHistoryEntrySeed, - ) -> Option { - let execution_context = self.current_runtime_window_execution_context_identity(scope)?; - let relevant_context = self.current_runtime_window_execution_context_binding(scope)?; - let sender = self.page_history_traversal_sender(); - let task_id = self.history_queue.queue_cross_document_history_traversal( - execution_context, - relevant_context, - PendingCrossDocumentTraversal { - target, - target_index, - target_key, - seed, - info: None, - results: Vec::new(), - }, - ); - Some(sender.bind_task( - execution_context, - target, - task_id, - RendererPageHistoryTraversalTaskKind::CrossDocument, - )) - } - - #[allow(clippy::too_many_arguments)] pub(crate) fn queue_cross_document_history_traversal_with_result<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, @@ -683,6 +823,9 @@ impl PageScriptHost { return None; } let (target, kind) = match &queued.action { + PendingHistoryTraversalAction::ByDelta { target, .. } => { + (*target, RendererPageHistoryTraversalTaskKind::ByDelta) + } PendingHistoryTraversalAction::SameDocument(pending) => ( pending.target, RendererPageHistoryTraversalTaskKind::SameDocument, @@ -709,6 +852,9 @@ impl PageScriptHost { ) -> Option { let queued = self.history_queue.pending_history_traversal_task(task_id)?; let (queued_target, queued_kind) = match &queued.action { + PendingHistoryTraversalAction::ByDelta { target, .. } => { + (*target, RendererPageHistoryTraversalTaskKind::ByDelta) + } PendingHistoryTraversalAction::SameDocument(pending) => ( pending.target, RendererPageHistoryTraversalTaskKind::SameDocument, diff --git a/moli-renderer-v8/src/page_task_queue/history_traversal.rs b/moli-renderer-v8/src/page_task_queue/history_traversal.rs index 738ad796009..446747cddc9 100644 --- a/moli-renderer-v8/src/page_task_queue/history_traversal.rs +++ b/moli-renderer-v8/src/page_task_queue/history_traversal.rs @@ -39,6 +39,7 @@ impl RendererPageHistoryTraversalTaskId { /// source. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum RendererPageHistoryTraversalTaskKind { + ByDelta, SameDocument, CrossDocument, } diff --git a/moli-renderer-v8/src/runtime/navigation_history.rs b/moli-renderer-v8/src/runtime/navigation_history.rs index b217301711f..65f131cf2a3 100644 --- a/moli-renderer-v8/src/runtime/navigation_history.rs +++ b/moli-renderer-v8/src/runtime/navigation_history.rs @@ -117,6 +117,9 @@ impl RendererNavigationHistory { } } pub(crate) fn publish(&self, seed: NavigationHistoryEntrySeed) { + if let Some(history) = seed.session_history.traversable.as_deref() { + *self.joint.lock() = Some(history.clone()); + } *self.snapshot.lock() = Some(Arc::new(seed)); } @@ -149,22 +152,52 @@ impl RendererNavigationHistory { )?)) } - pub fn traverse(&self, delta: i64) -> Option { + fn traversal_target( + &self, + delta: i64, + ) -> Option<( + Arc, + u32, + Option, + )> { let source = self.snapshot()?; - let target_index = - u32::try_from(i64::from(source.current_index).checked_add(delta)?).ok()?; - let candidate = traversal_navigation_seed_candidate( + let joint = self.joint.lock(); + let (index, step) = if let Some(joint) = joint.as_ref() { + let step = joint.step_by_delta(delta)?; + let entry = joint + .entries_at(step)? + .get(&SessionHistoryContextId::ROOT)?; + let index = source + .entries + .iter() + .find(|candidate| { + crate::context_bootstrap::navigation_entry_public_token(candidate.key.as_str()) + == entry.key.as_str() + })? + .history_index; + (index, Some(step)) + } else { + ( + u32::try_from(i64::from(source.current_index).checked_add(delta)?).ok()?, + None, + ) + }; + Some((source, index, step)) + } + + pub fn traverse(&self, delta: i64) -> Option { + let (source, target_index, step) = self.traversal_target(delta)?; + let mut candidate = traversal_navigation_seed_candidate( source.entries.clone(), source.current_index, target_index, )?; + candidate.seed.session_history.target_step = step; Some(self.request(candidate.seed)) } pub fn traversal_is_same_document(&self, delta: i64) -> Option { - let source = self.snapshot()?; - let target_index = - u32::try_from(i64::from(source.current_index).checked_add(delta)?).ok()?; + let (source, target_index, _) = self.traversal_target(delta)?; let current = current_entry(&source)?; let target = source .entries @@ -245,6 +278,9 @@ impl RendererNavigationHistoryRequest { { from.index = from.history_index; } + if self.navigation_type() == Some("traverse") { + seed.session_history.target_step = self.requested.session_history.target_step; + } update_destination_url(&mut seed, final_url); if self.initial_empty_source && let Some(activation) = &mut seed.activation diff --git a/moli-renderer-v8/src/script_vm/history_traversal.rs b/moli-renderer-v8/src/script_vm/history_traversal.rs index 511ebf2b987..f5dc9130e23 100644 --- a/moli-renderer-v8/src/script_vm/history_traversal.rs +++ b/moli-renderer-v8/src/script_vm/history_traversal.rs @@ -67,6 +67,13 @@ impl ScriptVm { anyhow!("authorized history traversal lost its exact pending payload") })?; + let Some(queued) = self + ._context_host + .borrow_mut() + .defer_pending_history_traversal_task(queued) + else { + return Ok(()); + }; let execution_context = queued.execution_context; let action = queued.action; let (bound_owner, bound_dispatch_scope, _realm_token, context) = @@ -111,7 +118,7 @@ impl ScriptVm { return Ok(false); }; let results = match queued.action { - PendingHistoryTraversalAction::ByDelta { .. } => return Ok(false), + PendingHistoryTraversalAction::ByDelta { .. } => Vec::new(), PendingHistoryTraversalAction::SameDocument(traversal) => traversal.results, PendingHistoryTraversalAction::CrossDocument(traversal) => traversal.results, }; diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_navigation_and_history.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_navigation_and_history.rs index e692c3ec909..6b53ff11050 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_navigation_and_history.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_navigation_and_history.rs @@ -2588,10 +2588,14 @@ child.location.href = "about:blank#2"; assert_eq!(result, "about:blank#2|0|true|"); } -#[test] -fn initial_about_blank_iframe_assign_replaces_history_after_same_document_update() { +#[tokio::test] +async fn initial_about_blank_iframe_assign_replaces_history_after_same_document_update() { for update_fragment in [false, true] { - let mut vm = new_storage_test_vm("https://initial-blank-history.test/"); + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://initial-blank-history.test/", + &loader, + ); vm.exec( r#" const frame = document.createElement('iframe'); @@ -2623,7 +2627,11 @@ const initialDocument = frame.contentDocument; None, ) .expect("initial document navigation should queue"); - vm.drain_pending_child_frame_work_for_test(); + advance_page_task_executor_until_eval_equals( + &mut vm, &loader, + "String(frame.contentDocument !== initialDocument && frame.contentDocument.readyState === 'complete')", + "true", "replacement Document must complete after queued hashchange delivery", + ).await; assert_eq!( vm.eval( @@ -2772,7 +2780,11 @@ frame.contentWindow.location.replace('about:blank'); .committed_navigation_entry_seed; assert!( seed.entries.iter().any(|entry| { - entry.id == previous_entry_id && entry.history_index < seed.current_index + crate::context_bootstrap::navigation_entry_public_token(entry.id.as_str()) + == crate::context_bootstrap::navigation_entry_public_token( + previous_entry_id.as_str(), + ) + && entry.history_index < seed.current_index }), "assign must retain the previous history step; initial srcdoc: {initial_srcdoc}" );