eoka 0.17.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
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;

/// Pauses between checks: quick at first, so a condition that becomes true
/// soon is seen soon, then steady at the last value.
const POLL_BACKOFF: [Duration; 3] = [
    Duration::from_millis(10),
    Duration::from_millis(20),
    Duration::from_millis(50),
];

/// Whether a failed check means "not yet" rather than failure: a missing
/// element, or a lookup that a navigation or document change raced.
/// Operational failures such as a closed transport, an invalid query or an
/// ambiguous target still end the wait.
fn not_yet(error: &Error) -> bool {
    error.code() == ErrorCode::ElementNotFound
        || is_navigation_race(error)
        || matches!(
            cdp_failure(error),
            Some(CdpFailure::ContextLost | CdpFailure::NodeGone)
        )
}

/// The one polling loop behind every wait: calls `check` (pausing per
/// `POLL_BACKOFF`) until it returns `Ok(Some(value))`. Errors for which
/// [`not_yet`] holds count as a miss; others end the wait at once. The whole
/// wait, including a check in flight, ends with a timeout error after
/// `timeout`.
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))?
}

/// Wait timeouts, `wait` and `with_retry` delays use each `Duration` as given,
/// without rounding to whole milliseconds.
impl Page {
    /// Wait for an element to appear in the DOM
    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
    }

    /// Wait for a rendered element with a nonzero box and visible CSS visibility.
    /// Actions separately wait for enabled state, stability and hit testing.
    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
    }

    /// Wait for an element to disappear
    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(())),
                    // A navigation race is "not yet"; a node that is gone is hidden.
                    Err(error) if is_navigation_race(&error) => Ok(None),
                    Err(error) if element_unavailable(&error) => Ok(Some(())),
                    Err(error) => Err(error),
                }
            },
        )
        .await
    }

    /// Wait for a fixed duration
    pub async fn wait(&self, duration: Duration) {
        tokio::time::sleep(duration).await;
    }

    /// Wait for an element with specific text to appear
    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
    }

    /// Wait for the URL to contain a specific string
    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
    }

    /// Wait for the loaded top document's fetch/XHR requests to finish and stay
    /// idle for `idle`. Includes response bodies and requests started
    /// before this call. WebSockets, workers and subframes are outside this scope.
    /// Newly attached, previously untracked tabs require a full navigation or
    /// reload first; Eoka never reloads automatically. The timeout bounds the
    /// complete wait, including any pending header cleanup.
    pub async fn wait_for_network_idle(&self, idle: Duration, timeout: Duration) -> Result<()> {
        self.session.wait_for_network_idle(idle, timeout).await
    }

    /// Retry an operation multiple times with delays between attempts.
    ///
    /// Only errors for which [`Error::is_retryable`] holds are retried; any
    /// other error is returned at once. An action error is retried only when
    /// no input was sent, so a retry never repeats input that may have landed.
    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"
        )));
        // The locator engine's error for a world that stayed replaced.
        assert!(not_yet(&crate::error::classify::world_replaced()));
        assert!(!not_yet(&Error::transport("disconnected")));
        // An invalid CSS selector fails the locator query, not the wait.
        assert!(!not_yet(&Error::invalid_argument("invalid locator query")));
        // A pinned node that is gone never comes back.
        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);

        // A race that never ends stops at the deadline, with backoff between checks.
        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));
        // 10 + 20 + 50 * n: checks at 0, 10, 30, 80, 130, 180ms.
        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);
    }
}