Skip to main content

simulator_client/
client.rs

1use std::time::Duration;
2
3use bon::Builder;
4use chrono::{DateTime, Utc};
5use http::{HeaderMap, StatusCode};
6use reqwest::Method;
7use serde::de::DeserializeOwned;
8use simulator_api::{
9    AvailableRange, BacktestResponse, BundleBuildListResponse, BundleBuildRequest,
10    BundleBuildStatusResponse, BundleDeleteRequest, BundleDeleteResponse,
11    DatasetCredentialsResponse, DatasetDeleteRequest, DatasetDeleteResponse,
12    DatasetJobListResponse, DatasetJobRequest, DatasetJobStatusResponse, DatasetListQuery,
13    DatasetListResponse, DepthUniverseResponse, SessionId, SnapshotSlotResponse,
14    client_identity::{ClientProduct, ClientSurface, render},
15    session_endpoint::SessionGrant,
16    usage::{SessionUsage, SessionUsagePage, UsageReport},
17};
18use tokio::time::Instant;
19
20use crate::{
21    BacktestClientError, BacktestClientResult, BacktestSession, CreateSession,
22    endpoint::{ControlConnectError, FirstConnect, connect_control},
23    error::from_json,
24    managed::{
25        CreateError, Ws,
26        grant::{
27            AttachError, GrantError, ManagementTarget, SingleCreate, request_attach,
28            request_session_grant,
29        },
30    },
31    urls::{backtest_ws_url, http_base_from_ws_url},
32};
33
34const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
35
36fn rfc3339_secs(at: DateTime<Utc>) -> String {
37    at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
38}
39
40/// Client for the server's HTTP endpoints, authenticated with an API key.
41///
42/// Build with [`BacktestClient::builder`]; only `url` is required. The API key, when set, goes
43/// out as the `X-API-Key` header on every request.
44///
45/// Drive sessions through [`crate::ManagedBacktestSession`], or
46/// [`crate::managed::ManagedParallelSession`] for a parallel run.
47///
48/// # HTTP errors
49///
50/// The methods that call the server's HTTP endpoints fail with:
51///
52/// - [`BacktestClientError::HttpStatus`] when the server answers with a non-2xx status. 401 or
53///   403 means it rejected the API key.
54/// - [`BacktestClientError::Http`] when the request fails or the body does not decode.
55#[derive(Debug, Clone, Builder)]
56#[builder(on(String, into))]
57pub struct BacktestClient {
58    /// WebSocket endpoint. Accepts a bare hostname (normalized to
59    /// `wss://{host}/backtest`) or an explicit `ws(s)://` URL, whose
60    /// `/backtest` path is appended only if missing.
61    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
62    url: String,
63    /// API key injected as the `X-API-Key` header.
64    #[builder(default)]
65    api_key: String,
66
67    /// The product named first in the `User-Agent`. Default [`ClientProduct::Sdk`]; a tool
68    /// that wraps this library sets its own.
69    #[builder(default = ClientProduct::Sdk)]
70    product: ClientProduct,
71
72    /// The release of `product`, for tools wrapping this library (the CLI reports its crate
73    /// version here). Leave it unset otherwise; the SDK token always carries this library's.
74    product_version: Option<&'static str>,
75
76    /// Built once on first use and reused: a per-request `Client` would build a
77    /// fresh connection pool for every call.
78    #[builder(skip)]
79    http: std::sync::OnceLock<reqwest::Client>,
80
81    /// Timeout for the initial connect handshake.
82    #[builder(default = DEFAULT_CONNECT_TIMEOUT)]
83    connect_timeout: Duration,
84
85    /// Default timeout for each send and receive on a session, used when a call passes
86    /// `None`. Unset: wait indefinitely.
87    request_timeout: Option<Duration>,
88
89    /// Log raw inbound responses at debug level.
90    #[builder(default)]
91    log_raw: bool,
92}
93
94impl BacktestClient {
95    fn management(&self) -> ManagementTarget {
96        ManagementTarget {
97            url: self.url.clone(),
98            api_key: self.api_key.clone(),
99            extra_headers: HeaderMap::new(),
100            user_agent: self.raw_user_agent(),
101            connect_timeout: self.connect_timeout,
102        }
103    }
104
105    fn raw_user_agent(&self) -> String {
106        user_agent(self.product, self.product_version, ClientSurface::Raw)
107    }
108
109    fn api_key_rejected(&self, status: StatusCode) -> BacktestClientError {
110        BacktestClientError::HttpStatus {
111            url: self.url.clone(),
112            status,
113            body: "API key rejected".to_owned(),
114        }
115    }
116
117    fn grant_failed(&self, error: GrantError) -> BacktestClientError {
118        match error {
119            GrantError::ApiKeyRejected(status) => self.api_key_rejected(status),
120            GrantError::Create(error) => error.into(),
121        }
122    }
123
124    fn attach_failed(&self, error: AttachError) -> BacktestClientError {
125        match error {
126            AttachError::ApiKeyRejected(status) => self.api_key_rejected(status),
127            AttachError::Connection(reason) => BacktestClientError::Closed { reason },
128            AttachError::Protocol(message) => CreateError::Protocol(message).into(),
129        }
130    }
131
132    /// Connects to the granted session's control socket. A name that does not resolve yet is
133    /// retried until the first-connect window closes.
134    async fn connect_endpoint(&self, grant: &SessionGrant) -> BacktestClientResult<Ws> {
135        let user_agent = self.raw_user_agent();
136        let first = FirstConnect::start(Instant::now());
137        loop {
138            let why = match connect_control(grant, &user_agent, self.connect_timeout).await {
139                Ok(ws) => return Ok(ws),
140                Err(ControlConnectError::TokenRejected) => {
141                    return Err(BacktestClientError::SessionTokenRejected);
142                }
143                Err(request @ ControlConnectError::Request(_)) => {
144                    return Err(CreateError::Protocol(request.to_string()).into());
145                }
146                Err(ControlConnectError::Failed(why)) => why,
147            };
148            let Some(delay) = first.retry_after(Instant::now()) else {
149                return Err(CreateError::EndpointUnreachable {
150                    session_id: grant.session_id,
151                    endpoint: grant.endpoint.clone(),
152                    reason: why,
153                }
154                .into());
155            };
156            tokio::time::sleep(delay).await;
157        }
158    }
159
160    async fn attach_granted(
161        &self,
162        grant: SessionGrant,
163        last_sequence: Option<u64>,
164    ) -> BacktestClientResult<BacktestSession> {
165        let ws = self.connect_endpoint(&grant).await?;
166        BacktestSession::attached(ws, grant, last_sequence, self.request_timeout, self.log_raw)
167            .await
168    }
169
170    /// Create one session and attach to it on its own endpoint.
171    ///
172    /// # Errors
173    ///
174    /// - [`BacktestClientError::InvalidParams`] when `create` is rejected or sets `parallel`;
175    ///   nothing is sent.
176    /// - [`BacktestClientError::HttpStatus`] with 401 or 403 for a rejected API key;
177    ///   [`BacktestClientError::Closed`] when the server cannot be reached.
178    /// - [`BacktestClientError::Create`] with [`CreateError::LostAfterSend`]: a session may have
179    ///   started and ends itself when nobody attaches.
180    /// - [`BacktestClientError::Remote`] when the server refuses the create.
181    /// - [`BacktestClientError::Create`] with [`CreateError::EndpointUnreachable`]: the session
182    ///   ends itself later.
183    /// - [`BacktestClientError::SessionTokenRejected`] when the endpoint refuses the token.
184    #[doc(hidden)]
185    pub async fn create_session(
186        &self,
187        create: CreateSession,
188    ) -> BacktestClientResult<BacktestSession> {
189        let create = SingleCreate::try_from(create.into_request()?)?;
190        let grant = request_session_grant(&self.management(), create)
191            .await
192            .map_err(|error| self.grant_failed(error))?;
193        self.attach_granted(grant, None).await
194    }
195
196    /// Fetch the slot ranges that can be run, from the server's
197    /// `/available-ranges` endpoint. Narrow the list with [`crate::filter_ranges`].
198    ///
199    /// The list is sorted by `bundle_start_slot`, oldest first. Take the newest with
200    /// `ranges.iter().max_by_key(|r| r.bundle_start_slot)`.
201    ///
202    /// # Errors
203    ///
204    /// See [HTTP errors](BacktestClient#http-errors).
205    pub async fn available_ranges(&self) -> BacktestClientResult<Vec<AvailableRange>> {
206        self.fetch_available_ranges(false).await
207    }
208
209    /// Like [`Self::available_ranges`], plus the caller's own ranges available
210    /// to replay recorded account state. The two are not interchangeable, so
211    /// callers planning a run ask for the smaller list.
212    ///
213    /// # Errors
214    ///
215    /// As [`Self::available_ranges`].
216    pub async fn available_ranges_with_account_state(
217        &self,
218    ) -> BacktestClientResult<Vec<AvailableRange>> {
219        self.fetch_available_ranges(true).await
220    }
221
222    async fn fetch_available_ranges(
223        &self,
224        include_account_state: bool,
225    ) -> BacktestClientResult<Vec<AvailableRange>> {
226        let base = http_base_from_ws_url(&self.url);
227        let url = format!("{base}/available-ranges?include_account_state={include_account_state}");
228        // Forwarded (when set) so the endpoint adds this key's own ranges,
229        // keeping the client's split in sync with the server's. Omitted when
230        // unset so a keyless client gets global ranges, not an empty-key 401.
231        let mut request = self.http_client().get(&url);
232        if !self.api_key.is_empty() {
233            request = request.header("X-API-Key", &self.api_key);
234        }
235        Self::send_json(url, request).await
236    }
237
238    fn http_client(&self) -> &reqwest::Client {
239        self.http.get_or_init(|| {
240            reqwest::Client::builder()
241                .user_agent(self.raw_user_agent())
242                .build()
243                .unwrap_or_default()
244        })
245    }
246
247    /// Authenticated request builder for `path`, paired with the URL for errors.
248    fn http_request(&self, method: Method, path: &str) -> (String, reqwest::RequestBuilder) {
249        let url = format!("{}/{path}", http_base_from_ws_url(&self.url));
250        let request = self
251            .http_client()
252            .request(method, &url)
253            .header("X-API-Key", &self.api_key);
254        (url, request)
255    }
256
257    /// Send `request` and decode a 2xx JSON body; a non-2xx response keeps its
258    /// body in the error.
259    async fn send_json<T: DeserializeOwned>(
260        url: String,
261        request: reqwest::RequestBuilder,
262    ) -> BacktestClientResult<T> {
263        let resp = request
264            .send()
265            .await
266            .map_err(|e| BacktestClientError::Http {
267                url: url.clone(),
268                source: Box::new(e),
269            })?;
270        let status = resp.status();
271        if !status.is_success() {
272            let body = resp.text().await.unwrap_or_default();
273            return Err(BacktestClientError::HttpStatus { url, status, body });
274        }
275        let body = resp.bytes().await.map_err(|e| BacktestClientError::Http {
276            url,
277            source: Box::new(e),
278        })?;
279        from_json(&body).map_err(|source| BacktestClientError::DeserializeResponse {
280            raw: String::from_utf8_lossy(&body).into_owned(),
281            source,
282        })
283    }
284
285    /// Fetch per-API-key usage metrics from the server's `/usage` endpoint.
286    ///
287    /// `since` and `until` set the reporting window; both default to the
288    /// server's configured window when omitted. The report is bucketed by UTC
289    /// day, so the window served — and the totals over it — starts at the
290    /// midnight at or before `since`.
291    ///
292    /// # Errors
293    ///
294    /// See [HTTP errors](BacktestClient#http-errors).
295    pub async fn usage(
296        &self,
297        since: Option<DateTime<Utc>>,
298        until: Option<DateTime<Utc>>,
299    ) -> BacktestClientResult<UsageReport> {
300        let (url, mut req) = self.http_request(Method::GET, "usage");
301        for (name, value) in [("since", since), ("until", until)] {
302            if let Some(value) = value {
303                req = req.query(&[(name, rfc3339_secs(value))]);
304            }
305        }
306        Self::send_json(url, req).await
307    }
308
309    /// Every session that ended in the window (`GET /usage/sessions`).
310    ///
311    /// `since` and `until` set the window as [`Self::usage`] does. Reads every
312    /// page. Completeness is the guarantee, not order: sort by `ended_at` for
313    /// chronological.
314    ///
315    /// # Errors
316    ///
317    /// See [HTTP errors](BacktestClient#http-errors).
318    pub async fn usage_sessions(
319        &self,
320        since: Option<DateTime<Utc>>,
321        until: Option<DateTime<Utc>>,
322    ) -> BacktestClientResult<Vec<SessionUsage>> {
323        let mut since = since.map(rfc3339_secs);
324        let mut until = until.map(rfc3339_secs);
325        let mut cursor: Option<String> = None;
326        let mut sessions = Vec::new();
327        loop {
328            let (url, mut req) = self.http_request(Method::GET, "usage/sessions");
329            for (name, value) in [("since", &since), ("until", &until), ("cursor", &cursor)] {
330                if let Some(value) = value {
331                    req = req.query(&[(name, value)]);
332                }
333            }
334            let page: SessionUsagePage = Self::send_json(url, req).await?;
335            sessions.extend(page.sessions);
336            let Some(next) = page.next_cursor else {
337                return Ok(sessions);
338            };
339            // Pinned from the response so later pages cannot straddle a window
340            // that has drifted with `now`.
341            (since, until, cursor) = (
342                Some(rfc3339_secs(page.since)),
343                Some(rfc3339_secs(page.until)),
344                Some(next),
345            );
346        }
347    }
348
349    /// Most-recent available snapshot slot (`GET /snapshot-slot`).
350    ///
351    /// # Errors
352    ///
353    /// See [HTTP errors](BacktestClient#http-errors).
354    pub async fn get_latest_snapshot_slot(&self) -> BacktestClientResult<SnapshotSlotResponse> {
355        let (url, req) = self.http_request(Method::GET, "snapshot-slot");
356        Self::send_json(url, req).await
357    }
358
359    /// Issue a bundle build (`POST /build-bundle`); the build runs async, so
360    /// poll [`Self::get_bundle_status`] for completion.
361    ///
362    /// # Errors
363    ///
364    /// See [HTTP errors](BacktestClient#http-errors).
365    pub async fn build_bundle(
366        &self,
367        request: &BundleBuildRequest,
368    ) -> BacktestClientResult<BundleBuildStatusResponse> {
369        let (url, req) = self.http_request(Method::POST, "build-bundle");
370        Self::send_json(url, req.json(request)).await
371    }
372
373    /// Delete one of this key's own bundles (`DELETE /bundles`), by kind and
374    /// exact range. A range this key does not own reads as not found.
375    ///
376    /// # Errors
377    ///
378    /// See [HTTP errors](BacktestClient#http-errors).
379    pub async fn delete_bundle(
380        &self,
381        request: &BundleDeleteRequest,
382    ) -> BacktestClientResult<BundleDeleteResponse> {
383        let (url, req) = self.http_request(Method::DELETE, "bundles");
384        Self::send_json(url, req.query(request)).await
385    }
386
387    /// List this key's own bundle builds, newest first, together with the
388    /// bundles it owns (`GET /build-bundle`). Recovers the job ID (`request_id`) of a
389    /// build whose submit response was lost.
390    ///
391    /// # Errors
392    ///
393    /// See [HTTP errors](BacktestClient#http-errors).
394    pub async fn list_bundle_builds(
395        &self,
396        limit: Option<u32>,
397    ) -> BacktestClientResult<BundleBuildListResponse> {
398        let (url, mut req) = self.http_request(Method::GET, "build-bundle");
399        if let Some(limit) = limit {
400            req = req.query(&[("limit", limit)]);
401        }
402        Self::send_json(url, req).await
403    }
404
405    /// Fetch a bundle build job's status (`GET /build-bundle/{request_id}`).
406    ///
407    /// # Errors
408    ///
409    /// See [HTTP errors](BacktestClient#http-errors).
410    pub async fn get_bundle_status(
411        &self,
412        request_id: &str,
413    ) -> BacktestClientResult<BundleBuildStatusResponse> {
414        let (url, req) = self.http_request(Method::GET, &format!("build-bundle/{request_id}"));
415        Self::send_json(url, req).await
416    }
417
418    /// The markets, venues and size rungs of each depth source.
419    ///
420    /// # Errors
421    ///
422    /// See [HTTP errors](BacktestClient#http-errors).
423    pub async fn depth_universe(&self) -> BacktestClientResult<DepthUniverseResponse> {
424        let (url, req) = self.http_request(Method::GET, "dataset-jobs/depth/universe");
425        Self::send_json(url, req).await
426    }
427
428    /// Temporary, read-only S3 credentials for the shared datasets and this
429    /// key's own (`POST /datasets/credentials`).
430    ///
431    /// # Errors
432    ///
433    /// See [HTTP errors](BacktestClient#http-errors).
434    pub async fn dataset_credentials(&self) -> BacktestClientResult<DatasetCredentialsResponse> {
435        let (url, req) = self.http_request(Method::POST, "datasets/credentials");
436        Self::send_json(url, req).await
437    }
438
439    /// This key's own datasets, plus the shared one of a named dataset.
440    pub async fn list_datasets(
441        &self,
442        query: &DatasetListQuery,
443    ) -> BacktestClientResult<DatasetListResponse> {
444        let (url, req) = self.http_request(Method::GET, "datasets");
445        Self::send_json(url, req.query(query)).await
446    }
447
448    /// Remove a slot range of this key's own dataset; refused while one of its jobs replays any of
449    /// it.
450    pub async fn delete_dataset_range(
451        &self,
452        request: &DatasetDeleteRequest,
453    ) -> BacktestClientResult<DatasetDeleteResponse> {
454        let (url, req) = self.http_request(Method::DELETE, "datasets");
455        Self::send_json(url, req.query(request)).await
456    }
457
458    /// Start a dataset job; resubmitting the same request returns the same job.
459    pub async fn create_dataset_job(
460        &self,
461        request: &DatasetJobRequest,
462    ) -> BacktestClientResult<DatasetJobStatusResponse> {
463        let (url, req) = self.http_request(Method::POST, "dataset-jobs");
464        Self::send_json(url, req.json(request)).await
465    }
466
467    /// This key's dataset jobs, newest first.
468    pub async fn list_dataset_jobs(&self) -> BacktestClientResult<DatasetJobListResponse> {
469        let (url, req) = self.http_request(Method::GET, "dataset-jobs");
470        Self::send_json(url, req).await
471    }
472
473    /// A dataset job of this key.
474    pub async fn get_dataset_job(
475        &self,
476        job_id: &str,
477    ) -> BacktestClientResult<DatasetJobStatusResponse> {
478        let (url, req) = self.http_request(Method::GET, &format!("dataset-jobs/{job_id}"));
479        Self::send_json(url, req).await
480    }
481
482    /// Cancel a dataset job; rows it already wrote stay, and an ended job is returned unchanged.
483    pub async fn cancel_dataset_job(
484        &self,
485        job_id: &str,
486    ) -> BacktestClientResult<DatasetJobStatusResponse> {
487        let (url, req) = self.http_request(Method::DELETE, &format!("dataset-jobs/{job_id}"));
488        Self::send_json(url, req).await
489    }
490
491    /// Reattach to a running session over a new connection.
492    ///
493    /// Pass the `last_sequence` of the lost connection ([`BacktestSession::last_sequence`]); `None`
494    /// replays everything the session holds. Reattach within the session's
495    /// `disconnect_timeout_secs`.
496    ///
497    /// # Errors
498    ///
499    /// - [`BacktestClientError::HttpStatus`] with 401 or 403 for a rejected API key;
500    ///   [`BacktestClientError::Closed`] when the server cannot be reached.
501    /// - [`BacktestClientError::Remote`]: `SessionNotFound` and `SessionOwnerMismatch` are final.
502    ///   `SessionOwnershipBusy` is worth one retry, but never for a child of a parallel run.
503    /// - [`BacktestClientError::UnexpectedResponse`] when the server attaches the session itself,
504    ///   which this client cannot use.
505    /// - [`CreateError::EndpointUnreachable`] and [`BacktestClientError::SessionTokenRejected`] as
506    ///   for [`Self::create_session`].
507    #[doc(hidden)]
508    pub async fn attach_session(
509        &self,
510        session_id: SessionId,
511        last_sequence: Option<u64>,
512    ) -> BacktestClientResult<BacktestSession> {
513        let response = request_attach(&self.management(), session_id)
514            .await
515            .map_err(|error| self.attach_failed(error))?;
516        match response {
517            BacktestResponse::SessionGranted(grant) => {
518                self.attach_granted(grant, last_sequence).await
519            }
520            BacktestResponse::Error(error) => Err(BacktestClientError::Remote(error)),
521            BacktestResponse::Status { .. }
522            | BacktestResponse::SessionCreated { .. }
523            | BacktestResponse::SessionAttached { .. }
524            | BacktestResponse::SessionsGranted(_)
525            | BacktestResponse::SessionsCreatedV2 { .. }
526            | BacktestResponse::ParallelSessionAttachedV2 { .. }
527            | BacktestResponse::ReadyForContinue
528            | BacktestResponse::SlotNotification(_)
529            | BacktestResponse::Paused(_)
530            | BacktestResponse::DiscoveryBatch(_)
531            | BacktestResponse::Success
532            | BacktestResponse::Completed { .. }
533            | BacktestResponse::SessionEventV2 { .. } => {
534                Err(BacktestClientError::UnexpectedResponse {
535                    context: "attaching to a session",
536                    response: Box::new(response),
537                })
538            }
539        }
540    }
541}
542
543pub(crate) fn user_agent(
544    product: ClientProduct,
545    product_version: Option<&str>,
546    surface: ClientSurface,
547) -> String {
548    let sdk_version = env!("CARGO_PKG_VERSION");
549    render(
550        product,
551        surface,
552        product_version.unwrap_or(sdk_version),
553        sdk_version,
554    )
555}
556
557#[cfg(test)]
558mod tests {
559    use simulator_api::BundleKind;
560
561    use super::*;
562
563    #[test]
564    fn builder_normalizes_bare_hosts_and_keeps_full_urls() {
565        let from_host = BacktestClient::builder()
566            .url("simulator.termina.technology")
567            .build();
568        assert_eq!(from_host.url, "wss://simulator.termina.technology/backtest");
569
570        let from_full_url = BacktestClient::builder()
571            .url("ws://localhost:8900/backtest".to_string())
572            .build();
573        assert_eq!(from_full_url.url, "ws://localhost:8900/backtest");
574    }
575
576    #[test]
577    fn delete_bundle_names_the_bundle_in_the_query() {
578        // The serialized form is the wire contract, not an implementation detail.
579        let query = |kind| {
580            reqwest::Client::builder()
581                .build()
582                .expect("a default client builds")
583                .delete("http://localhost/bundles")
584                .query(&BundleDeleteRequest {
585                    start_slot: 100,
586                    end_slot: 200,
587                    kind,
588                })
589                .build()
590                .unwrap()
591                .url()
592                .query()
593                .unwrap()
594                .to_string()
595        };
596        assert_eq!(
597            query(BundleKind::Blocks),
598            "start_slot=100&end_slot=200&kind=blocks"
599        );
600        assert_eq!(
601            query(BundleKind::AccountState),
602            "start_slot=100&end_slot=200&kind=account_state"
603        );
604    }
605
606    #[test]
607    fn list_datasets_names_only_the_filters_it_was_given() {
608        let query = |query: &DatasetListQuery| {
609            reqwest::Client::builder()
610                .build()
611                .expect("a default client builds")
612                .get("http://localhost/datasets")
613                .query(query)
614                .build()
615                .unwrap()
616                .url()
617                .query()
618                .map(str::to_owned)
619        };
620        assert_eq!(query(&DatasetListQuery::default()), None);
621        assert_eq!(
622            query(&DatasetListQuery {
623                dataset: Some("modified/depth/onchain/slot/ab12".to_string()),
624                version: Some(4),
625            })
626            .as_deref(),
627            Some("dataset=modified%2Fdepth%2Fonchain%2Fslot%2Fab12&version=4")
628        );
629    }
630}