eoka 0.17.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Stable machine-readable error codes.

use std::fmt;
use std::str::FromStr;

/// Stable machine-readable code of every [`crate::Error`], returned by
/// [`crate::Error::code`]. Chrome's protocol errors, page JavaScript
/// exceptions and eoka-internal invariant failures carry `cdp_error`.
///
/// | Category | Codes | What to do |
/// |---|---|---|
/// | Deadline | `action_timeout`, `timeout`, `retry_exhausted` | Retry, or allow more time (`retry_exhausted` already retried: not transient) |
/// | Usage | `invalid_argument`, `invalid_url`, `invalid_timeout`, `invalid_expectation`, `expectation_required`, `expectation_already_satisfied`, `ambiguous_target`, `ambiguous_destination`, `unsupported_input`, `invalid_input_value`, `result_too_large` | Change the call; retrying it unchanged fails again |
/// | Target | `element_not_found`, `element_not_visible`, `target_unavailable`, `actionability_changed`, `precondition_failed`, `target_stale`, `target_crashed`, `history_unavailable`, `invalid_state` | Wait for the page; a stale handle must be found again; a crashed page needs `goto` or `reload` |
/// | Navigation | `navigation_failed`, `navigation_aborted` | Retry the navigation |
/// | Outcome | `action_failed`, `value_mismatch`, `input_state`, `cleanup_uncertain` | Inspect the receipt: input may have landed |
/// | Browser | `launch_failed`, `chrome_not_found`, `unsupported`, `download_unsupported`, `busy`, `download_busy`, `decode_failed`, `patching` | Check the environment or wait for the owner; `chrome_not_found`, `unsupported` and `download_unsupported` are permanent, the rest transient |
/// | Protocol | `cdp_error`, `transport`, `io`, `serialization` | Chrome, page JavaScript, an eoka invariant or the connection failed; `serialization` is permanent |
///
/// [`ErrorCode::is_transient`] is the authority on which codes are worth
/// retrying unchanged.
///
/// `#[non_exhaustive]`: match with a `_ =>` arm. Codes compare equal to their
/// snake_case string form, so `code == "history_unavailable"` works.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
    /// The action deadline passed.
    ActionTimeout,
    /// A wait, command or operation outside an action exceeded its deadline.
    Timeout,
    /// Chrome could not be launched or its launch was cancelled.
    LaunchFailed,
    /// No Chrome executable was found.
    ChromeNotFound,
    /// A URL could not be used.
    InvalidUrl,
    /// A checked JavaScript result exceeded its JSON byte limit.
    ResultTooLarge,
    /// Data from Chrome (base64, a stream chunk, a body) could not be decoded.
    DecodeFailed,
    /// The action failed for a reason without a more specific code.
    ActionFailed,
    /// Held input state was invalid or its cleanup failed.
    InputState,
    /// The target does not support the requested input action.
    UnsupportedInput,
    /// The value cannot be represented by the target control.
    InvalidInputValue,
    /// No element matched, or the element is not rendered.
    TargetUnavailable,
    /// A pinned element handle no longer refers to a live node.
    TargetStale,
    /// The page's renderer process crashed. Only `goto`, `reload` and history
    /// navigation reach the page until one of them loads a new renderer.
    TargetCrashed,
    /// More than one element matched a strict locator.
    AmbiguousTarget,
    /// The target stopped being actionable between preparation and input.
    ActionabilityChanged,
    /// No history entry exists at the requested offset.
    HistoryUnavailable,
    /// The action needs an explicit expectation.
    ExpectationRequired,
    /// The expectation already held before dispatch, so it proves nothing.
    ExpectationAlreadySatisfied,
    /// The expectation is malformed.
    InvalidExpectation,
    /// The action timeout is outside the accepted range.
    InvalidTimeout,
    /// A caller-supplied argument is invalid.
    InvalidArgument,
    /// More than one page satisfied the expectation.
    AmbiguousDestination,
    /// Chrome reported a navigation failure.
    NavigationFailed,
    /// Chrome aborted the navigation (it became a download or was replaced).
    NavigationAborted,
    /// A filled control settled on a different value than requested.
    ValueMismatch,
    /// Another download watch owns the browser's download configuration.
    DownloadBusy,
    /// This browser connection cannot observe downloads.
    DownloadUnsupported,
    /// The browser or connection does not support the operation.
    Unsupported,
    /// The target is not in a state that allows the operation (for example
    /// not a ready, active top-level page).
    PreconditionFailed,
    /// Another owner already holds the resource (a recorder on this target).
    Busy,
    /// The handle's own state does not allow the operation.
    InvalidState,
    /// Cleanup was not acknowledged; the resource may still be held.
    CleanupUncertain,
    /// No element matched the selector or text.
    ElementNotFound,
    /// The element exists in the DOM but is not rendered.
    ElementNotVisible,
    /// Chrome answered a protocol command with an error, page JavaScript
    /// threw, or an eoka-internal invariant failed.
    CdpError,
    /// The connection to Chrome failed.
    Transport,
    /// A value could not be serialized or deserialized as JSON.
    Serialization,
    /// A file or process operation failed.
    Io,
    /// Binary patching failed.
    Patching,
    /// Every attempt of a retried operation failed.
    RetryExhausted,
}

impl ErrorCode {
    /// Every code, for parsing.
    pub(crate) const ALL: &[Self] = &[
        Self::ActionTimeout,
        Self::Timeout,
        Self::LaunchFailed,
        Self::ChromeNotFound,
        Self::InvalidUrl,
        Self::ResultTooLarge,
        Self::DecodeFailed,
        Self::ActionFailed,
        Self::InputState,
        Self::UnsupportedInput,
        Self::InvalidInputValue,
        Self::TargetUnavailable,
        Self::TargetStale,
        Self::TargetCrashed,
        Self::AmbiguousTarget,
        Self::ActionabilityChanged,
        Self::HistoryUnavailable,
        Self::ExpectationRequired,
        Self::ExpectationAlreadySatisfied,
        Self::InvalidExpectation,
        Self::InvalidTimeout,
        Self::InvalidArgument,
        Self::AmbiguousDestination,
        Self::NavigationFailed,
        Self::NavigationAborted,
        Self::ValueMismatch,
        Self::DownloadBusy,
        Self::DownloadUnsupported,
        Self::Unsupported,
        Self::PreconditionFailed,
        Self::Busy,
        Self::InvalidState,
        Self::CleanupUncertain,
        Self::ElementNotFound,
        Self::ElementNotVisible,
        Self::CdpError,
        Self::Transport,
        Self::Serialization,
        Self::Io,
        Self::Patching,
        Self::RetryExhausted,
    ];

    /// The stable snake_case form, e.g. `"history_unavailable"`.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ActionTimeout => "action_timeout",
            Self::Timeout => "timeout",
            Self::LaunchFailed => "launch_failed",
            Self::ChromeNotFound => "chrome_not_found",
            Self::InvalidUrl => "invalid_url",
            Self::ResultTooLarge => "result_too_large",
            Self::DecodeFailed => "decode_failed",
            Self::ActionFailed => "action_failed",
            Self::InputState => "input_state",
            Self::UnsupportedInput => "unsupported_input",
            Self::InvalidInputValue => "invalid_input_value",
            Self::TargetUnavailable => "target_unavailable",
            Self::TargetStale => "target_stale",
            Self::TargetCrashed => "target_crashed",
            Self::AmbiguousTarget => "ambiguous_target",
            Self::ActionabilityChanged => "actionability_changed",
            Self::HistoryUnavailable => "history_unavailable",
            Self::ExpectationRequired => "expectation_required",
            Self::ExpectationAlreadySatisfied => "expectation_already_satisfied",
            Self::InvalidExpectation => "invalid_expectation",
            Self::InvalidTimeout => "invalid_timeout",
            Self::InvalidArgument => "invalid_argument",
            Self::AmbiguousDestination => "ambiguous_destination",
            Self::NavigationFailed => "navigation_failed",
            Self::NavigationAborted => "navigation_aborted",
            Self::ValueMismatch => "value_mismatch",
            Self::DownloadBusy => "download_busy",
            Self::DownloadUnsupported => "download_unsupported",
            Self::Unsupported => "unsupported",
            Self::PreconditionFailed => "precondition_failed",
            Self::Busy => "busy",
            Self::InvalidState => "invalid_state",
            Self::CleanupUncertain => "cleanup_uncertain",
            Self::ElementNotFound => "element_not_found",
            Self::ElementNotVisible => "element_not_visible",
            Self::CdpError => "cdp_error",
            Self::Transport => "transport",
            Self::Serialization => "serialization",
            Self::Io => "io",
            Self::Patching => "patching",
            Self::RetryExhausted => "retry_exhausted",
        }
    }

    /// Whether retrying the same call unchanged can succeed. Usage errors
    /// (invalid arguments, ambiguous selectors, missing expectations) cannot.
    pub const fn is_transient(self) -> bool {
        matches!(
            self,
            Self::ActionTimeout
                | Self::Timeout
                | Self::LaunchFailed
                | Self::DecodeFailed
                | Self::TargetUnavailable
                | Self::ActionabilityChanged
                | Self::NavigationFailed
                | Self::NavigationAborted
                | Self::DownloadBusy
                | Self::Busy
                | Self::PreconditionFailed
                | Self::ActionFailed
                | Self::ElementNotFound
                | Self::ElementNotVisible
                | Self::CdpError
                | Self::Transport
                | Self::Io
                | Self::Patching
        )
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<ErrorCode> for String {
    fn from(code: ErrorCode) -> Self {
        code.as_str().to_owned()
    }
}

impl PartialEq<str> for ErrorCode {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for ErrorCode {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<ErrorCode> for &str {
    fn eq(&self, other: &ErrorCode) -> bool {
        *self == other.as_str()
    }
}

impl serde::Serialize for ErrorCode {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl FromStr for ErrorCode {
    type Err = crate::Error;

    /// Parses the snake_case form; an unknown code is
    /// [`ErrorCode::InvalidArgument`].
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .iter()
            .copied()
            .find(|code| code.as_str() == text)
            .ok_or_else(|| crate::Error::invalid_argument(format!("unknown error code {text:?}")))
    }
}

impl<'de> serde::Deserialize<'de> for ErrorCode {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::ErrorCode;

    fn source_codes() -> Vec<&'static str> {
        include_str!("code.rs")
            .lines()
            .filter_map(|l| l.trim().strip_prefix("Self::")?.split_once(" => "))
            .map(|(_, rest)| rest.trim_matches(|c| c == '"' || c == ','))
            .collect()
    }

    /// Every code parses from its string form and through serde, and
    /// `ALL` lists each `as_str` arm once.
    #[test]
    fn every_code_round_trips() {
        let codes = source_codes();
        assert_eq!(codes.len(), ErrorCode::ALL.len());
        for text in codes {
            let code: ErrorCode = text.parse().unwrap();
            assert_eq!(code.as_str(), text);
            assert!(code == text && text == code);
            let json = serde_json::to_value(code).unwrap();
            assert_eq!(json, serde_json::json!(text));
            assert_eq!(serde_json::from_value::<ErrorCode>(json).unwrap(), code);
        }
        let unique: std::collections::HashSet<_> = ErrorCode::ALL.iter().collect();
        assert_eq!(unique.len(), ErrorCode::ALL.len());
        let error = "nope".parse::<ErrorCode>().unwrap_err();
        assert_eq!(error.code(), ErrorCode::InvalidArgument);
        let error = serde_json::from_value::<ErrorCode>(serde_json::json!("nope")).unwrap_err();
        assert_eq!(
            error.to_string(),
            "invalid_argument: unknown error code \"nope\""
        );
    }

    /// The category table in the `ErrorCode` docs lists every code.
    #[test]
    fn doc_table_lists_every_code() {
        let table: Vec<&str> = include_str!("code.rs")
            .lines()
            .filter(|l| l.starts_with("/// |"))
            .collect();
        let codes = source_codes();
        assert!(codes.len() > 30, "{codes:?}");
        for code in codes {
            let quoted = format!("`{code}`");
            assert!(
                table.iter().any(|l| l.contains(&quoted)),
                "{code} missing from the table"
            );
        }
    }
}