use super::{is_element_cdp_error, is_navigation_race, Element, Page};
use crate::error::{Error, Result};
use std::time::Duration;
const POLL_BACKOFF: [Duration; 3] = [
Duration::from_millis(10),
Duration::from_millis(20),
Duration::from_millis(50),
];
fn retry_if_not_found<T>(result: Result<T>) -> Result<Option<T>> {
match result {
Ok(value) => Ok(Some(value)),
Err(Error::ElementNotFound(_)) => Ok(None),
Err(error) if is_navigation_race(&error) => Ok(None),
Err(error) => Err(error),
}
}
impl Page {
async fn poll_until<T, F, Fut>(timeout: Duration, error_msg: 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.. {
if let Some(val) = check().await? {
return Ok(val);
}
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(error_msg))?
}
pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<Element> {
Self::poll_until(
timeout,
format!("Element '{selector}' not found within {timeout:?}"),
|| async { retry_if_not_found(self.find(selector).await) },
)
.await
}
pub async fn wait_for_visible(&self, selector: &str, timeout: Duration) -> Result<Element> {
Self::poll_until(
timeout,
format!("Element '{selector}' not visible within {timeout:?}"),
|| async {
let Some(element) = retry_if_not_found(self.find(selector).await)? else {
return Ok(None);
};
match element.is_visible().await {
Ok(true) => Ok(Some(element)),
Ok(false) => Ok(None),
Err(error) if is_element_cdp_error(&error) || is_navigation_race(&error) => {
Ok(None)
}
Err(error) => Err(error),
}
},
)
.await
}
pub async fn wait_for_hidden(&self, selector: &str, timeout: Duration) -> Result<()> {
Self::poll_until(
timeout,
format!("Element '{selector}' still visible after {timeout:?}"),
|| async {
match self.find(selector).await {
Err(Error::ElementNotFound(_)) => Ok(Some(())),
Ok(el) => match el.is_visible().await {
Ok(false) => Ok(Some(())),
Ok(true) => Ok(None),
Err(error) if is_navigation_race(&error) => Ok(None),
Err(error) if is_element_cdp_error(&error) => Ok(Some(())),
Err(error) => Err(error),
},
Err(error) if is_navigation_race(&error) => Ok(None),
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> {
Self::poll_until(
timeout,
format!("Element with text '{text}' not found within {timeout:?}"),
|| async { retry_if_not_found(self.find_by_text(text).await) },
)
.await
}
pub async fn wait_for_url_contains(&self, pattern: &str, timeout: Duration) -> Result<()> {
Self::poll_until(
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_url_change(&self, timeout: Duration) -> Result<String> {
tokio::time::timeout(timeout, async {
let original_url = self.url().await?;
Self::poll_until(
timeout,
format!("URL did not change from '{original_url}' within {timeout:?}"),
|| async {
let url = self.url().await?;
Ok((url != original_url).then_some(url))
},
)
.await
})
.await
.map_err(|_| Error::timeout("URL did not change before the deadline"))?
}
pub async fn wait_for_any(&self, selectors: &[&str], timeout: Duration) -> Result<Element> {
Self::poll_until(
timeout,
format!("None of the selectors found within {timeout:?}: {selectors:?}"),
|| async { retry_if_not_found(self.find_any(selectors).await) },
)
.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::RetryExhausted {
attempts,
last_error: error.to_string(),
source: Box::new(error),
})
}
Err(_) => {
attempt += 1;
tokio::time::sleep(delay).await;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn slow_command_cannot_overrun_poll_deadline() {
let start = tokio::time::Instant::now();
let result: Result<()> =
Page::poll_until(Duration::from_millis(100), "bounded".into(), || async {
tokio::time::sleep(Duration::from_secs(60)).await;
Ok(Some(()))
})
.await;
assert!(matches!(
result,
Err(Error::Coded {
code: crate::ErrorCode::Timeout,
..
})
));
assert_eq!(start.elapsed(), Duration::from_millis(100));
}
#[test]
fn test_retry_if_not_found_only_retries_absence() {
assert!(matches!(retry_if_not_found::<()>(Ok(())), Ok(Some(()))));
assert!(matches!(
retry_if_not_found::<()>(Err(Error::ElementNotFound("missing".into()))),
Ok(None)
));
assert!(matches!(
retry_if_not_found::<()>(Err(Error::transport("disconnected"))),
Err(Error::Transport { .. })
));
}
#[test]
fn test_retry_if_not_found_retries_navigation_race() {
let race = Error::cdp(
"Runtime.evaluate",
-32000,
"Execution context was destroyed.",
);
assert!(matches!(retry_if_not_found::<()>(Err(race)), Ok(None)));
let invalid = Error::cdp(
"DOM.querySelector",
-32000,
"DOMException: not a valid selector",
);
assert!(matches!(
retry_if_not_found::<()>(Err(invalid)),
Err(Error::Cdp { .. })
));
}
}