Skip to main content

simulator_client/
error.rs

1use std::{error::Error, fmt::Write, time::Duration};
2
3use simulator_api::{BacktestError, BacktestResponse};
4use thiserror::Error;
5use tokio_tungstenite::tungstenite;
6
7use crate::managed::CreateError;
8
9/// Result type returned by [`crate::BacktestClient`].
10pub type BacktestClientResult<T> = Result<T, BacktestClientError>;
11
12/// Format an error with its full `source()` chain joined by `: `.
13///
14/// `Display` on most error types (notably `reqwest::Error`,
15/// `tokio_tungstenite::Error`, and `solana_client::client_error::Error`) only
16/// emits the top-level reason, hiding the cause. Use this when logging so the
17/// underlying DNS / TLS / IO detail is preserved.
18pub(crate) fn err_chain(e: &(dyn Error + 'static)) -> String {
19    let mut out = e.to_string();
20    let mut src = e.source();
21    while let Some(s) = src {
22        let _ = write!(&mut out, ": {s}");
23        src = s.source();
24    }
25    out
26}
27
28/// Error from [`crate::BacktestClient`] and the helpers built on it.
29///
30/// Each variant says what to do next:
31///
32/// - **Retry**: the call can be sent again, usually after a backoff.
33/// - **Reattach**: the connection is gone but the session may still be running on the server.
34///   [`crate::ManagedBacktestSession`] reattaches for you.
35/// - **Stop**: sending the same thing again fails the same way. Fix the cause first.
36#[derive(Debug, Error)]
37#[allow(missing_docs)]
38pub enum BacktestClientError {
39    /// [`crate::CreateSession::into_params`] rejected the builder before anything was sent.
40    /// Stop: `message` says which setting to change.
41    #[error("invalid params: {message}")]
42    InvalidParams { message: String },
43
44    /// The session token is not a valid header value. Stop: the grant is malformed.
45    #[error("the session token is not a valid header value")]
46    InvalidSessionToken(#[source] tungstenite::http::header::InvalidHeaderValue),
47
48    /// A connect, send or receive did not finish within its timeout. Retry, or raise the
49    /// timeout.
50    #[error("timeout while {action} after {duration:?}")]
51    Timeout {
52        /// What timed out: `connecting`, `sending` or `receiving`.
53        action: &'static str,
54        duration: Duration,
55    },
56
57    /// The request could not be serialized as JSON. Stop: this is a bug, so report it.
58    #[error("failed to serialize request: {source}")]
59    SerializeRequest {
60        #[source]
61        source: serde_json::Error,
62    },
63
64    /// A message from the server is not a response this client knows. Stop: the server is
65    /// likely newer than this crate, so upgrade `simulator-client`.
66    #[error("failed to deserialize response: {source}; raw={raw}")]
67    DeserializeResponse {
68        /// The message as received.
69        raw: String,
70        /// Why it does not parse.
71        #[source]
72        source: serde_json::Error,
73    },
74
75    /// The server answered with an error. If [`BacktestError::is_terminal`] is true, the
76    /// session is over: stop. Otherwise the server refused only this request: fix what the
77    /// variant names and send it again.
78    #[error("remote error: {0}")]
79    Remote(#[from] BacktestError),
80
81    /// The connection closed, or the server could not be reached before the session existed.
82    ///
83    /// From `create_session` or `attach_session`, nothing started: create again. During a run,
84    /// reattach with [`crate::BacktestClient::attach_session`] within `disconnect_timeout_secs`.
85    #[error("websocket closed: {reason}")]
86    Closed { reason: String },
87
88    /// The create or attach did not give a usable session. Holds only
89    /// [`CreateError::LostAfterSend`], [`CreateError::EndpointUnreachable`] and
90    /// [`CreateError::Protocol`]; the other [`CreateError`] variants map to
91    /// [`BacktestClientError::Remote`], [`BacktestClientError::Closed`] and
92    /// [`BacktestClientError::InvalidParams`].
93    /// [`CreateError::LostAfterSend`] and [`CreateError::EndpointUnreachable`] are never retried.
94    /// [`CreateError::Protocol`] means this crate is older than the server.
95    #[error(transparent)]
96    Create(CreateError),
97
98    /// Never retried: a new session gets a new token.
99    #[error("the session's endpoint rejected the token")]
100    SessionTokenRejected,
101
102    /// The server sent a response the call did not expect at that point, such as `completed`
103    /// while waiting for a status, or several session IDs for a single-session create. Stop: use
104    /// the call that matches the session, or upgrade `simulator-client` if the versions differ.
105    #[error("unexpected response while {context}: {response:?}")]
106    UnexpectedResponse {
107        /// What the call was doing.
108        context: &'static str,
109        response: Box<BacktestResponse>,
110    },
111
112    /// The WebSocket failed while sending, receiving or closing. The connection is gone:
113    /// reattach.
114    #[error("websocket error while {action}: {source}")]
115    WebSocket {
116        /// What failed: `sending`, `receiving` or `closing`.
117        action: &'static str,
118        #[source]
119        source: Box<tungstenite::Error>,
120    },
121
122    /// An HTTP request did not complete, its body did not decode, or a JSON-RPC call returned
123    /// an error. Retry a network failure with backoff; a decode failure means this crate is
124    /// older than the server, so upgrade it. A non-2xx status is [`Self::HttpStatus`] instead.
125    #[error("HTTP request to {url} failed: {source}")]
126    Http {
127        url: String,
128        #[source]
129        source: Box<dyn std::error::Error + Send + Sync>,
130    },
131
132    /// The server answered an HTTP request with a non-2xx status.
133    ///
134    /// - 401 or 403: the server rejected the API key. Stop and fix the key.
135    /// - 429: retry later.
136    /// - Any other 4xx: `body` says what to change. Stop.
137    /// - 5xx: retry later.
138    #[error("HTTP {status} from {url}: {body}")]
139    HttpStatus {
140        url: String,
141        status: reqwest::StatusCode,
142        /// The response body, usually the server's error message.
143        body: String,
144    },
145}
146
147impl BacktestClientError {
148    /// Whether the same call may succeed after a backoff. After `Closed` or `WebSocket`, reattach first. After `SessionTokenRejected`, use a new session.
149    pub fn is_retryable(&self) -> bool {
150        match self {
151            Self::Timeout { .. }
152            | Self::Closed { .. }
153            | Self::WebSocket { .. }
154            | Self::SessionTokenRejected => true,
155            Self::Remote(err) => err.is_retryable(),
156            Self::Create(error) => error.is_retryable(),
157            Self::Http { source, .. } => source
158                .downcast_ref::<reqwest::Error>()
159                .is_some_and(|e| !e.is_decode() && !e.is_builder()),
160            Self::HttpStatus { status, .. } => is_retryable_status(*status),
161            Self::InvalidParams { .. }
162            | Self::InvalidSessionToken(_)
163            | Self::SerializeRequest { .. }
164            | Self::DeserializeResponse { .. }
165            | Self::UnexpectedResponse { .. } => false,
166        }
167    }
168}
169
170impl From<CreateError> for BacktestClientError {
171    fn from(error: CreateError) -> Self {
172        match error {
173            CreateError::Rejected(error) => Self::Remote(error),
174            CreateError::Connection(reason) => Self::Closed { reason },
175            CreateError::ParallelRequest | CreateError::SingleRequest => Self::InvalidParams {
176                message: error.to_string(),
177            },
178            CreateError::LostAfterSend { .. }
179            | CreateError::Protocol(_)
180            | CreateError::EndpointUnreachable { .. } => Self::Create(error),
181        }
182    }
183}
184
185/// A 429 or a 5xx may clear up on its own; any other status will not.
186fn is_retryable_status(status: http::StatusCode) -> bool {
187    status == http::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()
188}