simulator-client 0.29.0

Async WebSocket client for the Solana simulator backtest API
Documentation
use std::{error::Error, fmt::Write, time::Duration};

use simulator_api::{BacktestError, BacktestResponse};
use thiserror::Error;
use tokio_tungstenite::tungstenite;

/// Result type returned by [`crate::BacktestClient`].
pub type BacktestClientResult<T> = Result<T, BacktestClientError>;

/// Format an error with its full `source()` chain joined by `: `.
///
/// `Display` on most error types (notably `reqwest::Error`,
/// `tokio_tungstenite::Error`, and `solana_client::client_error::Error`) only
/// emits the top-level reason, hiding the cause. Use this when logging so the
/// underlying DNS / TLS / IO detail is preserved.
pub(crate) fn err_chain(e: &(dyn Error + 'static)) -> String {
    let mut out = e.to_string();
    let mut src = e.source();
    while let Some(s) = src {
        let _ = write!(&mut out, ": {s}");
        src = s.source();
    }
    out
}

/// Error from [`crate::BacktestClient`] and the helpers built on it.
///
/// Each variant says what to do next:
///
/// - **Retry**: the call can be sent again, usually after a backoff.
/// - **Reattach**: the connection is gone but the session may still be running on the server.
///   [`crate::ManagedBacktestSession`] reattaches for you.
/// - **Stop**: sending the same thing again fails the same way. Fix the cause first.
#[derive(Debug, Error)]
#[allow(missing_docs)]
pub enum BacktestClientError {
    /// [`crate::CreateSession::into_params`] rejected the builder before anything was sent.
    /// Stop: `message` says which setting to change.
    #[error("invalid params: {message}")]
    InvalidParams { message: String },

    /// The API key (or the `User-Agent`) holds characters an HTTP header cannot carry. Stop:
    /// check the key for stray whitespace or quotes.
    #[error("invalid API key header value: {0}")]
    InvalidApiKeyHeader(#[from] tungstenite::http::header::InvalidHeaderValue),

    /// The URL passed to [`crate::SessionGeyserChannel::connect`] does not parse. Stop: pass a
    /// bare host or a full `http(s)://` or `ws(s)://` URL.
    #[error("{url} is not a usable endpoint: {source}")]
    InvalidUrl {
        url: String,
        /// Why it does not parse.
        #[source]
        source: http::uri::InvalidUri,
    },

    /// The WebSocket request for the server URL could not be built. Stop: fix the URL.
    #[error("failed to build websocket request for {url}: {source}")]
    BuildRequest {
        /// The WebSocket URL.
        url: String,
        /// Why the request could not be built.
        #[source]
        source: Box<tungstenite::Error>,
    },

    /// The WebSocket connection to the server failed.
    ///
    /// When `source` is [`tungstenite::Error::Http`] with a 4xx status other than 429, stop:
    /// 401 or 403 means the server rejected the API key. Any other cause (DNS, TLS, a refused
    /// connection, a 429 or 5xx) is worth a retry with backoff.
    #[error("websocket connect to {url} failed: {source}")]
    Connect {
        /// The WebSocket URL.
        url: String,
        /// Why the connection failed.
        #[source]
        source: Box<tungstenite::Error>,
    },

    /// A connect, send or receive did not finish within its timeout. Retry, or raise the
    /// timeout.
    #[error("timeout while {action} after {duration:?}")]
    Timeout {
        /// What timed out: `connecting`, `sending` or `receiving`.
        action: &'static str,
        duration: Duration,
    },

    /// The request could not be serialized as JSON. Stop: this is a bug, so report it.
    #[error("failed to serialize request: {source}")]
    SerializeRequest {
        #[source]
        source: serde_json::Error,
    },

    /// A message from the server is not a response this client knows. Stop: the server is
    /// likely newer than this crate, so upgrade `simulator-client`.
    #[error("failed to deserialize response: {source}; raw={raw}")]
    DeserializeResponse {
        /// The message as received.
        raw: String,
        /// Why it does not parse.
        #[source]
        source: serde_json::Error,
    },

    /// The server answered with an error. If [`BacktestError::is_terminal`] is true, the
    /// session is over: stop. Otherwise the server refused only this request: fix what the
    /// variant names and send it again.
    #[error("remote error: {0}")]
    Remote(#[from] BacktestError),

    /// The connection closed, or the call needs something the session does not have (such as
    /// an RPC endpoint).
    ///
    /// After a close the session may still be running on the server: reattach. A `reason`
    /// starting with `Restart` (close code 1012) means the server paused the session so a
    /// client can reattach, for example during a redeploy.
    #[error("websocket closed: {reason}")]
    Closed {
        /// The close code and reason the server sent, or what was missing.
        reason: String,
    },

    /// The server sent a response the call did not expect at that point, such as `completed`
    /// while waiting for a status, or several session IDs for a single-session create. Stop: use
    /// the call that matches the session, or upgrade `simulator-client` if the versions differ.
    #[error("unexpected response while {context}: {response:?}")]
    UnexpectedResponse {
        /// What the call was doing.
        context: &'static str,
        response: Box<BacktestResponse>,
    },

    /// The WebSocket failed while sending, receiving or closing. The connection is gone:
    /// reattach.
    #[error("websocket error while {action}: {source}")]
    WebSocket {
        /// What failed: `sending`, `receiving` or `closing`.
        action: &'static str,
        #[source]
        source: Box<tungstenite::Error>,
    },

    /// An HTTP request did not complete, its body did not decode, or a JSON-RPC call returned
    /// an error. Retry a network failure with backoff; a decode failure means this crate is
    /// older than the server, so upgrade it. A non-2xx status is [`Self::HttpStatus`] instead.
    #[error("HTTP request to {url} failed: {source}")]
    Http {
        url: String,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// The server answered an HTTP request with a non-2xx status.
    ///
    /// - 401 or 403: the server rejected the API key. Stop and fix the key.
    /// - 429: retry later.
    /// - Any other 4xx: `body` says what to change. Stop.
    /// - 5xx: retry later.
    #[error("HTTP {status} from {url}: {body}")]
    HttpStatus {
        url: String,
        status: reqwest::StatusCode,
        /// The response body, usually the server's error message.
        body: String,
    },
}

impl BacktestClientError {
    /// Whether making the same call again after a backoff, with nothing changed, may succeed.
    ///
    /// - `Connect`: true unless the server answered the upgrade with a 4xx other than 429.
    /// - `Timeout`, `Closed`, `WebSocket`: true. After `Closed` or `WebSocket`, reattach first.
    /// - `Remote`: as [`BacktestError::is_retryable`]. If the error is terminal, retry with a new
    ///   session.
    /// - `Http`: true for a network failure; false for a body that does not decode or a
    ///   JSON-RPC error.
    /// - `HttpStatus`: true for 429 and 5xx.
    /// - `InvalidParams`, `InvalidApiKeyHeader`, `InvalidUrl`, `BuildRequest`,
    ///   `SerializeRequest`, `DeserializeResponse`, `UnexpectedResponse`: false.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Connect { source, .. } => match source.as_ref() {
                tungstenite::Error::Http(response) => is_retryable_status(response.status()),
                _ => true,
            },
            Self::Timeout { .. } | Self::Closed { .. } | Self::WebSocket { .. } => true,
            Self::Remote(err) => err.is_retryable(),
            Self::Http { source, .. } => source
                .downcast_ref::<reqwest::Error>()
                .is_some_and(|e| !e.is_decode() && !e.is_builder()),
            Self::HttpStatus { status, .. } => is_retryable_status(*status),
            Self::InvalidParams { .. }
            | Self::InvalidApiKeyHeader(_)
            | Self::InvalidUrl { .. }
            | Self::BuildRequest { .. }
            | Self::SerializeRequest { .. }
            | Self::DeserializeResponse { .. }
            | Self::UnexpectedResponse { .. } => false,
        }
    }
}

/// A 429 or a 5xx may clear up on its own; any other status will not.
fn is_retryable_status(status: http::StatusCode) -> bool {
    status == http::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()
}