use super::{Element, Page};
use crate::action::{first_element, first_visibility, Visibility};
use crate::error::classify::{cdp_failure, element_unavailable, is_navigation_race, CdpFailure};
use crate::error::{Error, ErrorCode, Result};
use crate::LocatorSpec;
use std::time::Duration;
const POLL_BACKOFF: [Duration; 3] = [
Duration::from_millis(10),
Duration::from_millis(20),
Duration::from_millis(50),
];
fn not_yet(error: &Error) -> bool {
error.code() == ErrorCode::ElementNotFound
|| is_navigation_race(error)
|| matches!(
cdp_failure(error),
Some(CdpFailure::ContextLost | CdpFailure::NodeGone)
)
}
pub(crate) async fn poll<T, F, Fut>(
timeout: Duration,
timeout_message: String,
check: F,
) -> Result<T>
where
F: Fn() -> Fut,
Fut: std::future::Future<Output = Result<Option<T>>>,
{
tokio::time::timeout(timeout, async {
for attempt in 0.. {
match check().await {
Ok(Some(value)) => return Ok(value),
Ok(None) => {}
Err(error) if not_yet(&error) => {
tracing::debug!("wait check raced a document change: {error}");
}
Err(error) => return Err(error),
}
let pause = POLL_BACKOFF[attempt.min(POLL_BACKOFF.len() - 1)];
tokio::time::sleep(pause).await;
}
unreachable!("the attempt counter does not end")
})
.await
.map_err(|_| Error::timeout(timeout_message))?
}
impl Page {
pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<Element> {
poll(
timeout,
format!("Element '{selector}' not found within {timeout:?}"),
|| first_element(self, LocatorSpec::css(selector)),
)
.await
}
pub async fn wait_for_visible(&self, selector: &str, timeout: Duration) -> Result<Element> {
poll(
timeout,
format!("Element '{selector}' not visible within {timeout:?}"),
|| async {
match first_visibility(self, LocatorSpec::css(selector), true).await {
Ok(Visibility::Visible(element)) => Ok(element),
Ok(Visibility::Missing | Visibility::Hidden) => Ok(None),
Err(error) if element_unavailable(&error) => Ok(None),
Err(error) => Err(error),
}
},
)
.await
}
pub async fn wait_for_hidden(&self, selector: &str, timeout: Duration) -> Result<()> {
poll(
timeout,
format!("Element '{selector}' still visible after {timeout:?}"),
|| async {
match first_visibility(self, LocatorSpec::css(selector), false).await {
Ok(Visibility::Visible(_)) => Ok(None),
Ok(Visibility::Missing | Visibility::Hidden) => Ok(Some(())),
Err(error) if is_navigation_race(&error) => Ok(None),
Err(error) if element_unavailable(&error) => Ok(Some(())),
Err(error) => Err(error),
}
},
)
.await
}
pub async fn wait(&self, duration: Duration) {
tokio::time::sleep(duration).await;
}
pub async fn wait_for_text(&self, text: &str, timeout: Duration) -> Result<Element> {
poll(
timeout,
format!("Element with text '{text}' not found within {timeout:?}"),
|| first_element(self, LocatorSpec::text(text)),
)
.await
}
pub async fn wait_for_url_contains(&self, pattern: &str, timeout: Duration) -> Result<()> {
poll(
timeout,
format!("URL did not contain '{pattern}' within {timeout:?}"),
|| async {
let url = self.url().await?;
Ok(url.contains(pattern).then_some(()))
},
)
.await
}
pub async fn wait_for_network_idle(&self, idle: Duration, timeout: Duration) -> Result<()> {
self.session.wait_for_network_idle(idle, timeout).await
}
pub async fn with_retry<F, Fut, T>(
&self,
attempts: u32,
delay: Duration,
operation: F,
) -> Result<T>
where
F: Fn() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let attempts = attempts.max(1);
let mut attempt = 1;
loop {
match operation().await {
Ok(result) => return Ok(result),
Err(error) if !error.is_retryable() => return Err(error),
Err(error) if attempt >= attempts => {
return Err(Error::retry_exhausted(attempts, error))
}
Err(_) => {
attempt += 1;
tokio::time::sleep(delay).await;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
#[tokio::test(start_paused = true)]
async fn slow_command_cannot_overrun_poll_deadline() {
let start = tokio::time::Instant::now();
let result: Result<()> = poll(Duration::from_millis(100), "bounded".into(), || async {
tokio::time::sleep(Duration::from_secs(60)).await;
Ok(Some(()))
})
.await;
assert_eq!(result.unwrap_err().code(), ErrorCode::Timeout);
assert_eq!(start.elapsed(), Duration::from_millis(100));
}
#[test]
fn only_absence_and_document_changes_are_not_yet() {
assert!(not_yet(&Error::element_not_found("missing")));
assert!(not_yet(&Error::cdp(
"Runtime.evaluate",
-32000,
"Execution context was destroyed."
)));
assert!(not_yet(&Error::cdp(
"DOM.resolveNode",
-32000,
"Node with given id does not belong to the document"
)));
assert!(not_yet(&crate::error::classify::world_replaced()));
assert!(!not_yet(&Error::transport("disconnected")));
assert!(!not_yet(&Error::invalid_argument("invalid locator query")));
assert!(!not_yet(&Error::coded(
ErrorCode::TargetStale,
"pinned element no longer refers to a live node"
)));
assert!(!not_yet(&Error::coded(
ErrorCode::AmbiguousTarget,
"locator matched multiple elements"
)));
}
#[tokio::test(start_paused = true)]
async fn poll_treats_a_navigation_race_as_not_yet() {
let calls = AtomicU32::new(0);
let value = poll(Duration::from_secs(1), "raced".into(), || async {
if calls.fetch_add(1, Ordering::SeqCst) < 3 {
Err(Error::cdp(
"Runtime.evaluate",
-32000,
"Cannot find context with specified id",
))
} else {
Ok(Some(7))
}
})
.await
.unwrap();
assert_eq!(value, 7);
let calls = AtomicU32::new(0);
let start = tokio::time::Instant::now();
let error = poll::<(), _, _>(Duration::from_millis(200), "raced".into(), || async {
calls.fetch_add(1, Ordering::SeqCst);
Err(Error::cdp(
"Runtime.evaluate",
-32000,
"Execution context was destroyed.",
))
})
.await
.unwrap_err();
assert_eq!(error.code(), ErrorCode::Timeout);
assert_eq!(error.message(), "raced");
assert_eq!(start.elapsed(), Duration::from_millis(200));
assert_eq!(calls.load(Ordering::SeqCst), 6);
}
#[tokio::test]
async fn poll_ends_at_once_on_an_operational_error() {
let error = poll::<(), _, _>(Duration::from_secs(5), "never".into(), || async {
Err(Error::transport("disconnected"))
})
.await
.unwrap_err();
assert_eq!(error.code(), ErrorCode::Transport);
}
}