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