Skip to main content

simulator_client/
client.rs

1use std::time::Duration;
2
3use bon::Builder;
4use chrono::{DateTime, Utc};
5use reqwest::Method;
6use serde::de::DeserializeOwned;
7use simulator_api::{
8    AvailableRange, BacktestResponse, BundleBuildListResponse, BundleBuildRequest,
9    BundleBuildStatusResponse, ControlSessionId, SessionId, SnapshotSlotResponse,
10    usage::UsageReport,
11};
12use tokio_tungstenite::{
13    connect_async,
14    tungstenite::{client::IntoClientRequest, http::HeaderValue},
15};
16
17use crate::{
18    BacktestClientError, BacktestClientResult, BacktestSession, CreateSession,
19    session::CreateRequestResult,
20    urls::{backtest_ws_url, http_base_from_ws_url},
21};
22
23const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
24
25/// Backtest WebSocket client configured with a base URL and API key.
26///
27/// Build with [`BacktestClient::builder`], which supports optional timeouts and
28/// raw message logging.
29#[derive(Debug, Clone, Builder)]
30#[builder(on(String, into))]
31pub struct BacktestClient {
32    /// WebSocket endpoint. Accepts a bare hostname (normalized to
33    /// `wss://{host}/backtest`) or an explicit `ws(s)://` URL, whose
34    /// `/backtest` path is appended only if missing.
35    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
36    url: String,
37    /// API key injected as the `X-API-Key` header.
38    #[builder(default)]
39    api_key: String,
40
41    /// Timeout for the initial connect handshake.
42    #[builder(default = DEFAULT_CONNECT_TIMEOUT)]
43    connect_timeout: Duration,
44
45    /// Default timeout for request/response operations.
46    request_timeout: Option<Duration>,
47
48    /// Log raw inbound responses at debug level.
49    #[builder(default)]
50    log_raw: bool,
51}
52
53impl BacktestClient {
54    async fn connect(&self) -> BacktestClientResult<BacktestSession> {
55        let mut request = self.url.clone().into_client_request().map_err(|source| {
56            BacktestClientError::BuildRequest {
57                url: self.url.clone(),
58                source: Box::new(source),
59            }
60        })?;
61
62        request
63            .headers_mut()
64            .insert("X-API-Key", HeaderValue::from_str(&self.api_key)?);
65
66        let (stream, _) = tokio::time::timeout(self.connect_timeout, connect_async(request))
67            .await
68            .map_err(|_| BacktestClientError::Timeout {
69                action: "connecting",
70                duration: self.connect_timeout,
71            })?
72            .map_err(|source| BacktestClientError::Connect {
73                url: self.url.clone(),
74                source: Box::new(source),
75            })?;
76        Ok(BacktestSession::new(
77            stream,
78            self.request_timeout,
79            self.log_raw,
80        ))
81    }
82
83    /// Create a backtest session by connecting and sending a `CreateBacktestSession` request.
84    pub async fn create_session(
85        &self,
86        create: CreateSession,
87    ) -> BacktestClientResult<BacktestSession> {
88        let request = create.into_request()?;
89        let rpc_base_url = http_base_from_ws_url(&self.url);
90        let mut session = self.connect().await?;
91        match session
92            .create_with_request(request, rpc_base_url, None)
93            .await?
94        {
95            CreateRequestResult::Single { .. } => {}
96            CreateRequestResult::Parallel { session_ids, .. } => {
97                return Err(BacktestClientError::UnexpectedResponse {
98                    context: "creating single session",
99                    response: Box::new(BacktestResponse::SessionsCreatedV2 {
100                        control_session_id: ControlSessionId::default(),
101                        session_ids,
102                        task_ids: Vec::new(),
103                        start_slots: Vec::new(),
104                        end_slots: Vec::new(),
105                    }),
106                });
107            }
108        }
109        Ok(session)
110    }
111
112    /// Create one or many sessions and return the resulting session IDs.
113    ///
114    /// When `CreateSession.parallel` is true, this may return many IDs.
115    pub async fn create_sessions(
116        &self,
117        create: CreateSession,
118    ) -> BacktestClientResult<Vec<SessionId>> {
119        self.create_sessions_with_progress(create, |_| {}).await
120    }
121
122    /// Create one or many sessions and stream each successfully created session ID.
123    ///
124    /// `on_session_created` is called for each streamed `SessionCreated` response.
125    pub async fn create_sessions_with_progress(
126        &self,
127        create: CreateSession,
128        mut on_session_created: impl FnMut(SessionId) + Send,
129    ) -> BacktestClientResult<Vec<SessionId>> {
130        let request = create.into_request()?;
131        let rpc_base_url = http_base_from_ws_url(&self.url);
132        let mut session = self.connect().await?;
133        match session
134            .create_with_request(request, rpc_base_url, Some(&mut on_session_created))
135            .await?
136        {
137            CreateRequestResult::Single { session_id, .. } => Ok(vec![session_id]),
138            CreateRequestResult::Parallel { session_ids, .. } => Ok(session_ids),
139        }
140    }
141
142    /// Like [`Self::create_sessions`], but additionally returns the opaque
143    /// per-session `task_id` reported by the server (if any).
144    pub async fn create_sessions_with_task_ids(
145        &self,
146        create: CreateSession,
147    ) -> BacktestClientResult<Vec<(SessionId, Option<String>)>> {
148        let request = create.into_request()?;
149        let rpc_base_url = http_base_from_ws_url(&self.url);
150        let mut session = self.connect().await?;
151        match session
152            .create_with_request(request, rpc_base_url, None)
153            .await?
154        {
155            CreateRequestResult::Single {
156                session_id,
157                task_id,
158            } => Ok(vec![(session_id, task_id)]),
159            CreateRequestResult::Parallel {
160                session_ids,
161                task_ids,
162            } => Ok(session_ids.into_iter().zip(task_ids).collect()),
163        }
164    }
165
166    /// Fetch the available slot ranges from the server's `/available-ranges` endpoint.
167    pub async fn available_ranges(&self) -> BacktestClientResult<Vec<AvailableRange>> {
168        let base = http_base_from_ws_url(&self.url);
169        let url = format!("{base}/available-ranges");
170        // Forwarded (when set) so the endpoint adds this key's own ranges,
171        // keeping the client's split in sync with the server's. Omitted when
172        // unset so a keyless client gets global ranges, not an empty-key 401.
173        let mut request = reqwest::Client::new().get(&url);
174        if !self.api_key.is_empty() {
175            request = request.header("X-API-Key", &self.api_key);
176        }
177        let ranges = request
178            .send()
179            .await
180            .map_err(|e| BacktestClientError::Http {
181                url: url.clone(),
182                source: Box::new(e),
183            })?
184            .error_for_status()
185            .map_err(|e| BacktestClientError::Http {
186                url: url.clone(),
187                source: Box::new(e),
188            })?
189            .json::<Vec<AvailableRange>>()
190            .await
191            .map_err(|e| BacktestClientError::Http {
192                url: url.clone(),
193                source: Box::new(e),
194            })?;
195        Ok(ranges)
196    }
197
198    /// Authenticated request builder for `path`, paired with the URL for errors.
199    fn http_request(&self, method: Method, path: &str) -> (String, reqwest::RequestBuilder) {
200        let url = format!("{}/{path}", http_base_from_ws_url(&self.url));
201        let request = reqwest::Client::new()
202            .request(method, &url)
203            .header("X-API-Key", &self.api_key);
204        (url, request)
205    }
206
207    /// Send `request` and decode a 2xx JSON body; a non-2xx response keeps its
208    /// body in the error.
209    async fn send_json<T: DeserializeOwned>(
210        url: String,
211        request: reqwest::RequestBuilder,
212    ) -> BacktestClientResult<T> {
213        let resp = request
214            .send()
215            .await
216            .map_err(|e| BacktestClientError::Http {
217                url: url.clone(),
218                source: Box::new(e),
219            })?;
220        let status = resp.status();
221        if !status.is_success() {
222            let body = resp.text().await.unwrap_or_default();
223            return Err(BacktestClientError::HttpStatus { url, status, body });
224        }
225        resp.json::<T>()
226            .await
227            .map_err(|e| BacktestClientError::Http {
228                url,
229                source: Box::new(e),
230            })
231    }
232
233    /// Fetch per-API-key usage metrics from the server's `/usage` endpoint.
234    ///
235    /// `since` and `until` narrow the reporting window; both default to the
236    /// server's configured window when omitted.
237    pub async fn usage(
238        &self,
239        since: Option<DateTime<Utc>>,
240        until: Option<DateTime<Utc>>,
241    ) -> BacktestClientResult<UsageReport> {
242        let (url, mut req) = self.http_request(Method::GET, "usage");
243        if let Some(t) = since {
244            req = req.query(&[(
245                "since",
246                t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
247            )]);
248        }
249        if let Some(t) = until {
250            req = req.query(&[(
251                "until",
252                t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
253            )]);
254        }
255        Self::send_json(url, req).await
256    }
257
258    /// Most-recent available snapshot slot (`GET /snapshot-slot`).
259    pub async fn get_latest_snapshot_slot(&self) -> BacktestClientResult<SnapshotSlotResponse> {
260        let (url, req) = self.http_request(Method::GET, "snapshot-slot");
261        Self::send_json(url, req).await
262    }
263
264    /// Issue a bundle build (`POST /build-bundle`); the build runs async, so
265    /// poll [`Self::get_bundle_status`] for completion.
266    pub async fn build_bundle(
267        &self,
268        request: &BundleBuildRequest,
269    ) -> BacktestClientResult<BundleBuildStatusResponse> {
270        let (url, req) = self.http_request(Method::POST, "build-bundle");
271        Self::send_json(url, req.json(request)).await
272    }
273
274    /// List this key's own bundle builds, newest first (`GET /build-bundle`).
275    /// Recovers the `request_id` of a build whose submit response was lost.
276    pub async fn list_bundle_builds(
277        &self,
278        limit: Option<u32>,
279    ) -> BacktestClientResult<BundleBuildListResponse> {
280        let (url, mut req) = self.http_request(Method::GET, "build-bundle");
281        if let Some(limit) = limit {
282            req = req.query(&[("limit", limit)]);
283        }
284        Self::send_json(url, req).await
285    }
286
287    /// Fetch a build's status (`GET /build-bundle/{request_id}`).
288    pub async fn get_bundle_status(
289        &self,
290        request_id: &str,
291    ) -> BacktestClientResult<BundleBuildStatusResponse> {
292        let (url, req) = self.http_request(Method::GET, &format!("build-bundle/{request_id}"));
293        Self::send_json(url, req).await
294    }
295
296    /// Attach to an existing backtest session over the control websocket.
297    pub async fn attach_session(
298        &self,
299        session_id: SessionId,
300        last_sequence: Option<u64>,
301    ) -> BacktestClientResult<BacktestSession> {
302        let rpc_base_url = http_base_from_ws_url(&self.url);
303        let mut session = self.connect().await?;
304        session
305            .attach(session_id, last_sequence, rpc_base_url)
306            .await?;
307        Ok(session)
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn builder_normalizes_bare_hosts_and_keeps_full_urls() {
317        let from_host = BacktestClient::builder()
318            .url("simulator.termina.technology")
319            .build();
320        assert_eq!(from_host.url, "wss://simulator.termina.technology/backtest");
321
322        let from_full_url = BacktestClient::builder()
323            .url("ws://localhost:8900/backtest".to_string())
324            .build();
325        assert_eq!(from_full_url.url, "ws://localhost:8900/backtest");
326    }
327}