simulator-client 0.30.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;

use crate::managed::CreateError;

/// 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 session token is not a valid header value. Stop: the grant is malformed.
    #[error("the session token is not a valid header value")]
    InvalidSessionToken(#[source] tungstenite::http::header::InvalidHeaderValue),

    /// 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 server could not be reached before the session existed.
    ///
    /// From `create_session` or `attach_session`, nothing started: create again. During a run,
    /// reattach with [`crate::BacktestClient::attach_session`] within `disconnect_timeout_secs`.
    #[error("websocket closed: {reason}")]
    Closed { reason: String },

    /// The create or attach did not give a usable session. Holds only
    /// [`CreateError::LostAfterSend`], [`CreateError::EndpointUnreachable`] and
    /// [`CreateError::Protocol`]; the other [`CreateError`] variants map to
    /// [`BacktestClientError::Remote`], [`BacktestClientError::Closed`] and
    /// [`BacktestClientError::InvalidParams`].
    /// [`CreateError::LostAfterSend`] and [`CreateError::EndpointUnreachable`] are never retried.
    /// [`CreateError::Protocol`] means this crate is older than the server.
    #[error(transparent)]
    Create(CreateError),

    /// Never retried: a new session gets a new token.
    #[error("the session's endpoint rejected the token")]
    SessionTokenRejected,

    /// 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 the same call may succeed after a backoff. After `Closed` or `WebSocket`, reattach first. After `SessionTokenRejected`, use a new session.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Timeout { .. }
            | Self::Closed { .. }
            | Self::WebSocket { .. }
            | Self::SessionTokenRejected => true,
            Self::Remote(err) => err.is_retryable(),
            Self::Create(error) => error.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::InvalidSessionToken(_)
            | Self::SerializeRequest { .. }
            | Self::DeserializeResponse { .. }
            | Self::UnexpectedResponse { .. } => false,
        }
    }
}

impl From<CreateError> for BacktestClientError {
    fn from(error: CreateError) -> Self {
        match error {
            CreateError::Rejected(error) => Self::Remote(error),
            CreateError::Connection(reason) => Self::Closed { reason },
            CreateError::ParallelRequest | CreateError::SingleRequest => Self::InvalidParams {
                message: error.to_string(),
            },
            CreateError::LostAfterSend { .. }
            | CreateError::Protocol(_)
            | CreateError::EndpointUnreachable { .. } => Self::Create(error),
        }
    }
}

/// 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()
}