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