Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(protocol): retire superseded intercepted navigations

ldm0255238328ffa
diff --git a/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger.rs b/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger.rs
index b462404e8..4a029b9f5 100644
--- a/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger.rs
+++ b/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger.rs
@@ -1,5 +1,7 @@
use super::*;
+mod superseded_interception;
+
type TestSocket =
tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
@@ -461,37 +463,43 @@ async fn assert_intercepted_navigation_while_paused(
.find(|message| message["method"] == "Fetch.requestPaused")
.unwrap()["params"]["requestId"]
.clone();
- let navigation_id = if let Some(stale_action) = stale_response {
- send_cdp_command_without_wait(
- &mut socket,
- 20,
- "Page.navigate",
- Some(&session_id),
- json!({"url": format!("http://{fixture_addr}/?replacement")}),
- )
- .await;
- let replacement = recv_until_match(&mut socket, |message| {
- message["method"] == "Fetch.requestPaused"
- })
- .await;
- let replacement_id = replacement
- .iter()
- .find(|message| message["method"] == "Fetch.requestPaused")
- .unwrap()["params"]["requestId"]
- .clone();
- assert_ne!(request_id, replacement_id);
- let (method, params) = stale_action.command(request_id);
- let stale = send_cdp_command(&mut socket, 21, method, Some(&session_id), params).await;
- assert!(
- stale
+ let navigation_id =
+ if let Some(stale_action) = stale_response {
+ send_cdp_command_without_wait(
+ &mut socket,
+ 20,
+ "Page.navigate",
+ Some(&session_id),
+ json!({"url": format!("http://{fixture_addr}/?replacement")}),
+ )
+ .await;
+ let replacement = recv_until_match(&mut socket, |message| {
+ message["method"] == "Fetch.requestPaused"
+ })
+ .await;
+ let replacement_id = replacement
.iter()
- .any(|message| message["id"] == 21 && message.get("error").is_none())
- );
- request_id = replacement_id;
- 20
- } else {
- 9
- };
+ .find(|message| message["method"] == "Fetch.requestPaused")
+ .unwrap()["params"]["requestId"]
+ .clone();
+ assert_ne!(request_id, replacement_id);
+ assert!(
+ replacement.iter().any(|message| {
+ message["id"] == 9 && message["result"]["errorText"] == "net::ERR_ABORTED"
+ }),
+ "supersession must reply to A without a client action: {replacement:#?}"
+ );
+ let (method, params) = stale_action.command(request_id);
+ let stale = send_cdp_command(&mut socket, 21, method, Some(&session_id), params).await;
+ assert!(
+ stale.iter().any(|message| message["id"] == 21
+ && message["error"]["message"] == "RequestNotFound")
+ );
+ request_id = replacement_id;
+ 20
+ } else {
+ 9
+ };
let (method, params) = action.command(request_id);
let mut completed = send_cdp_command(&mut socket, 10, method, Some(&session_id), params).await;
if !completed
diff --git a/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger/superseded_interception.rs b/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger/superseded_interception.rs
new file mode 100644
index 000000000..eaaedfc2a
--- /dev/null
+++ b/moli-protocol-server/src/protocol_server/tests/websocket/navigation_debugger/superseded_interception.rs
@@ -0,0 +1,242 @@
+use super::*;
+
+#[tokio::test]
+async fn superseded_fetch_request_does_not_block_cancelled_replacement() {
+ assert_superseded_interception("Request", false, false).await;
+}
+
+#[tokio::test]
+async fn superseded_fetch_response_does_not_block_cancelled_replacement() {
+ assert_superseded_interception("Response", false, false).await;
+}
+
+#[tokio::test]
+async fn superseded_fetch_request_preserves_the_cancelled_replacements_debugger_pause() {
+ assert_superseded_interception("Request", true, false).await;
+}
+
+#[tokio::test]
+async fn superseded_fetch_response_preserves_the_cancelled_replacements_debugger_pause() {
+ assert_superseded_interception("Response", true, false).await;
+}
+
+#[tokio::test]
+async fn superseded_response_cancels_an_inflight_body_read_without_resurrecting_the_request() {
+ assert_superseded_interception("Response", false, true).await;
+}
+
+async fn assert_superseded_interception(stage: &str, debugger_paused: bool, body_read: bool) {
+ use axum::response::IntoResponse;
+
+ let (fixture_addr, fixture) = spawn_dedicated_fixture_server(
+ Router::new().route(
+ "/",
+ get(move || async move {
+ if body_read {
+ // Send the response head, but never finish the body. Only
+ // navigation cancellation can release the pending IO.read.
+ let stream = futures_util::stream::once(std::future::pending::<
+ Result<axum::body::Bytes, std::io::Error>,
+ >());
+ axum::body::Body::from_stream(stream).into_response()
+ } else {
+ "<title>replacement</title>".into_response()
+ }
+ }),
+ ),
+ "superseded-interception",
+ );
+ let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;
+ let (mut socket, _) = connect_async(format!(
+ "ws://{cdp_addr}/devtools/browser/{DEFAULT_BROWSER_ID}"
+ ))
+ .await
+ .unwrap();
+ let session_id =
+ cdp_create_default_session_and_navigate(&mut socket, "data:text/html,<title>old</title>")
+ .await;
+ send_cdp_command(
+ &mut socket,
+ 6,
+ "Debugger.enable",
+ Some(&session_id),
+ json!({}),
+ )
+ .await;
+ send_cdp_command(
+ &mut socket,
+ 7,
+ "Fetch.enable",
+ Some(&session_id),
+ json!({"patterns": [{"urlPattern": "*", "resourceType": "Document", "requestStage": stage}]}),
+ )
+ .await;
+ if debugger_paused {
+ pause_in_timer(
+ &mut socket,
+ &session_id,
+ 8,
+ "debugger; globalThis.resumedNormally = true;",
+ )
+ .await;
+ }
+
+ let mut messages = Vec::new();
+ let mut requests = Vec::new();
+ for id in [9, 10] {
+ send_cdp_command_without_wait(
+ &mut socket,
+ id,
+ "Page.navigate",
+ Some(&session_id),
+ json!({"url": format!("http://{fixture_addr}/?navigation={id}")}),
+ )
+ .await;
+ let paused = recv_until_match(&mut socket, |message| {
+ message["method"] == "Fetch.requestPaused"
+ })
+ .await;
+ requests.push(paused.last().unwrap()["params"]["requestId"].clone());
+ messages.extend(paused);
+ if body_read && id == 9 {
+ let opened = send_cdp_command(
+ &mut socket,
+ 15,
+ "Fetch.takeResponseBodyAsStream",
+ Some(&session_id),
+ json!({"requestId": requests[0]}),
+ )
+ .await;
+ let handle =
+ opened.iter().find(|message| message["id"] == 15).unwrap()["result"]["stream"]
+ .clone();
+ assert!(handle.is_string(), "body stream should open: {opened:#?}");
+ messages.extend(opened);
+ send_cdp_command_without_wait(
+ &mut socket,
+ 16,
+ "IO.read",
+ Some(&session_id),
+ json!({"handle": handle}),
+ )
+ .await;
+ }
+ }
+
+ // Leave A entirely alone. Only B is cancelled, and the old document must
+ // become usable without a client action on A (including Fetch.disable).
+ messages.extend(
+ send_cdp_command(
+ &mut socket,
+ 11,
+ "Fetch.failRequest",
+ Some(&session_id),
+ json!({"requestId": requests[1], "errorReason": "Aborted"}),
+ )
+ .await,
+ );
+ if debugger_paused {
+ messages.extend(
+ send_cdp_command(
+ &mut socket,
+ 12,
+ "Debugger.resume",
+ Some(&session_id),
+ json!({}),
+ )
+ .await,
+ );
+ }
+ send_cdp_command_without_wait(
+ &mut socket,
+ 13,
+ "Runtime.evaluate",
+ Some(&session_id),
+ json!({"expression": "document.title + ':' + globalThis.resumedNormally", "returnByValue": true}),
+ )
+ .await;
+ let completion = timeout(NAVIGATION_TIMEOUT, async {
+ while ![9, 13]
+ .into_iter()
+ .all(|id| messages.iter().any(|message| message["id"] == id))
+ || (body_read && !messages.iter().any(|message| message["id"] == 16))
+ {
+ messages.push(recv_ws_json(&mut socket).await);
+ }
+ })
+ .await;
+
+ // Always clean up before asserting so a failure cannot strand the old
+ // document's owner thread in a debugger pause or suspended channel.
+ messages.extend(
+ send_cdp_command(
+ &mut socket,
+ 14,
+ "Fetch.failRequest",
+ Some(&session_id),
+ json!({"requestId": requests[0], "errorReason": "Aborted"}),
+ )
+ .await,
+ );
+ let _ = socket.close(None).await;
+ abort_test_cdp_server(protocol_server).await;
+ drop(fixture);
+
+ assert!(
+ completion.is_ok(),
+ "unhandled stale A blocked the old document: {messages:#?}"
+ );
+ for id in [9, 10] {
+ let replies = messages
+ .iter()
+ .filter(|message| message["id"] == id)
+ .collect::<Vec<_>>();
+ assert_eq!(
+ replies.len(),
+ 1,
+ "each navigation needs exactly one terminal reply: {messages:#?}"
+ );
+ if id == 9 {
+ assert!(replies[0].get("error").is_none());
+ assert_eq!(replies[0]["result"]["errorText"], "net::ERR_ABORTED");
+ } else {
+ assert_eq!(replies[0]["error"]["message"], "Aborted");
+ }
+ }
+ assert!(
+ !messages
+ .iter()
+ .any(|message| message["method"] == "Page.frameNavigated")
+ );
+ let value =
+ &messages.iter().find(|message| message["id"] == 13).unwrap()["result"]["result"]["value"];
+ assert_eq!(
+ value,
+ if debugger_paused {
+ "old:true"
+ } else {
+ "old:undefined"
+ }
+ );
+ if debugger_paused {
+ assert!(
+ messages
+ .iter()
+ .any(|message| message["id"] == 12 && message.get("error").is_none()),
+ "supersession and cancellation must not terminate the original pause: {messages:#?}"
+ );
+ }
+ assert!(
+ messages
+ .iter()
+ .any(|message| message["id"] == 14 && message.get("error").is_some()),
+ "the retired interception must no longer accept client actions: {messages:#?}"
+ );
+ if body_read {
+ assert!(
+ messages.iter().any(|message| message["id"] == 16
+ && message["error"]["message"] == "StreamHandleNotFound"),
+ "the cancelled read must complete without restoring the old response: {messages:#?}"
+ );
+ }
+}
diff --git a/moli-protocol/src/conn/browser_context/fetch_owner.rs b/moli-protocol/src/conn/browser_context/fetch_owner.rs
index 998dac422..29fd13ca6 100644
--- a/moli-protocol/src/conn/browser_context/fetch_owner.rs
+++ b/moli-protocol/src/conn/browser_context/fetch_owner.rs
@@ -1182,6 +1182,36 @@ impl CdpConnection {
.drain_fetch_pending_state(),
)
}
+
+ pub(crate) fn take_superseded_intercepted_document_navigations(
+ &mut self,
+ owner: &CommandOwnerScope,
+ current: &crate::conn::DocumentNavigationToken,
+ ) -> Vec<crate::conn::NavigationDispatchState> {
+ let Some(mut target) = self.target_session_owner_mut_for_owner(owner) else {
+ return Vec::new();
+ };
+ let Some(mut fetch) = target.pending_fetch_owner_mut() else {
+ return Vec::new();
+ };
+ let retired = fetch.take_superseded_document_navigations(current);
+ retired
+ .into_iter()
+ .map(|(token, navigation)| {
+ if let Some(token) = token {
+ let finish = target
+ .runtime_slot_mut()
+ .finish_renderer_document_navigation(&token)
+ .expect("a newly admitted navigation keeps the renderer channel open");
+ // The replacement was registered before retiring its predecessors.
+ // Finishing old work must not release output or replay calls yet.
+ debug_assert!(finish.released_output.is_empty());
+ debug_assert!(finish.renderer_call_replacements.is_none());
+ }
+ navigation
+ })
+ .collect()
+ }
}
fn pending_fetch_request_route(
@@ -1274,6 +1304,15 @@ impl TargetSessionOwnerMut<'_> {
navigation: crate::conn::NavigationDispatchState,
body: crate::conn::DocumentBodySource,
) -> bool {
+ if let Some(token) = document_navigation_token.as_ref()
+ && let crate::conn::DocumentBodySource::StreamingRaw { response, .. } = &body
+ {
+ // Supersession must cancel the transport even while an IO.read
+ // task temporarily owns the response outside the Fetch maps.
+ self.runtime_slot_mut()
+ .page_slot_mut()
+ .add_document_navigation_cancellation(token, response.cancellation_handle());
+ }
let Some(mut owner) = self.pending_fetch_owner_mut() else {
return false;
};
diff --git a/moli-protocol/src/conn/fetch_support.rs b/moli-protocol/src/conn/fetch_support.rs
index 5599cb284..6b9f4713e 100644
--- a/moli-protocol/src/conn/fetch_support.rs
+++ b/moli-protocol/src/conn/fetch_support.rs
@@ -587,6 +587,22 @@ impl PausedDocumentTransfers {
.collect()
}
+ pub(crate) fn drain_superseded(
+ &mut self,
+ current: &DocumentNavigationToken,
+ ) -> Vec<PausedDocumentTransfer> {
+ let request_ids = self
+ .transfers
+ .iter()
+ .filter(|(_, transfer)| transfer.navigation_token() != Some(current))
+ .map(|(request_id, _)| request_id.clone())
+ .collect::<Vec<_>>();
+ request_ids
+ .into_iter()
+ .filter_map(|id| self.take(&id))
+ .collect()
+ }
+
pub(crate) fn drain_pending_transfers_for_session(
&mut self,
session_id: Option<&str>,
@@ -698,6 +714,7 @@ pub(crate) enum PendingFetchResponseBodyStreamRead {
NotFound,
Read { bytes: Vec<u8>, eof: bool },
Failed(anyhow::Error),
+ SupersededNavigation(Box<NavigationDispatchState>),
}
#[derive(Debug)]
@@ -793,6 +810,45 @@ pub(crate) struct PendingStreamingDocumentResponseNavigation {
}
impl PausedDocumentTransfer {
+ pub(crate) fn navigation_token(&self) -> Option<&DocumentNavigationToken> {
+ match &self.state {
+ PausedDocumentTransferState::Pending {
+ document_navigation_token,
+ ..
+ }
+ | PausedDocumentTransferState::ActiveBodyStream {
+ stream:
+ ActiveDocumentBodyStreamState {
+ document_navigation_token,
+ ..
+ },
+ ..
+ } => document_navigation_token.as_ref(),
+ }
+ }
+
+ pub(crate) fn into_navigation(
+ self,
+ ) -> (Option<DocumentNavigationToken>, NavigationDispatchState) {
+ // Dropping the remaining body also cancels an unfinished transport.
+ match self.state {
+ PausedDocumentTransferState::Pending {
+ document_navigation_token,
+ navigation,
+ ..
+ }
+ | PausedDocumentTransferState::ActiveBodyStream {
+ stream:
+ ActiveDocumentBodyStreamState {
+ document_navigation_token,
+ navigation,
+ ..
+ },
+ ..
+ } => (document_navigation_token, navigation),
+ }
+ }
+
pub(crate) fn pending(
fetch_request_id: String,
document_navigation_token: Option<DocumentNavigationToken>,
@@ -1220,17 +1276,8 @@ impl PausedDocumentTransfer {
NavigationDispatchState,
anyhow::Result<NavigationLoadOutcome>,
) {
- match self.state {
- PausedDocumentTransferState::Pending {
- document_navigation_token,
- navigation,
- body,
- } => {
- let _ = body;
- (document_navigation_token, navigation, Err(error))
- }
- PausedDocumentTransferState::ActiveBodyStream { stream, .. } => stream.fail(error),
- }
+ let (token, navigation) = self.into_navigation();
+ (token, navigation, Err(error))
}
}
@@ -1332,17 +1379,6 @@ impl ActiveDocumentBodyStreamState {
.await;
(self.document_navigation_token, navigation_state, navigation)
}
-
- fn fail(
- self,
- error: anyhow::Error,
- ) -> (
- Option<DocumentNavigationToken>,
- NavigationDispatchState,
- anyhow::Result<NavigationLoadOutcome>,
- ) {
- (self.document_navigation_token, self.navigation, Err(error))
- }
}
#[derive(Debug)]
diff --git a/moli-protocol/src/conn/state/devtools_renderer_channel.rs b/moli-protocol/src/conn/state/devtools_renderer_channel.rs
index b1daf3c91..1040b3d68 100644
--- a/moli-protocol/src/conn/state/devtools_renderer_channel.rs
+++ b/moli-protocol/src/conn/state/devtools_renderer_channel.rs
@@ -266,12 +266,18 @@ impl DevToolsRendererChannel {
navigation: &DocumentNavigationToken,
) -> Result<bool, DevToolsRendererChannelError> {
self.ensure_open()?;
- Ok(self.inflight_cross_document_navigations.remove(navigation)
- && !self.output_is_suspended())
+ let was_suspended = self.output_is_suspended();
+ self.inflight_cross_document_navigations.remove(navigation);
+ Ok(was_suspended && !self.output_is_suspended())
}
pub(crate) fn output_is_suspended(&self) -> bool {
- !self.inflight_cross_document_navigations.is_empty()
+ // Older work may still need a terminal reply or resource cleanup, but
+ // only the current navigation can keep the renderer channel suspended.
+ self.latest_navigation.as_ref().is_some_and(|latest| {
+ self.inflight_cross_document_navigations
+ .contains(&latest.token)
+ })
}
pub(crate) fn inflight_navigation_count(&self) -> usize {
@@ -641,7 +647,7 @@ mod tests {
}
#[test]
- fn output_remains_suspended_until_all_overlapping_navigations_finish() {
+ fn only_current_navigation_can_keep_output_suspended() {
let request_a = navigation(1);
let request_b = navigation(2);
let mut channel = DevToolsRendererChannel::default();
@@ -655,14 +661,37 @@ mod tests {
assert_eq!(channel.inflight_navigation_count(), 2);
assert!(channel.output_is_suspended());
- assert_eq!(channel.navigation_finished(&request_b), Ok(false));
- assert!(channel.output_is_suspended());
- assert!(
- channel
- .navigation_finished(&request_a)
- .expect("final overlapping navigation")
- );
+ assert_eq!(channel.navigation_finished(&request_b), Ok(true));
assert!(!channel.output_is_suspended());
+ assert_eq!(channel.inflight_navigation_count(), 1);
+ assert_eq!(channel.navigation_finished(&request_a), Ok(false));
+ assert_eq!(channel.inflight_navigation_count(), 0);
+ assert!(!channel.output_is_suspended());
+ }
+
+ #[test]
+ fn late_completion_cannot_release_a_subsequent_navigation() {
+ let mut channel = DevToolsRendererChannel::default();
+ let a = navigation(1);
+ let b = navigation(2);
+ let c = navigation(3);
+ channel.navigation_started(a.clone()).unwrap();
+ let candidate_a = channel
+ .attach_candidate(&a, RendererDevToolsAgentToken::allocate())
+ .unwrap();
+ channel.navigation_started(b.clone()).unwrap();
+ assert_eq!(channel.navigation_finished(&b), Ok(true));
+ assert_eq!(
+ channel.commit_candidate(candidate_a),
+ Err(DevToolsRendererChannelError::SupersededNavigation)
+ );
+ channel.navigation_started(c.clone()).unwrap();
+ assert_eq!(channel.navigation_finished(&a), Ok(false));
+ assert_eq!(channel.navigation_finished(&b), Ok(false));
+ assert!(channel.output_is_suspended());
+ assert_eq!(channel.navigation_finished(&c), Ok(true));
+ assert_eq!(channel.navigation_finished(&c), Ok(false));
+ assert_eq!(channel.inflight_navigation_count(), 0);
}
#[test]
diff --git a/moli-protocol/src/conn/state/fetch.rs b/moli-protocol/src/conn/state/fetch.rs
index 12213759b..1c9b308a7 100644
--- a/moli-protocol/src/conn/state/fetch.rs
+++ b/moli-protocol/src/conn/state/fetch.rs
@@ -16,6 +16,7 @@ use super::super::fetch_support::{
pub(super) use super::super::fetch_support::{
FetchInterceptionPattern, FetchRequestStage, FetchResourceTypeFilter, OpenBodyStreamError,
};
+use super::DocumentNavigationToken;
use super::navigation_outcome::NavigationDispatchState;
use super::runtime_slot::TargetRuntimeSlot;
use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
@@ -34,6 +35,36 @@ pub struct TargetFetchState {
}
impl TargetFetchState {
+ fn take_superseded_document_navigations(
+ &mut self,
+ current: &DocumentNavigationToken,
+ ) -> Vec<(Option<DocumentNavigationToken>, NavigationDispatchState)> {
+ let mut retired = Vec::new();
+ for (id, pending) in self
+ .pending_fetch_navigations
+ .extract_if(|_, pending| pending.document_navigation_token.as_ref() != Some(current))
+ {
+ self.pending_fetch_request_ids.remove(&id);
+ retired.push((pending.document_navigation_token, pending.navigation));
+ }
+ for (id, pending) in self
+ .pending_fetch_auth_navigations
+ .extract_if(|_, pending| pending.document_navigation_token.as_ref() != Some(current))
+ {
+ self.pending_fetch_request_ids.remove(&id);
+ retired.push((pending.document_navigation_token, pending.navigation));
+ }
+ for transfer in self
+ .pending_fetch_response_transfers
+ .drain_superseded(current)
+ {
+ self.pending_fetch_request_ids
+ .remove(transfer.fetch_request_id());
+ retired.push(transfer.into_navigation());
+ }
+ retired
+ }
+
fn pending_action_matches(
pending: &PendingSubresourceFetchRequest,
session_id: Option<&str>,
@@ -643,20 +674,45 @@ impl TargetFetchState {
) -> PendingFetchResponseBodyStreamRead {
let request_id = completed.request_id().to_owned();
let handle = completed.handle().to_owned();
- match completed.into_completed() {
- Ok((bytes, eof, transfer)) => {
- self.register_pending_fetch_response_transfer(request_id, transfer);
- if eof {
- runtime_slot.insert_io_stream(handle, Vec::new(), 0);
- }
- PendingFetchResponseBodyStreamRead::Read { bytes, eof }
- }
+ let (transfer, read) = match completed.into_completed() {
+ Ok((bytes, eof, transfer)) => (
+ transfer,
+ PendingFetchResponseBodyStreamRead::Read { bytes, eof },
+ ),
Err(completed) => {
let (transfer, message) = *completed;
- self.register_pending_fetch_response_transfer(request_id, transfer);
- PendingFetchResponseBodyStreamRead::Failed(message)
+ (
+ transfer,
+ PendingFetchResponseBodyStreamRead::Failed(message),
+ )
+ }
+ };
+ if let Some(token) = transfer.navigation_token()
+ && !runtime_slot
+ .page_slot()
+ .accepts_pending_document_navigation_event(token)
+ {
+ self.pending_fetch_request_ids.remove(&request_id);
+ match runtime_slot.finish_renderer_document_navigation(token) {
+ Ok(finish) => {
+ debug_assert!(finish.released_output.is_empty());
+ debug_assert!(finish.renderer_call_replacements.is_none());
+ }
+ Err(error) => {
+ tracing::debug!(%error, "renderer channel closed before obsolete body read completed")
+ }
}
+ let (_, navigation) = transfer.into_navigation();
+ return PendingFetchResponseBodyStreamRead::SupersededNavigation(Box::new(navigation));
+ }
+ self.register_pending_fetch_response_transfer(request_id, transfer);
+ if matches!(
+ read,
+ PendingFetchResponseBodyStreamRead::Read { eof: true, .. }
+ ) {
+ runtime_slot.insert_io_stream(handle, Vec::new(), 0);
}
+ read
}
pub(crate) fn close_pending_fetch_response_body_stream(&mut self, handle: &str) -> bool {
@@ -1853,6 +1909,13 @@ impl TargetFetchOwner {
}
}
+ pub(crate) fn take_superseded_document_navigations(
+ &mut self,
+ current: &DocumentNavigationToken,
+ ) -> Vec<(Option<DocumentNavigationToken>, NavigationDispatchState)> {
+ self.pending.take_superseded_document_navigations(current)
+ }
+
pub(crate) fn consume_pending_request_action(
&mut self,
request_id: &str,
@@ -2211,6 +2274,7 @@ impl TargetFetchOwner {
#[cfg(test)]
mod tests {
use super::*;
+ mod supersession;
use crate::conn::{
CapturedBody, FetchAuthChallenge, NavigationResultProjection,
PendingSubresourceFetchAuthStage, PendingSubresourceFetchAuthStageChain,
diff --git a/moli-protocol/src/conn/state/fetch/tests/supersession.rs b/moli-protocol/src/conn/state/fetch/tests/supersession.rs
new file mode 100644
index 000000000..daa9536ca
--- /dev/null
+++ b/moli-protocol/src/conn/state/fetch/tests/supersession.rs
@@ -0,0 +1,176 @@
+use super::*;
+use moli_fetch::{FetchCancelHandle, NetworkObservationJournal, StreamingRawResponse};
+use tokio::sync::{mpsc, oneshot};
+
+fn navigation(token: &DocumentNavigationToken, id: &str) -> NavigationDispatchState {
+ let mut navigation = pending_fetch_auth_navigation(id, Some("SID-A")).navigation;
+ navigation.loader_id.clone_from(&token.loader_id);
+ navigation.frame_id.clone_from(&token.target_id);
+ navigation
+}
+
+fn request(token: &DocumentNavigationToken, id: &str) -> PendingFetchNavigation {
+ PendingFetchNavigation {
+ fetch_request_id: id.to_owned(),
+ interception_session_id: Some("SID-A".to_owned()),
+ document_navigation_token: Some(token.clone()),
+ navigation: navigation(token, id),
+ request_cookie_report: None,
+ intercept_response: false,
+ response_stage_url_match_policy: ResponseStageUrlMatchPolicy::AlreadyMatched,
+ auth_required_blocked_intercepts: Vec::new(),
+ }
+}
+
+struct TestStream {
+ body: DocumentBodySource,
+ cancellation: FetchCancelHandle,
+ chunks: mpsc::UnboundedSender<Vec<u8>>,
+ completion: oneshot::Sender<anyhow::Result<()>>,
+}
+
+fn stream_body() -> TestStream {
+ let (chunks, chunks_rx) = mpsc::unbounded_channel();
+ let (completion, completion_rx) = oneshot::channel();
+ let cancellation = FetchCancelHandle::new();
+ let response = StreamingRawResponse::new_with_head(
+ PendingFetchAuthNavigation::test_auth_response(test_url("body"))
+ .response()
+ .head(),
+ chunks_rx,
+ cancellation.clone(),
+ completion_rx,
+ );
+ TestStream {
+ body: DocumentBodySource::StreamingRaw {
+ requested_url: test_url("body"),
+ request_method: "GET".to_owned(),
+ request_headers: Default::default(),
+ response,
+ network_observation_journal: NetworkObservationJournal::default(),
+ body_progress_source: Default::default(),
+ },
+ cancellation,
+ chunks,
+ completion,
+ }
+}
+
+#[test]
+fn supersession_retires_all_document_pause_kinds_but_keeps_current_and_subresources() {
+ for open_body in [false, true] {
+ let mut runtime = TargetRuntimeSlot::default();
+ let mut fetch = TargetFetchState::default();
+ let request_token = runtime.start_document_navigation("TID".into(), "LID-request".into());
+ fetch.register_pending_fetch_navigation_request(request(&request_token, "request"));
+ let auth_token = runtime.start_document_navigation("TID".into(), "LID-auth".into());
+ let mut auth = pending_fetch_auth_navigation("auth", Some("SID-other"));
+ auth.document_navigation_token = Some(auth_token.clone());
+ fetch.register_pending_fetch_auth_navigation("auth".into(), auth);
+ let response_token = runtime.start_document_navigation("TID".into(), "LID-response".into());
+ let stream = stream_body();
+ fetch.register_pending_fetch_response_navigation(
+ "response".into(),
+ Some(response_token.clone()),
+ navigation(&response_token, "response"),
+ stream.body,
+ );
+ if open_body {
+ fetch
+ .open_pending_fetch_response_body_stream(&mut runtime, "response", "stream".into())
+ .unwrap();
+ }
+ let current = runtime.start_document_navigation("TID".into(), "LID-current".into());
+ fetch.register_pending_fetch_navigation_request(request(&current, "current"));
+ fetch.register_pending_subresource_fetch_request(
+ "xhr".into(),
+ pending_subresource_fetch(1, Some("SID-A")),
+ );
+
+ let retired = fetch.take_superseded_document_navigations(&current);
+ let tokens = retired
+ .into_iter()
+ .map(|(token, _)| token.unwrap())
+ .collect::<HashSet<_>>();
+ assert_eq!(
+ tokens,
+ HashSet::from([request_token, auth_token, response_token])
+ );
+ assert_eq!(
+ fetch.pending_fetch_request_ids,
+ HashSet::from(["current".into(), "xhr".into()])
+ );
+ assert!(fetch.pending_fetch_response_transfers.is_empty());
+ assert!(
+ stream.cancellation.is_cancelled(),
+ "retirement must cancel the transport as well as drop routing metadata"
+ );
+ assert!(fetch.pending_fetch_navigations.contains_key("current"));
+ assert!(fetch.pending_subresource_fetches.contains_key("xhr"));
+ assert!(
+ fetch
+ .take_superseded_document_navigations(&current)
+ .is_empty(),
+ "retirement is once-only"
+ );
+ }
+}
+
+#[tokio::test]
+async fn late_body_read_success_and_failure_cannot_restore_superseded_interception() {
+ for succeeds in [false, true] {
+ let mut runtime = TargetRuntimeSlot::default();
+ let mut fetch = TargetFetchState::default();
+ let old = runtime.start_document_navigation("TID".into(), "LID-old".into());
+ let stream = stream_body();
+ runtime
+ .page_slot_mut()
+ .add_document_navigation_cancellation(&old, stream.cancellation.clone());
+ fetch.register_pending_fetch_response_navigation(
+ "response".into(),
+ Some(old.clone()),
+ navigation(&old, "response"),
+ stream.body,
+ );
+ fetch
+ .open_pending_fetch_response_body_stream(&mut runtime, "response", "stream".into())
+ .unwrap();
+ let PendingFetchResponseBodyStreamReadStart::Pending(read) =
+ fetch.start_pending_fetch_response_body_stream_read("stream", None, None)
+ else {
+ panic!("body read should start");
+ };
+ let current = runtime.start_document_navigation("TID".into(), "LID-current".into());
+ assert!(stream.cancellation.is_cancelled());
+ assert!(
+ fetch
+ .take_superseded_document_navigations(&current)
+ .is_empty(),
+ "the IO task owns A's terminal reply while it holds the body"
+ );
+ runtime
+ .finish_renderer_document_navigation(&current)
+ .unwrap();
+ assert!(!runtime.renderer_document_navigation_is_suspended());
+ if succeeds {
+ stream.chunks.send(b"body".to_vec()).unwrap();
+ }
+ drop(stream.chunks);
+ stream
+ .completion
+ .send(if succeeds {
+ Ok(())
+ } else {
+ Err(moli_fetch::FetchCancelled.into())
+ })
+ .unwrap();
+ let completed = read.wait().await;
+ assert!(matches!(
+ fetch.finish_pending_fetch_response_body_stream_read(&mut runtime, completed),
+ PendingFetchResponseBodyStreamRead::SupersededNavigation(_)
+ ));
+ assert!(fetch.pending_fetch_request_ids.is_empty());
+ assert!(fetch.pending_fetch_response_transfers.is_empty());
+ assert!(!runtime.renderer_document_navigation_is_suspended());
+ }
+}
diff --git a/moli-protocol/src/conn/state/page_slot.rs b/moli-protocol/src/conn/state/page_slot.rs
index 1df1f0401..f7adf205f 100644
--- a/moli-protocol/src/conn/state/page_slot.rs
+++ b/moli-protocol/src/conn/state/page_slot.rs
@@ -690,6 +690,22 @@ impl TargetPageSlot {
.and_then(PendingNavigationRequest::cancellation_handle)
}
+ pub(crate) fn add_document_navigation_cancellation(
+ &mut self,
+ token: &DocumentNavigationToken,
+ cancellation: moli_fetch::FetchCancelHandle,
+ ) {
+ if let Some(request) = self
+ .pending_navigation_request
+ .as_mut()
+ .filter(|request| request.matches(token) && !request.committed)
+ {
+ request.cancellation_handles.push(cancellation);
+ } else {
+ cancellation.cancel();
+ }
+ }
+
/// Claims the exact request's sole background completion and returns its
/// cancellation authority. Rejection leaves the request unchanged; the
/// caller still owns (and must drop) any rejected response.
diff --git a/moli-protocol/src/domains/fetch/tests/mod.rs b/moli-protocol/src/domains/fetch/tests/mod.rs
index 183abcd44..e48038cb3 100644
--- a/moli-protocol/src/domains/fetch/tests/mod.rs
+++ b/moli-protocol/src/domains/fetch/tests/mod.rs
@@ -325,6 +325,7 @@ mod navigation_auth;
mod navigation_control;
mod navigation_response_stage;
mod navigation_subresource;
+mod navigation_supersession;
mod runtime_auth_response;
mod runtime_fetch;
mod runtime_websocket;
diff --git a/moli-protocol/src/domains/fetch/tests/navigation_response_stage.rs b/moli-protocol/src/domains/fetch/tests/navigation_response_stage.rs
index 47d5972d4..8a089f8f0 100644
--- a/moli-protocol/src/domains/fetch/tests/navigation_response_stage.rs
+++ b/moli-protocol/src/domains/fetch/tests/navigation_response_stage.rs
@@ -959,6 +959,16 @@ async fn assert_interleaved_response_heads(pause_old_document: bool) {
"params": { "url": format!("http://{addr}/second") }
}))
.await;
+ let superseded = take_response_by_id(&mut ctx, 365);
+ assert!(superseded.get("error").is_none());
+ assert_eq!(superseded["result"]["errorText"], "net::ERR_ABORTED");
+ let failed = ctx.take_one();
+ assert_eq!(failed["method"], "Network.loadingFailed");
+ assert_eq!(
+ failed["params"]["requestId"],
+ first_pause["params"]["networkId"]
+ );
+ assert_eq!(failed["params"]["canceled"], true);
let second_pause = take_main_document_request_pause(&mut ctx).await;
let second_request_id = second_pause["params"]["requestId"]
.as_str()
@@ -986,10 +996,14 @@ async fn assert_interleaved_response_heads(pause_old_document: bool) {
"params": { "requestId": first_request_id }
}))
.await;
- ctx.expect_result(367, json!({}), Some("SID-1"));
- let superseded = take_response_by_id(&mut ctx, 365);
- assert!(superseded.get("error").is_none());
- assert_eq!(superseded["result"]["errorText"], "net::ERR_ABORTED");
+ assert_eq!(
+ take_response_by_id(&mut ctx, 367)["error"]["message"],
+ "RequestNotFound"
+ );
+ assert!(
+ !ctx.sent.iter().any(|message| message["id"] == 365),
+ "stale actions must not reply to A twice"
+ );
assert_eq!(
ctx.conn.browser_context.as_ref().and_then(|bc| bc
.active_page_target()
diff --git a/moli-protocol/src/domains/fetch/tests/navigation_supersession.rs b/moli-protocol/src/domains/fetch/tests/navigation_supersession.rs
new file mode 100644
index 000000000..908eb19c1
--- /dev/null
+++ b/moli-protocol/src/domains/fetch/tests/navigation_supersession.rs
@@ -0,0 +1,148 @@
+use super::*;
+
+async fn start_request_pause(
+ ctx: &mut TestContext,
+ id: u64,
+ session_id: &str,
+ url: &str,
+) -> String {
+ ctx.process_async(json!({
+ "id": id, "sessionId": session_id, "method": "Page.navigate", "params": {"url": url}
+ }))
+ .await;
+ let pause = ctx
+ .sent
+ .iter()
+ .find(|message| {
+ message["method"] == "Fetch.requestPaused"
+ && message["sessionId"] == session_id
+ && message["params"]["request"]["url"] == url
+ })
+ .expect("request-stage pause");
+ pause["params"]["requestId"].as_str().unwrap().to_owned()
+}
+
+#[tokio::test]
+async fn supersession_only_retires_interceptions_owned_by_the_same_target() {
+ let mut ctx = TestContext::new();
+ let mut bc = attached_browser_context();
+ bc.insert_page_target_host(PageTargetHost::with_url(
+ "TID-2".into(),
+ Some("SID-2".into()),
+ "about:blank".into(),
+ ));
+ ctx.conn.install_browser_context_fixture_for_test(bc);
+ for (id, session) in [(1, "SID-1"), (2, "SID-2")] {
+ ctx.process_async(json!({"id": id, "sessionId": session, "method": "Fetch.enable"}))
+ .await;
+ ctx.expect_result(id, json!({}), Some(session));
+ }
+ let old = start_request_pause(&mut ctx, 3, "SID-1", "http://example.test/old").await;
+ let other = start_request_pause(&mut ctx, 4, "SID-2", "http://example.test/other").await;
+ let current = start_request_pause(&mut ctx, 5, "SID-1", "http://example.test/current").await;
+ let retired = take_response_by_id(&mut ctx, 3);
+ assert_eq!(retired["sessionId"], "SID-1");
+ assert_eq!(retired["result"]["errorText"], "net::ERR_ABORTED");
+ assert!(
+ !ctx.sent
+ .iter()
+ .any(|message| message["id"] == 4 || message["id"] == 5)
+ );
+ for (id, method, extra) in [
+ (6, "Fetch.continueRequest", json!({})),
+ (7, "Fetch.failRequest", json!({"errorReason": "Aborted"})),
+ (8, "Fetch.fulfillRequest", json!({"responseCode": 200})),
+ ] {
+ let mut params = extra;
+ params["requestId"] = json!(old);
+ ctx.process_async(
+ json!({"id": id, "sessionId": "SID-1", "method": method, "params": params}),
+ )
+ .await;
+ let reply = take_response_by_id(&mut ctx, id);
+ assert_eq!(reply["error"]["message"], "RequestNotFound");
+ assert!(
+ !ctx.sent.iter().any(|message| message["id"] == 3),
+ "late actions cannot reply to the retired navigation twice"
+ );
+ }
+ for (id, session, request, navigate_id) in [(9, "SID-1", current, 5), (10, "SID-2", other, 4)] {
+ ctx.process_async(
+ json!({"id": id, "sessionId": session, "method": "Fetch.failRequest",
+ "params": {"requestId": request, "errorReason": "Aborted"}}),
+ )
+ .await;
+ assert_eq!(take_response_by_id(&mut ctx, id)["result"], json!({}));
+ assert_eq!(
+ take_response_by_id(&mut ctx, navigate_id)["error"]["message"],
+ "Aborted"
+ );
+ assert!(
+ !ctx.conn
+ .renderer_document_navigation_is_suspended_for_session_owner(Some(session))
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn supersession_retires_an_auth_pause_without_client_credentials() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ axum::serve(
+ listener,
+ Router::new().route(
+ "/",
+ get(|| async {
+ (
+ StatusCode::UNAUTHORIZED,
+ [(WWW_AUTHENTICATE, "Basic realm=\"supersession\"")],
+ "auth required",
+ )
+ }),
+ ),
+ )
+ .await
+ .unwrap();
+ });
+ let mut ctx = TestContext::new();
+ ctx.conn
+ .install_browser_context_fixture_for_test(attached_browser_context());
+ ctx.process_async(json!({"id": 1, "sessionId": "SID-1", "method": "Fetch.enable", "params": {"handleAuthRequests": true}})).await;
+ let old = start_request_pause(&mut ctx, 2, "SID-1", &format!("http://{addr}/")).await;
+ ctx.process_async(json!({"id": 3, "sessionId": "SID-1", "method": "Fetch.continueRequest", "params": {"requestId": old}})).await;
+ assert!(
+ ctx.sent
+ .iter()
+ .any(|message| message["method"] == "Fetch.authRequired")
+ );
+ let current = start_request_pause(&mut ctx, 4, "SID-1", "http://example.test/current").await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, 2)["result"]["errorText"],
+ "net::ERR_ABORTED"
+ );
+ ctx.process_async(
+ json!({"id": 5, "sessionId": "SID-1", "method": "Fetch.continueWithAuth",
+ "params": {"requestId": old, "authChallengeResponse": {"response": "CancelAuth"}}}),
+ )
+ .await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, 5)["error"]["message"],
+ "RequestNotFound"
+ );
+ ctx.process_async(
+ json!({"id": 6, "sessionId": "SID-1", "method": "Fetch.failRequest",
+ "params": {"requestId": current, "errorReason": "Aborted"}}),
+ )
+ .await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, 4)["error"]["message"],
+ "Aborted"
+ );
+ assert!(
+ !ctx.conn
+ .renderer_document_navigation_is_suspended_for_session_owner(Some("SID-1"))
+ );
+ assert!(!ctx.sent.iter().any(|message| message["id"] == 2));
+ server.abort();
+}
diff --git a/moli-protocol/src/domains/io.rs b/moli-protocol/src/domains/io.rs
index ef1c45489..895f3e7c9 100644
--- a/moli-protocol/src/domains/io.rs
+++ b/moli-protocol/src/domains/io.rs
@@ -116,7 +116,7 @@ pub(crate) fn complete_pending_io_command(
let read = conn.finish_pending_fetch_response_body_stream_read_for_stream_owner(
session_id, *completed,
);
- read_fetch_response_body_stream_output_plan(read)
+ read_fetch_response_body_stream_output_plan(conn, read)
}
CompletedIoCommandKind::ResolveBlob(completed) => {
complete_resolve_blob_command(conn, session_id, completed)
@@ -278,6 +278,7 @@ fn complete_read_blob_command(
}
fn read_fetch_response_body_stream_output_plan(
+ conn: &mut CdpConnection,
read: PendingFetchResponseBodyStreamRead,
) -> CommandOutputPlan {
match read {
@@ -288,6 +289,14 @@ fn read_fetch_response_body_stream_output_plan(
PendingFetchResponseBodyStreamRead::Failed(error) => {
CommandOutputPlan::error(-32000, format!("{error:#}"))
}
+ PendingFetchResponseBodyStreamRead::SupersededNavigation(navigation) => {
+ let mut plan = CommandOutputPlan::error(-32000, "StreamHandleNotFound");
+ plan.extend_background_events(super::page::superseded_intercepted_navigation_events(
+ conn,
+ &navigation,
+ ));
+ plan
+ }
}
}
diff --git a/moli-protocol/src/domains/network.rs b/moli-protocol/src/domains/network.rs
index a29076e2f..bcb921add 100644
--- a/moli-protocol/src/domains/network.rs
+++ b/moli-protocol/src/domains/network.rs
@@ -108,7 +108,7 @@ pub(crate) use main_document_progress::{
MaterializedLoadedDocumentProgress, MaterializedNavigationLoadOutcome,
emit_child_document_navigation_network_background_events,
emit_fetch_navigation_initial_request_for_pause_background_events,
- materialize_loaded_navigation_progress,
+ failed_navigation_progress_gate, materialize_loaded_navigation_progress,
materialize_navigation_failure_preserving_committed_document,
materialize_navigation_load_result, record_completed_main_document_response_body,
record_failed_main_document_response_body, record_main_document_request_body,
diff --git a/moli-protocol/src/domains/network/main_document_progress/mod.rs b/moli-protocol/src/domains/network/main_document_progress/mod.rs
index 5f8df3d8a..80ab431d0 100644
--- a/moli-protocol/src/domains/network/main_document_progress/mod.rs
+++ b/moli-protocol/src/domains/network/main_document_progress/mod.rs
@@ -274,7 +274,7 @@ impl CompletedDownloadBodyNetworkProgress {
}
}
-fn failed_navigation_progress_gate(
+pub(crate) fn failed_navigation_progress_gate(
conn: &CdpConnection,
state: &NavigationDispatchState,
error_text: &str,
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index ebbc3eed6..7b21e0454 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -165,6 +165,7 @@ pub(crate) use navigation::navigation_cookie_access_report;
pub(crate) use navigation::{
MaterializedNavigationCompletion, complete_materialized_navigation_into_buffer_async,
emit_prepared_child_frame_activity, push_superseded_navigation_result,
+ superseded_intercepted_navigation_events,
};
use prepared_navigation::{
PagePreparedSameDocumentNavigation, PagePreparedTopLevelLocationNavigation,
diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rs
index cd7890d1f..ad89a4120 100644
--- a/moli-protocol/src/domains/page/navigation.rs
+++ b/moli-protocol/src/domains/page/navigation.rs
@@ -1329,6 +1329,32 @@ pub(crate) fn push_superseded_navigation_result(
}
}
+pub(crate) fn superseded_intercepted_navigation_events(
+ conn: &mut CdpConnection,
+ state: &NavigationDispatchState,
+) -> Vec<BackgroundProtocolEvent> {
+ let mut events = Vec::new();
+ let mut progress =
+ network::failed_navigation_progress_gate(conn, state, NET_ERR_ABORTED_ERROR_TEXT);
+ network::MainDocumentProgressBackgroundEventBarrier::drain_until_body_finished_visible(
+ &mut events,
+ &mut progress,
+ );
+ network::record_failed_main_document_response_body(
+ conn,
+ state,
+ NET_ERR_ABORTED_ERROR_TEXT.to_owned(),
+ );
+ let mut output = CommandOutputBuffer::default();
+ push_superseded_navigation_result(&mut output, state);
+ events.extend(
+ output
+ .into_plan()
+ .into_background_events(state.navigate_id, state.owner.session_id()),
+ );
+ events
+}
+
fn fill_navigation_id_from_current_loader_for_route(
conn: &mut CdpConnection,
route: &CdpSessionRoute,
@@ -2798,6 +2824,11 @@ fn start_navigate_to_url_command_with_background_policy_and_request(
"TargetNotLoaded",
));
};
+ for superseded in
+ conn.take_superseded_intercepted_document_navigations(owner, &document_navigation_token)
+ {
+ out.extend(superseded_intercepted_navigation_events(conn, &superseded));
+ }
if let Some(pending) = pending_fetch_navigation.as_mut() {
pending.document_navigation_token = Some(document_navigation_token.clone());
}