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