eoka 0.13.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
use super::{is_element_cdp_error, is_navigation_race, Element, Page};
use crate::error::{Error, Result};
use std::time::Duration;

/// Polling interval used by wait_for_* loop iterations.
const POLL_INTERVAL: Duration = Duration::from_millis(100);

/// Convert a missing element, or a lookup that a navigation raced, into a
/// polling miss while preserving operational failures such as a closed
/// transport or malformed CDP reply.
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),
    }
}

/// Wait timeouts, `wait` and `with_retry` delays use each `Duration` as given,
/// without rounding to whole milliseconds.
impl Page {
    /// Generic polling helper — calls `check` every `POLL_INTERVAL` until it
    /// returns `Ok(Some(value))`, then returns that value. Operational errors
    /// propagate immediately; `Ok(None)` retries until the timeout.
    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 {
            loop {
                if let Some(val) = check().await? {
                    return Ok(val);
                }
                tokio::time::sleep(POLL_INTERVAL).await;
            }
        })
        .await
        .map_err(|_| Error::timeout(error_msg))?
    }

    /// Wait for an element to appear in the DOM
    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
    }

    /// 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> {
        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
    }

    /// Wait for an element to disappear
    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
    }

    /// 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> {
        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
    }

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

    /// Wait for URL to change from current URL
    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"))?
    }

    /// Wait for any of the given selectors to appear
    ///
    /// Returns the first selector that matches.
    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
    }

    /// 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::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 { .. })
        ));
    }
}