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, BundleDeleteRequest, BundleDeleteResponse, ControlSessionId,
10    SessionId, SnapshotSlotResponse,
11    client_identity::{ClientProduct, ClientSurface, render},
12    usage::UsageReport,
13};
14use tokio_tungstenite::{
15    connect_async,
16    tungstenite::{client::IntoClientRequest, http::HeaderValue},
17};
18
19use crate::{
20    BacktestClientError, BacktestClientResult, BacktestSession, CreateSession,
21    session::CreateRequestResult,
22    urls::{backtest_ws_url, http_base_from_ws_url},
23};
24
25const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
26
27/// Backtest WebSocket client configured with a base URL and API key.
28///
29/// Build with [`BacktestClient::builder`], which supports optional timeouts and
30/// raw message logging.
31///
32/// This is the low-level layer: every session it opens is one raw WebSocket
33/// with no reconnect and no reattach, so a dropped connection ends the run
34/// unless the caller reattaches with [`BacktestClient::attach_session`]. Most
35/// callers want [`crate::ManagedBacktestSession`], which does that for them —
36/// see the crate docs on session handoff.
37#[derive(Debug, Clone, Builder)]
38#[builder(on(String, into))]
39pub struct BacktestClient {
40    /// WebSocket endpoint. Accepts a bare hostname (normalized to
41    /// `wss://{host}/backtest`) or an explicit `ws(s)://` URL, whose
42    /// `/backtest` path is appended only if missing.
43    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
44    url: String,
45    /// API key injected as the `X-API-Key` header.
46    #[builder(default)]
47    api_key: String,
48
49    #[builder(default = ClientProduct::Sdk)]
50    product: ClientProduct,
51
52    /// The leading product token's own release, for binaries wrapping this library (the CLI
53    /// reports its crate version here); the SDK token always carries this library's.
54    product_version: Option<&'static str>,
55
56    /// Built once on first use and reused: a per-request `Client` would build a
57    /// fresh connection pool for every call.
58    #[builder(skip)]
59    http: std::sync::OnceLock<reqwest::Client>,
60
61    /// Timeout for the initial connect handshake.
62    #[builder(default = DEFAULT_CONNECT_TIMEOUT)]
63    connect_timeout: Duration,
64
65    /// Default timeout for request/response operations.
66    request_timeout: Option<Duration>,
67
68    /// Log raw inbound responses at debug level.
69    #[builder(default)]
70    log_raw: bool,
71}
72
73impl BacktestClient {
74    async fn connect(&self) -> BacktestClientResult<BacktestSession> {
75        let mut request = self.url.clone().into_client_request().map_err(|source| {
76            BacktestClientError::BuildRequest {
77                url: self.url.clone(),
78                source: Box::new(source),
79            }
80        })?;
81
82        request
83            .headers_mut()
84            .insert("X-API-Key", HeaderValue::from_str(&self.api_key)?);
85        request.headers_mut().insert(
86            reqwest::header::USER_AGENT.as_str(),
87            HeaderValue::from_str(&user_agent(
88                self.product,
89                self.product_version,
90                ClientSurface::Raw,
91            ))?,
92        );
93
94        let (stream, _) = tokio::time::timeout(self.connect_timeout, connect_async(request))
95            .await
96            .map_err(|_| BacktestClientError::Timeout {
97                action: "connecting",
98                duration: self.connect_timeout,
99            })?
100            .map_err(|source| BacktestClientError::Connect {
101                url: self.url.clone(),
102                source: Box::new(source),
103            })?;
104        Ok(BacktestSession::new(
105            stream,
106            self.request_timeout,
107            self.log_raw,
108        ))
109    }
110
111    /// Create a backtest session by connecting and sending a `CreateBacktestSession` request.
112    pub async fn create_session(
113        &self,
114        create: CreateSession,
115    ) -> BacktestClientResult<BacktestSession> {
116        let request = create.into_request()?;
117        let rpc_base_url = http_base_from_ws_url(&self.url);
118        let mut session = self.connect().await?;
119        match session
120            .create_with_request(request, rpc_base_url, None)
121            .await?
122        {
123            CreateRequestResult::Single { .. } => {}
124            CreateRequestResult::Parallel { session_ids, .. } => {
125                return Err(BacktestClientError::UnexpectedResponse {
126                    context: "creating single session",
127                    response: Box::new(BacktestResponse::SessionsCreatedV2 {
128                        control_session_id: ControlSessionId::default(),
129                        session_ids,
130                        task_ids: Vec::new(),
131                        start_slots: Vec::new(),
132                        end_slots: Vec::new(),
133                    }),
134                });
135            }
136        }
137        Ok(session)
138    }
139
140    /// Create one or many sessions and return the resulting session IDs.
141    ///
142    /// When `CreateSession.parallel` is true, this may return many IDs.
143    pub async fn create_sessions(
144        &self,
145        create: CreateSession,
146    ) -> BacktestClientResult<Vec<SessionId>> {
147        self.create_sessions_with_progress(create, |_| {}).await
148    }
149
150    /// Create one or many sessions and stream each successfully created session ID.
151    ///
152    /// `on_session_created` is called for each streamed `SessionCreated` response.
153    pub async fn create_sessions_with_progress(
154        &self,
155        create: CreateSession,
156        mut on_session_created: impl FnMut(SessionId) + Send,
157    ) -> BacktestClientResult<Vec<SessionId>> {
158        let request = create.into_request()?;
159        let rpc_base_url = http_base_from_ws_url(&self.url);
160        let mut session = self.connect().await?;
161        match session
162            .create_with_request(request, rpc_base_url, Some(&mut on_session_created))
163            .await?
164        {
165            CreateRequestResult::Single { session_id, .. } => Ok(vec![session_id]),
166            CreateRequestResult::Parallel { session_ids, .. } => Ok(session_ids),
167        }
168    }
169
170    /// Like [`Self::create_sessions`], but additionally returns the opaque
171    /// per-session `task_id` reported by the server (if any).
172    pub async fn create_sessions_with_task_ids(
173        &self,
174        create: CreateSession,
175    ) -> BacktestClientResult<Vec<(SessionId, Option<String>)>> {
176        let request = create.into_request()?;
177        let rpc_base_url = http_base_from_ws_url(&self.url);
178        let mut session = self.connect().await?;
179        match session
180            .create_with_request(request, rpc_base_url, None)
181            .await?
182        {
183            CreateRequestResult::Single {
184                session_id,
185                task_id,
186            } => Ok(vec![(session_id, task_id)]),
187            CreateRequestResult::Parallel {
188                session_ids,
189                task_ids,
190            } => Ok(session_ids.into_iter().zip(task_ids).collect()),
191        }
192    }
193
194    /// Fetch the slot ranges that can be run, from the server's
195    /// `/available-ranges` endpoint.
196    pub async fn available_ranges(&self) -> BacktestClientResult<Vec<AvailableRange>> {
197        self.fetch_available_ranges(false).await
198    }
199
200    /// Like [`Self::available_ranges`], plus the caller's own ranges available
201    /// to replay recorded account state. The two are not interchangeable, so
202    /// callers planning a run ask for the smaller list.
203    pub async fn available_ranges_with_account_state(
204        &self,
205    ) -> BacktestClientResult<Vec<AvailableRange>> {
206        self.fetch_available_ranges(true).await
207    }
208
209    async fn fetch_available_ranges(
210        &self,
211        include_account_state: bool,
212    ) -> BacktestClientResult<Vec<AvailableRange>> {
213        let base = http_base_from_ws_url(&self.url);
214        let url = format!("{base}/available-ranges?include_account_state={include_account_state}");
215        // Forwarded (when set) so the endpoint adds this key's own ranges,
216        // keeping the client's split in sync with the server's. Omitted when
217        // unset so a keyless client gets global ranges, not an empty-key 401.
218        let mut request = self.http_client().get(&url);
219        if !self.api_key.is_empty() {
220            request = request.header("X-API-Key", &self.api_key);
221        }
222        let ranges = request
223            .send()
224            .await
225            .map_err(|e| BacktestClientError::Http {
226                url: url.clone(),
227                source: Box::new(e),
228            })?
229            .error_for_status()
230            .map_err(|e| BacktestClientError::Http {
231                url: url.clone(),
232                source: Box::new(e),
233            })?
234            .json::<Vec<AvailableRange>>()
235            .await
236            .map_err(|e| BacktestClientError::Http {
237                url: url.clone(),
238                source: Box::new(e),
239            })?;
240        Ok(ranges)
241    }
242
243    fn http_client(&self) -> &reqwest::Client {
244        self.http.get_or_init(|| {
245            reqwest::Client::builder()
246                .user_agent(user_agent(
247                    self.product,
248                    self.product_version,
249                    ClientSurface::Raw,
250                ))
251                .build()
252                .unwrap_or_default()
253        })
254    }
255
256    /// Authenticated request builder for `path`, paired with the URL for errors.
257    fn http_request(&self, method: Method, path: &str) -> (String, reqwest::RequestBuilder) {
258        let url = format!("{}/{path}", http_base_from_ws_url(&self.url));
259        let request = self
260            .http_client()
261            .request(method, &url)
262            .header("X-API-Key", &self.api_key);
263        (url, request)
264    }
265
266    /// Send `request` and decode a 2xx JSON body; a non-2xx response keeps its
267    /// body in the error.
268    async fn send_json<T: DeserializeOwned>(
269        url: String,
270        request: reqwest::RequestBuilder,
271    ) -> BacktestClientResult<T> {
272        let resp = request
273            .send()
274            .await
275            .map_err(|e| BacktestClientError::Http {
276                url: url.clone(),
277                source: Box::new(e),
278            })?;
279        let status = resp.status();
280        if !status.is_success() {
281            let body = resp.text().await.unwrap_or_default();
282            return Err(BacktestClientError::HttpStatus { url, status, body });
283        }
284        resp.json::<T>()
285            .await
286            .map_err(|e| BacktestClientError::Http {
287                url,
288                source: Box::new(e),
289            })
290    }
291
292    /// Fetch per-API-key usage metrics from the server's `/usage` endpoint.
293    ///
294    /// `since` and `until` narrow the reporting window; both default to the
295    /// server's configured window when omitted.
296    pub async fn usage(
297        &self,
298        since: Option<DateTime<Utc>>,
299        until: Option<DateTime<Utc>>,
300    ) -> BacktestClientResult<UsageReport> {
301        let (url, mut req) = self.http_request(Method::GET, "usage");
302        if let Some(t) = since {
303            req = req.query(&[(
304                "since",
305                t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
306            )]);
307        }
308        if let Some(t) = until {
309            req = req.query(&[(
310                "until",
311                t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
312            )]);
313        }
314        Self::send_json(url, req).await
315    }
316
317    /// Most-recent available snapshot slot (`GET /snapshot-slot`).
318    pub async fn get_latest_snapshot_slot(&self) -> BacktestClientResult<SnapshotSlotResponse> {
319        let (url, req) = self.http_request(Method::GET, "snapshot-slot");
320        Self::send_json(url, req).await
321    }
322
323    /// Issue a bundle build (`POST /build-bundle`); the build runs async, so
324    /// poll [`Self::get_bundle_status`] for completion.
325    pub async fn build_bundle(
326        &self,
327        request: &BundleBuildRequest,
328    ) -> BacktestClientResult<BundleBuildStatusResponse> {
329        let (url, req) = self.http_request(Method::POST, "build-bundle");
330        Self::send_json(url, req.json(request)).await
331    }
332
333    /// Delete one of this key's own bundles (`DELETE /bundles`), by kind and
334    /// exact range. A range this key does not own reads as not found.
335    pub async fn delete_bundle(
336        &self,
337        request: &BundleDeleteRequest,
338    ) -> BacktestClientResult<BundleDeleteResponse> {
339        let (url, req) = self.http_request(Method::DELETE, "bundles");
340        Self::send_json(url, req.query(request)).await
341    }
342
343    /// List this key's own bundle builds, newest first, together with the
344    /// bundles it owns (`GET /build-bundle`). Recovers the `request_id` of a
345    /// build whose submit response was lost.
346    pub async fn list_bundle_builds(
347        &self,
348        limit: Option<u32>,
349    ) -> BacktestClientResult<BundleBuildListResponse> {
350        let (url, mut req) = self.http_request(Method::GET, "build-bundle");
351        if let Some(limit) = limit {
352            req = req.query(&[("limit", limit)]);
353        }
354        Self::send_json(url, req).await
355    }
356
357    /// Fetch a build's status (`GET /build-bundle/{request_id}`).
358    pub async fn get_bundle_status(
359        &self,
360        request_id: &str,
361    ) -> BacktestClientResult<BundleBuildStatusResponse> {
362        let (url, req) = self.http_request(Method::GET, &format!("build-bundle/{request_id}"));
363        Self::send_json(url, req).await
364    }
365
366    /// Attach to an existing backtest session over the control websocket.
367    pub async fn attach_session(
368        &self,
369        session_id: SessionId,
370        last_sequence: Option<u64>,
371    ) -> BacktestClientResult<BacktestSession> {
372        let rpc_base_url = http_base_from_ws_url(&self.url);
373        let mut session = self.connect().await?;
374        session
375            .attach(session_id, last_sequence, rpc_base_url)
376            .await?;
377        Ok(session)
378    }
379}
380
381pub(crate) fn user_agent(
382    product: ClientProduct,
383    product_version: Option<&str>,
384    surface: ClientSurface,
385) -> String {
386    let sdk_version = env!("CARGO_PKG_VERSION");
387    render(
388        product,
389        surface,
390        product_version.unwrap_or(sdk_version),
391        sdk_version,
392    )
393}
394
395#[cfg(test)]
396mod tests {
397    use simulator_api::BundleKind;
398
399    use super::*;
400
401    #[test]
402    fn builder_normalizes_bare_hosts_and_keeps_full_urls() {
403        let from_host = BacktestClient::builder()
404            .url("simulator.termina.technology")
405            .build();
406        assert_eq!(from_host.url, "wss://simulator.termina.technology/backtest");
407
408        let from_full_url = BacktestClient::builder()
409            .url("ws://localhost:8900/backtest".to_string())
410            .build();
411        assert_eq!(from_full_url.url, "ws://localhost:8900/backtest");
412    }
413
414    #[test]
415    fn delete_bundle_names_the_bundle_in_the_query() {
416        // The serialized form is the wire contract, not an implementation detail.
417        let query = |kind| {
418            reqwest::Client::new()
419                .delete("http://localhost/bundles")
420                .query(&BundleDeleteRequest {
421                    start_slot: 100,
422                    end_slot: 200,
423                    kind,
424                })
425                .build()
426                .unwrap()
427                .url()
428                .query()
429                .unwrap()
430                .to_string()
431        };
432        assert_eq!(
433            query(BundleKind::Blocks),
434            "start_slot=100&end_slot=200&kind=blocks"
435        );
436        assert_eq!(
437            query(BundleKind::AccountState),
438            "start_slot=100&end_slot=200&kind=account_state"
439        );
440    }
441}