Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4878,6 +4878,187 @@ async fn stop_loading_stops_parsing_a_streaming_document() {
abort_test_cdp_server(server).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stop_loading_aborts_a_provisional_navigation() {
let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
Router::new()
.route(
"/slow",
get(|| async {
std::future::pending::<axum::response::Html<&'static str>>().await
}),
)
.route(
"/home",
get(|| async { axum::response::Html("<p id=home>home</p>") }),
),
"stop-loading-provisional",
);
let (addr, server) = spawn_test_protocol_server().await;
let (mut browser, _) = connect_async(discover_browser_websocket_url(addr).await.unwrap())
.await
.unwrap();
let target_id = create_dynamic_target(&mut browser, 1).await;
let mut sessions = Vec::new();
for id in 2..=4 {
let attached = send_cdp_command(
&mut browser,
id,
"Target.attachToTarget",
None,
json!({"targetId": target_id, "flatten": true}),
)
.await;
sessions.push(
response_by_id(&attached, id)["result"]["sessionId"]
.as_str()
.expect("attached session")
.to_owned(),
);
}
let [navigator, observer, unsubscribed] = sessions.as_slice() else {
unreachable!("three attached sessions")
};
for (id, session) in [(5, navigator), (6, observer)] {
let enabled =
send_cdp_command(&mut browser, id, "Page.enable", Some(session), json!({})).await;
assert_eq!(response_by_id(&enabled, id)["result"], json!({}));
}
send_cdp_command(
&mut browser,
7,
"Network.enable",
Some(navigator),
json!({}),
)
.await;
send_cdp_command_without_wait(
&mut browser,
8,
"Page.navigate",
Some(navigator),
json!({"url": format!("http://{fixture_addr}/home")}),
)
.await;
let mut home_stops = std::collections::HashSet::new();
let mut home_reply = false;
let home = recv_until_match(&mut browser, |message| {
if message["method"] == "Page.frameStoppedLoading"
&& message["params"]["frameId"] == target_id
{
home_stops.insert(message["sessionId"].as_str().unwrap().to_owned());
}
home_reply |= message["id"] == 8;
home_reply && home_stops.contains(navigator) && home_stops.contains(observer)
})
.await;
assert!(response_by_id(&home, 8)["error"].is_null());

let slow_url = format!("http://{fixture_addr}/slow");
for (navigate_id, caller) in [(10, observer), (20, unsubscribed)] {
send_cdp_command_without_wait(
&mut browser,
navigate_id,
"Page.navigate",
Some(navigator),
json!({"url": slow_url}),
)
.await;
let mut starts = std::collections::HashSet::new();
let mut request_id = None;
recv_until_match(&mut browser, |message| {
if message["method"] == "Page.frameStartedLoading"
&& message["params"]["frameId"] == target_id
{
starts.insert(message["sessionId"].as_str().unwrap().to_owned());
}
if message["method"] == "Network.requestWillBeSent"
&& message["params"]["request"]["url"] == slow_url
{
request_id = Some(message["params"]["requestId"].clone());
}
starts.contains(navigator) && starts.contains(observer) && request_id.is_some()
})
.await;
let request_id = request_id.unwrap();

let stop_id = navigate_id + 1;
send_cdp_command_without_wait(
&mut browser,
stop_id,
"Page.stopLoading",
Some(caller),
json!({}),
)
.await;
let (mut stopped, mut aborted, mut failed) = (false, false, false);
let mut stop_count = 0;
let mut messages = recv_until_match(&mut browser, |message| {
stopped |= message["id"] == stop_id;
aborted |= message["id"] == navigate_id;
failed |= message["method"] == "Network.loadingFailed"
&& message["params"]["requestId"] == request_id;
if message["method"] == "Page.frameStoppedLoading" {
stop_count += 1;
}
stopped && aborted && failed && stop_count >= 2
})
.await;
assert_eq!(response_by_id(&messages, stop_id)["result"], json!({}));
assert_eq!(
response_by_id(&messages, navigate_id)["result"]["errorText"],
"net::ERR_ABORTED"
);

// Also check the interrupted navigation left the loaded Document in place.
let evaluation_id = navigate_id + 2;
let evaluation = send_cdp_command(
&mut browser,
evaluation_id,
"Runtime.evaluate",
Some(navigator),
json!({"expression": "location.pathname", "returnByValue": true}),
)
.await;
assert_eq!(
response_by_id(&evaluation, evaluation_id)["result"]["result"]["value"],
"/home"
);
messages.extend(evaluation);

let mut stop_sessions = Vec::new();
for message in &messages {
assert_ne!(message["method"], "Page.frameNavigated", "{message}");
if message["method"] == "Page.frameStoppedLoading" {
assert_eq!(message["params"]["frameId"], target_id, "{message}");
stop_sessions.push(message["sessionId"].as_str().unwrap());
}
}
let mut expected = [navigator.as_str(), observer.as_str()];
expected.sort_unstable();
stop_sessions.sort_unstable();
assert_eq!(stop_sessions, expected, "stop called by {caller}");

let terminals: Vec<_> = messages
.iter()
.filter(|message| {
message["params"]["requestId"] == request_id
&& matches!(
message["method"].as_str(),
Some("Network.loadingFailed" | "Network.loadingFinished")
)
})
.collect();
assert_eq!(terminals.len(), 1, "{messages:#?}");
let terminal = terminals[0];
assert_eq!(terminal["method"], "Network.loadingFailed");
assert_eq!(terminal["params"]["type"], "Document");
assert_eq!(terminal["params"]["errorText"], "net::ERR_ABORTED");
assert_eq!(terminal["params"]["canceled"], true);
}
abort_test_cdp_server(server).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn websocket_cdp_dynamic_page_matches_chromium_browser_attach_access_modes() {
let (addr, server) = spawn_test_protocol_server().await;
Expand Down
87 changes: 87 additions & 0 deletions moli-protocol/src/conn/state_access/page_command/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,3 +470,90 @@ async fn stop_loading_captures_original_navigation_at_admission_before_a_success
})
.unwrap();
}

#[tokio::test]
async fn stop_loading_reports_provisional_stop_before_successor_start() {
let mut fixture = TestContext::new();
let mut browser = BrowserContext::new("BID-page-owned".into());
browser.set_active_target_id("TID-page-owned");
browser.attach_active_session("SID-page-owned");
fixture.with_fixture(|conn| conn.install_browser_context_fixture_for_test(browser));
fixture
.install_navigation_fixture_for_session_owner("about:blank", Some("SID-page-owned"))
.await;
fixture.enable_page_events_for_test(Some("SID-page-owned"));
fixture
.process_async(json!({"id":2103,"method":"Fetch.enable","sessionId":"SID-page-owned"}))
.await;
fixture.take_all();
let original = fixture.with_fixture(|conn| {
let owner = crate::conn::CommandOwnerScope::capture(conn, Some("SID-page-owned"));
conn.start_document_navigation_for_owner(&owner, "LOADER-provisional".into())
.unwrap()
});

let gate = fixture.hold_fixture_renderer(Some("SID-page-owned")).await;
let handle = fixture.handle();
let (mut messages, pending) = admit_stop_loading(&handle);
let mut wait = Box::pin(pending.wait());
assert!(
wait.as_mut().now_or_never().is_none(),
"Native stop is held"
);
fixture.with_fixture(|conn| {
let owner = crate::conn::CommandOwnerScope::capture(conn, Some("SID-page-owned"));
assert!(!conn.accepts_pending_document_navigation_for_owner(&owner, &original));
});

let CdpCommandTaskStep::Complete(successor) = start(
&handle,
json!({"id":2105,"method":"Page.navigate","sessionId":"SID-page-owned",
"params":{"url":"http://example.test/stop-successor"}}),
&mut Default::default(),
) else {
panic!("successor pauses at Fetch");
};
let (events, _, _) = successor.into_protocol_event_parts();
messages.extend(
events
.into_iter()
.filter_map(crate::conn::BackgroundProtocolEvent::into_wire_message),
);
assert!(
messages
.iter()
.any(|message| message["method"] == "Fetch.requestPaused")
);

drop(gate);
let completed = tokio::time::timeout(std::time::Duration::from_secs(5), wait)
.await
.unwrap();
let (events, scheduler_events) = handle
.with_state(|state| state.complete_owned_protocol_scheduler_work(completed))
.unwrap()
.into_protocol_event_parts();
fixture
.route_direct_command_output_for_test(events, scheduler_events)
.await;
fixture
.wait_for_direct_command_work_completion_for_test("original stop cleanup")
.await;
messages.extend(fixture.take_all());
let loading_events: Vec<_> = messages
.iter()
.filter(|message| message["params"]["frameId"] == "TID-page-owned")
.filter_map(|message| message["method"].as_str())
.filter(|method| {
matches!(
*method,
"Page.frameStartedLoading" | "Page.frameStoppedLoading"
)
})
.collect();
assert_eq!(
loading_events,
["Page.frameStoppedLoading", "Page.frameStartedLoading"],
"{messages:#?}"
);
}
79 changes: 79 additions & 0 deletions moli-protocol/src/conn/tests/navigation_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,85 @@ async fn replaced_navigation_cancels_queued_commit_admission_and_settles_once()
.await;
}

#[tokio::test]
async fn stop_loading_settles_the_announced_request_while_commit_is_queued() {
tokio::task::LocalSet::new()
.run_until(async {
let CommitFixture {
mut ctx,
token,
navigation,
prepared,
mut completions,
} = commit_fixture(true).await;
assert!(navigation.request_announced);
let request_id = navigation.request_id.clone().unwrap();
ctx.process_async(json!({"id":89,"method":"Network.enable","sessionId":"SID-1"}))
.await;
ctx.take_all();
ctx.with_fixture(|conn| {
conn.start_background_prepared_navigation_commit(token, navigation, prepared);
});
// Admit stop on the same owner turn, before the queued commit can run.
let stop = crate::conn::ParsedCdpCommand::from_serializable(
json!({"id":90,"method":"Page.stopLoading","sessionId":"SID-1"}),
)
.unwrap();
let CdpCommandTaskStep::Complete(stop) = ctx
.handle()
.with_state(|state| {
state.start_parsed_command_dispatch_with_context(&stop, &mut Default::default())
})
.unwrap()
else {
panic!("stop acknowledges before the queued commit");
};
let (events, scheduler_events, predecessor) = stop.into_protocol_event_parts();
assert!(predecessor.is_empty());
ctx.route_direct_command_output_for_test(events, scheduler_events)
.await;
assert_eq!(ctx.take_response_by_id(90)["result"], json!({}));

let completion =
tokio::time::timeout(std::time::Duration::from_secs(5), completions.recv())
.await
.unwrap()
.unwrap();
assert!(matches!(
&completion,
BackgroundNavigationCompletion::PreparedDocument(result)
if result.transaction.is_none() && result.navigation.is_err()
));
let outcome =
ctx.with_fixture(|conn| conn.admit_background_navigation_completion(completion));
let messages = ctx
.route_fixture_background_turns(&mut completions, outcome)
.await;
let replies: Vec<_> = messages
.iter()
.filter(|message| message["id"] == 1)
.collect();
assert_eq!(replies.len(), 1, "{messages:#?}");
assert_eq!(replies[0]["result"]["errorText"], "net::ERR_ABORTED");
let terminals: Vec<_> = messages
.iter()
.filter(|message| {
message["params"]["requestId"] == request_id
&& matches!(
message["method"].as_str(),
Some("Network.loadingFailed" | "Network.loadingFinished")
)
})
.collect();
assert_eq!(terminals.len(), 1, "{messages:#?}");
assert_eq!(terminals[0]["method"], "Network.loadingFailed");
assert_eq!(terminals[0]["params"]["errorText"], "net::ERR_ABORTED");
assert_eq!(terminals[0]["params"]["canceled"], true);
assert!(completions.try_recv().is_err());
})
.await;
}

#[tokio::test]
async fn cancelled_adoption_cannot_clean_up_a_replacement_page() {
tokio::task::LocalSet::new()
Expand Down
11 changes: 7 additions & 4 deletions moli-protocol/src/domains/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,10 +1466,13 @@ pub(crate) fn execute_immediate_devtools_page_command_with_protocol_events(
) {
let result = match command {
AutomationCommand::StopLoading(command) => {
page_command_owner(conn, &command.context).map(|owner| {
termination::stop_loading(conn, &owner);
AutomationResult::Empty
})
return match page_command_owner(conn, &command.context) {
Ok(owner) => (
Ok(AutomationResult::Empty),
termination::stop_loading(conn, &owner),
),
Err(error) => (Err(error), Vec::new()),
};
}
AutomationCommand::GetNavigationHistory(command) => {
navigation::execute_devtools_get_navigation_history_command(conn, command)
Expand Down
Loading
Loading