Skip to main content

simulator_client/
error.rs

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