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