use std::{
sync::{atomic::Ordering, Arc},
time::Duration,
};
use serde_json::Value;
use tokio::sync::{broadcast, OwnedMutexGuard};
use super::{
destination::DestinationWatch,
dispatch::Dispatch,
locator::{resolve, Node},
perform::{self, Verification},
*,
};
use crate::{
cdp::transport::CdpMessage,
error::classify::{cdp_failure, CdpFailure},
page::ActionInput,
Error, ErrorCode, Page, Result,
};
const VALUE_SETTLE: Duration = Duration::from_millis(750);
struct Cleanup {
gate: Option<OwnedMutexGuard<()>>,
input: Option<ActionInput>,
state: Arc<ActionState>,
dispatch: Arc<Dispatch>,
}
impl Drop for Cleanup {
fn drop(&mut self) {
let Some(mut input) = self.input.take() else {
return;
};
if self.dispatch.state() == DispatchState::NotSent {
input.discard_unsent_reservations();
}
if !input.has_held_input() {
return;
}
let gate = self.gate.take();
let state = self.state.clone();
state.cleanup_failed.store(true, Ordering::Release);
crate::util::spawn_detached(async move {
let succeeded = matches!(
tokio::time::timeout(Duration::from_secs(5), input.cleanup()).await,
Ok(Ok(()))
);
state.cleanup_failed.store(!succeeded, Ordering::Release);
drop(input);
drop(gate);
});
}
}
impl Cleanup {
fn input(&mut self) -> Result<&mut ActionInput> {
self.input
.as_mut()
.ok_or_else(|| Error::cdp_msg("Action input missing"))
}
}
impl Page {
pub async fn act(&self, action: Action, options: ActionOptions) -> Result<ActionReceipt> {
self.run_action(action, options, false).await
}
pub async fn explore(&self, action: Action, options: ActionOptions) -> Result<ActionReceipt> {
self.run_action(action, options, true).await
}
async fn run_action(
&self,
action: Action,
options: ActionOptions,
exploratory: bool,
) -> Result<ActionReceipt> {
let started = tokio::time::Instant::now();
let dispatch = Arc::new(Dispatch::new(options.observer.clone()));
let mut receipt = ActionReceipt {
destination_target_id: None,
started_at_ms: timestamp(),
finished_at_ms: 0,
download_guid: None,
action: action.kind().into(),
target_id: self.target_id().into(),
outcome: ActionOutcome::NotDispatched,
dispatch: DispatchState::NotSent,
preparation_may_have_executed: false,
verification: None,
elapsed_ms: 0,
already_satisfied: false,
cleanup_pending: false,
};
let state = self.session().action_state();
let mut cleanup = Cleanup {
gate: None,
input: None,
state: state.clone(),
dispatch: dispatch.clone(),
};
let execution = async {
validate_timeout_ms(options.timeout_ms, "action")?;
if action.requires_expectation() && options.expect.is_none() && !exploratory {
return Err(Error::coded(
ErrorCode::ExpectationRequired,
"action requires an expected result",
));
}
cleanup.gate = Some(state.admit().await?);
if let Some(expect) = &options.expect {
validate_expectation(expect, 0)?;
if options.destination != Destination::NewTab
&& self.check_expectation(expect).await?
{
return Err(Error::coded(
ErrorCode::ExpectationAlreadySatisfied,
"choose a condition that proves a new result",
));
}
}
let mut destination_watch = if options.destination != Destination::Current
&& options
.expect
.as_ref()
.is_some_and(|e| !matches!(e, Expectation::DownloadStarted))
{
Some(DestinationWatch::begin(self, options.destination).await?)
} else {
None
};
dispatch.note("preparation");
cleanup.input = Some(ActionInput::acquire(self.session()).await?);
let download_frames = if matches!(options.expect, Some(Expectation::DownloadStarted)) {
self.frames()
.await?
.into_iter()
.map(|f| f.id)
.collect::<Vec<_>>()
} else {
Vec::new()
};
let main = self.session().get_frame_tree().await?.frame;
let (main_frame, previous_loader) = (main.id, main.loader_id);
let mut events = self.session().transport().subscribe();
let (node, verification) = loop {
let attempt = async {
let mut node =
perform::prepare(self, &action, &dispatch, options.wait_for_target).await?;
if matches!(action, Action::Hover { .. }) {
if let Some(node) = node.as_mut() {
node.arm_hover().await?;
}
}
let verification =
perform::perform(self, &action, node.as_ref(), cleanup.input()?, &dispatch)
.await?;
Ok((node, verification))
}
.await;
match attempt {
Ok(result) => break result,
Err(error)
if options.wait_for_target
&& dispatch.state() == DispatchState::NotSent
&& perform::retryable_preparation(&action, &error) =>
{
perform::pause().await;
}
Err(error) => return Err(error),
}
};
receipt.already_satisfied = matches!(verification, Verification::Noop);
dispatch.note("verification");
match verification {
Verification::Properties { field, expected } => {
verify_properties(&action, node.as_ref(), field, expected).await?;
receipt.verification = Some(field.into());
}
Verification::Navigation { .. } | Verification::NavigationAborted { .. }
if matches!(options.expect, Some(Expectation::DownloadStarted)) => {}
Verification::NavigationAborted { download } => {
return Err(Error::coded(
ErrorCode::NavigationAborted,
if download {
"the navigation became a download; expect DownloadStarted to wait for it"
} else {
"Chrome aborted the navigation before it committed"
},
));
}
Verification::Navigation { loader } => {
self.await_navigation(
&mut events,
loader.as_deref(),
previous_loader.as_deref(),
&main_frame,
)
.await?;
receipt.verification = Some("document_ready".into());
}
Verification::Noop => {
receipt.verification = Some("already_satisfied".into());
}
Verification::Explicit => {}
}
if let Some(Expectation::DownloadStarted) = &options.expect {
receipt.download_guid = await_download(&mut events, &download_frames).await?;
receipt.verification = Some("download_started".into());
} else if let Some(expect) = &options.expect {
let target = self
.await_expectation(expect, destination_watch.as_mut())
.await?;
receipt.destination_target_id = Some(target);
receipt.verification = Some(expect.kind().into());
}
cleanup.input()?.cleanup().await?;
cleanup.input.take();
receipt.outcome = if receipt.verification.is_some() {
ActionOutcome::VerifiedComplete
} else {
ActionOutcome::OutcomeUnknown
};
Ok(())
};
let result = tokio::time::timeout(
Duration::from_millis(options.timeout_ms.min(MAX_ACTION_TIMEOUT_MS)),
execution,
)
.await
.unwrap_or_else(|_| {
Err(Error::timeout(format!(
"Action deadline exceeded during {}",
dispatch.context()
)))
});
receipt.finished_at_ms = timestamp();
receipt.elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
receipt.dispatch = dispatch.state();
receipt.preparation_may_have_executed = dispatch.prepared();
match result {
Ok(()) => Ok(receipt),
Err(source) => {
receipt.outcome = if receipt.dispatch == DispatchState::NotSent {
ActionOutcome::NotDispatched
} else {
ActionOutcome::OutcomeUnknown
};
receipt.cleanup_pending = dispatch.state() != DispatchState::NotSent
&& cleanup
.input
.as_ref()
.is_some_and(ActionInput::has_held_input);
let code = action_code(&source);
Err(Error::action(code, receipt, source))
}
}
}
async fn await_navigation(
&self,
events: &mut Events,
loader: Option<&str>,
previous_loader: Option<&str>,
main_frame: &str,
) -> Result<()> {
loop {
let event = match events.recv().await {
Ok(event) => event,
Err(broadcast::error::RecvError::Lagged(skipped)) => {
tracing::debug!(skipped, "navigation events lagged");
let current = self.session().get_frame_tree().await?.frame;
match committed_after_lag(loader, previous_loader, current.loader_id.as_deref())
{
Some(true) => break,
Some(false) => continue,
None => {
return Err(Error::transport(format!(
"Navigation events lagged by {skipped}; commit unknown"
)))
}
}
}
Err(error @ broadcast::error::RecvError::Closed) => {
return Err(Error::transport_io(
"Navigation event stream lost",
std::io::Error::other(error),
));
}
};
if let CdpMessage::Event {
method,
params,
session_id,
} = &*event
{
if session_id.as_deref() != Some(self.session().session_id()) {
continue;
}
if (method == "Page.frameNavigated"
&& params["frame"]["parentId"].is_null()
&& loader.is_none_or(|id| params["frame"]["loaderId"] == id))
|| (method == "Page.navigatedWithinDocument"
&& loader.is_none()
&& params["frameId"] == main_frame)
{
break;
}
}
}
while !self.check_settling(&Expectation::DocumentReady).await? {
pause_for_progress(events, self.session().session_id()).await;
}
Ok(())
}
async fn await_expectation(
&self,
expect: &Expectation,
mut watch: Option<&mut DestinationWatch>,
) -> Result<String> {
loop {
let target = if let Some(watch) = watch.as_deref_mut() {
watch.check(expect).await?
} else if self.check_settling(expect).await? {
Some(self.target_id().into())
} else {
None
};
if let Some(target) = target {
return Ok(target);
}
perform::pause().await;
}
}
pub(super) async fn check_expectation(&self, expect: &Expectation) -> Result<bool> {
let (target, field, expected, contains) = match expect {
Expectation::DocumentReady => return self
.eval("document.readyState === 'interactive' || document.readyState === 'complete'")
.no_await()
.await,
Expectation::All { conditions } => {
for condition in conditions {
if !Box::pin(self.check_expectation(condition)).await? {
return Ok(false);
}
}
return Ok(true);
}
Expectation::Enabled { target, enabled } => {
(target, "disabled", Value::Bool(!enabled), false)
}
Expectation::DownloadStarted => return Ok(false),
Expectation::Focused { target } => (target, "focused", Value::Bool(true), false),
Expectation::Url { value, contains } => {
let url = self.url().await?;
return Ok(if *contains {
url.contains(value)
} else {
url == *value
});
}
Expectation::Visible { target } => (target, "visible", Value::Bool(true), false),
Expectation::Hidden { target } => (target, "visible", Value::Bool(false), false),
Expectation::Text {
target,
value,
contains,
} => (target, "text", Value::String(value.clone()), *contains),
Expectation::Value { target, value } => {
(target, "value", Value::String(value.clone()), false)
}
Expectation::Checked { target, checked } => {
(target, "checked", Value::Bool(*checked), false)
}
Expectation::Selected { target, values } => {
let mut values = values.clone();
values.sort();
values.dedup();
(target, "selected", serde_json::json!(values), false)
}
};
let Some(node) = resolve(self, target).await? else {
return Ok(matches!(expect, Expectation::Hidden { .. }));
};
let properties = node.properties().await?;
if matches!(expect, Expectation::Enabled { .. }) && properties["visible"] != true {
return Ok(false);
}
let actual = super::locator::Node::property(&properties, field);
Ok(if contains {
actual
.as_str()
.is_some_and(|text| text.contains(expected.as_str().unwrap_or_default()))
} else {
actual == expected
})
}
async fn check_settling(&self, expect: &Expectation) -> Result<bool> {
match self.check_expectation(expect).await {
Err(error)
if matches!(
cdp_failure(&error),
Some(CdpFailure::ContextLost | CdpFailure::NodeGone)
) =>
{
tracing::debug!("expectation check raced a document change: {error}");
Ok(false)
}
result => result,
}
}
pub async fn wait_for_expectation(
&self,
expectation: &Expectation,
timeout: Duration,
) -> Result<()> {
let timeout_ms = super::types::duration_to_ms(timeout);
validate_expectation(expectation, 0)?;
validate_timeout_ms(timeout_ms, "observation")?;
if matches!(expectation, Expectation::DownloadStarted) {
return Err(Error::coded(
ErrorCode::InvalidExpectation,
"download_started cannot be observed without an action",
));
}
crate::page::poll(
Duration::from_millis(timeout_ms),
"Page expectation was not satisfied".into(),
|| async { Ok(self.check_expectation(expectation).await?.then_some(())) },
)
.await
}
}
type Events = broadcast::Receiver<Arc<CdpMessage>>;
async fn verify_properties(
action: &Action,
node: Option<&Node>,
field: &str,
expected: Value,
) -> Result<()> {
let mut settled: Option<(Value, tokio::time::Instant)> = None;
loop {
if let Some(node) = node {
let properties = node.properties().await?;
if properties["connected"] != true {
return Err(Error::coded(
ErrorCode::TargetStale,
"target detached after dispatch",
));
}
let actual = Node::property(&properties, field);
if actual == expected {
return Ok(());
}
if field == "value" {
match &settled {
Some((value, since)) if *value == actual => {
if since.elapsed() >= VALUE_SETTLE {
return Err(value_mismatch(action, &expected, &actual));
}
}
_ => settled = Some((actual, tokio::time::Instant::now())),
}
}
}
perform::pause().await;
}
}
async fn await_download(events: &mut Events, frames: &[String]) -> Result<Option<String>> {
loop {
match &*events.recv().await.map_err(|error| {
Error::transport_io("Download event stream lost", std::io::Error::other(error))
})? {
CdpMessage::Event { method, params, .. }
if method == "Browser.downloadWillBegin"
&& params["frameId"]
.as_str()
.is_some_and(|id| frames.iter().any(|f| f == id)) =>
{
return Ok(params["guid"].as_str().map(str::to_owned));
}
_ => {}
}
}
}
fn validate_timeout_ms(timeout_ms: u64, what: &str) -> Result<()> {
if timeout_ms == 0 || timeout_ms > MAX_ACTION_TIMEOUT_MS {
return Err(Error::coded(
ErrorCode::InvalidTimeout,
format!("{what} timeout must be between 1 and {MAX_ACTION_TIMEOUT_MS}ms"),
));
}
Ok(())
}
fn value_mismatch(action: &Action, expected: &Value, actual: &Value) -> Error {
let chars = |v: &Value| v.as_str().map_or(0, |s| s.chars().count());
Error::value_mismatch(
action.target().map_or_else(
|| "the focused control".into(),
|t| format!("{:?}", t.query),
),
chars(expected),
chars(actual),
)
}
fn action_code(source: &Error) -> ErrorCode {
match source.code() {
ErrorCode::ElementNotFound | ErrorCode::ElementNotVisible => ErrorCode::TargetUnavailable,
ErrorCode::Timeout => ErrorCode::ActionTimeout,
ErrorCode::LaunchFailed
| ErrorCode::DecodeFailed
| ErrorCode::ChromeNotFound
| ErrorCode::InvalidUrl
| ErrorCode::ResultTooLarge
| ErrorCode::CdpError
| ErrorCode::Transport
| ErrorCode::Serialization
| ErrorCode::Io
| ErrorCode::Patching
| ErrorCode::RetryExhausted => ErrorCode::ActionFailed,
code => code,
}
}
fn validate_expectation(expectation: &Expectation, depth: usize) -> Result<()> {
if depth > 8 {
return Err(Error::coded(
ErrorCode::InvalidExpectation,
"nesting exceeds 8",
));
}
match expectation {
Expectation::All { conditions } => {
if conditions.is_empty() || conditions.len() > 16 {
return Err(Error::coded(
ErrorCode::InvalidExpectation,
"all requires 1 through 16 conditions",
));
}
for condition in conditions {
validate_expectation(condition, depth + 1)?;
}
}
Expectation::DownloadStarted if depth > 0 => {
return Err(Error::coded(
ErrorCode::InvalidExpectation,
"download_started must be a standalone event expectation",
))
}
_ => {}
}
Ok(())
}
fn timestamp() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|t| u64::try_from(t.as_millis()).unwrap_or(u64::MAX))
.unwrap_or_default()
}
fn committed_after_lag(
expected: Option<&str>,
previous: Option<&str>,
current: Option<&str>,
) -> Option<bool> {
match (expected, current) {
(Some(expected), current) => Some(current == Some(expected)),
(None, Some(current)) if previous != Some(current) => Some(true),
(None, _) => None,
}
}
#[cfg(test)]
mod code_tests {
use super::action_code;
use crate::{Error, ErrorCode};
#[test]
fn action_codes_keep_their_pre_coded_mapping() {
let cases = [
(Error::timeout("x"), ErrorCode::ActionTimeout),
(Error::input_state("x"), ErrorCode::InputState),
(
Error::coded(ErrorCode::NavigationFailed, "x"),
ErrorCode::NavigationFailed,
),
(Error::element_not_found("x"), ErrorCode::TargetUnavailable),
(
Error::element_not_visible("x"),
ErrorCode::TargetUnavailable,
),
(Error::value_mismatch("x", 1, 2), ErrorCode::ValueMismatch),
(Error::launch("x"), ErrorCode::ActionFailed),
(Error::decode("x"), ErrorCode::ActionFailed),
(Error::invalid_url("x"), ErrorCode::ActionFailed),
(Error::chrome_not_found(), ErrorCode::ActionFailed),
(Error::too_large(1), ErrorCode::ActionFailed),
(Error::cdp_msg("x"), ErrorCode::ActionFailed),
(Error::cdp("M.x", -32000, "x"), ErrorCode::ActionFailed),
(Error::transport("x"), ErrorCode::ActionFailed),
(
Error::from(std::io::Error::other("x")),
ErrorCode::ActionFailed,
),
(
Error::from(serde_json::from_str::<u8>("x").unwrap_err()),
ErrorCode::ActionFailed,
),
(Error::patching("x", "y"), ErrorCode::ActionFailed),
(
Error::retry_exhausted(2, Error::timeout("x")),
ErrorCode::ActionFailed,
),
];
for (error, expected) in cases {
assert_eq!(action_code(&error), expected, "{error}");
}
}
}
async fn pause_for_progress(
events: &mut broadcast::Receiver<std::sync::Arc<CdpMessage>>,
session: &str,
) {
let progress = async {
loop {
match events.recv().await {
Ok(event) => {
if let CdpMessage::Event {
method,
session_id: Some(source),
..
} = &*event
{
if source == session
&& matches!(
method.as_str(),
"Page.domContentEventFired"
| "Page.loadEventFired"
| "Page.lifecycleEvent"
| "Page.frameStoppedLoading"
)
{
return;
}
}
}
Err(broadcast::error::RecvError::Lagged(_)) => return,
Err(broadcast::error::RecvError::Closed) => std::future::pending().await,
}
}
};
let _ = tokio::time::timeout(perform::PAUSE, progress).await;
}
#[cfg(test)]
mod lag_tests {
use super::committed_after_lag;
#[test]
fn lagged_navigation_commit_follows_the_main_frame_loader() {
assert_eq!(
committed_after_lag(Some("new"), Some("old"), Some("new")),
Some(true)
);
assert_eq!(
committed_after_lag(Some("new"), Some("old"), Some("old")),
Some(false)
);
assert_eq!(
committed_after_lag(Some("new"), Some("old"), None),
Some(false)
);
assert_eq!(
committed_after_lag(None, Some("old"), Some("new")),
Some(true)
);
assert_eq!(committed_after_lag(None, Some("old"), Some("old")), None);
assert_eq!(committed_after_lag(None, Some("old"), None), None);
}
}