simulator-client 0.20.0

Async WebSocket client for the Solana simulator backtest API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::time::Duration;

use bon::Builder;
use chrono::{DateTime, Utc};
use reqwest::Method;
use serde::de::DeserializeOwned;
use simulator_api::{
    AvailableRange, BacktestResponse, BundleBuildListResponse, BundleBuildRequest,
    BundleBuildStatusResponse, BundleDeleteRequest, BundleDeleteResponse, ControlSessionId,
    SessionId, SnapshotSlotResponse,
    client_identity::{ClientProduct, ClientSurface, render},
    usage::UsageReport,
};
use tokio_tungstenite::{
    connect_async,
    tungstenite::{client::IntoClientRequest, http::HeaderValue},
};

use crate::{
    BacktestClientError, BacktestClientResult, BacktestSession, CreateSession,
    session::CreateRequestResult,
    urls::{backtest_ws_url, http_base_from_ws_url},
};

const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// Backtest WebSocket client configured with a base URL and API key.
///
/// Build with [`BacktestClient::builder`], which supports optional timeouts and
/// raw message logging.
///
/// This is the low-level layer: every session it opens is one raw WebSocket
/// with no reconnect and no reattach, so a dropped connection ends the run
/// unless the caller reattaches with [`BacktestClient::attach_session`]. Most
/// callers want [`crate::ManagedBacktestSession`], which does that for them —
/// see the crate docs on session handoff.
#[derive(Debug, Clone, Builder)]
#[builder(on(String, into))]
pub struct BacktestClient {
    /// WebSocket endpoint. Accepts a bare hostname (normalized to
    /// `wss://{host}/backtest`) or an explicit `ws(s)://` URL, whose
    /// `/backtest` path is appended only if missing.
    #[builder(with = |url: impl Into<String>| backtest_ws_url(&url.into()))]
    url: String,
    /// API key injected as the `X-API-Key` header.
    #[builder(default)]
    api_key: String,

    #[builder(default = ClientProduct::Sdk)]
    product: ClientProduct,

    /// The leading product token's own release, for binaries wrapping this library (the CLI
    /// reports its crate version here); the SDK token always carries this library's.
    product_version: Option<&'static str>,

    /// Built once on first use and reused: a per-request `Client` would build a
    /// fresh connection pool for every call.
    #[builder(skip)]
    http: std::sync::OnceLock<reqwest::Client>,

    /// Timeout for the initial connect handshake.
    #[builder(default = DEFAULT_CONNECT_TIMEOUT)]
    connect_timeout: Duration,

    /// Default timeout for request/response operations.
    request_timeout: Option<Duration>,

    /// Log raw inbound responses at debug level.
    #[builder(default)]
    log_raw: bool,
}

impl BacktestClient {
    async fn connect(&self) -> BacktestClientResult<BacktestSession> {
        let mut request = self.url.clone().into_client_request().map_err(|source| {
            BacktestClientError::BuildRequest {
                url: self.url.clone(),
                source: Box::new(source),
            }
        })?;

        request
            .headers_mut()
            .insert("X-API-Key", HeaderValue::from_str(&self.api_key)?);
        request.headers_mut().insert(
            reqwest::header::USER_AGENT.as_str(),
            HeaderValue::from_str(&user_agent(
                self.product,
                self.product_version,
                ClientSurface::Raw,
            ))?,
        );

        let (stream, _) = tokio::time::timeout(self.connect_timeout, connect_async(request))
            .await
            .map_err(|_| BacktestClientError::Timeout {
                action: "connecting",
                duration: self.connect_timeout,
            })?
            .map_err(|source| BacktestClientError::Connect {
                url: self.url.clone(),
                source: Box::new(source),
            })?;
        Ok(BacktestSession::new(
            stream,
            self.request_timeout,
            self.log_raw,
        ))
    }

    /// Create a backtest session by connecting and sending a `CreateBacktestSession` request.
    pub async fn create_session(
        &self,
        create: CreateSession,
    ) -> BacktestClientResult<BacktestSession> {
        let request = create.into_request()?;
        let rpc_base_url = http_base_from_ws_url(&self.url);
        let mut session = self.connect().await?;
        match session
            .create_with_request(request, rpc_base_url, None)
            .await?
        {
            CreateRequestResult::Single { .. } => {}
            CreateRequestResult::Parallel { session_ids, .. } => {
                return Err(BacktestClientError::UnexpectedResponse {
                    context: "creating single session",
                    response: Box::new(BacktestResponse::SessionsCreatedV2 {
                        control_session_id: ControlSessionId::default(),
                        session_ids,
                        task_ids: Vec::new(),
                        start_slots: Vec::new(),
                        end_slots: Vec::new(),
                    }),
                });
            }
        }
        Ok(session)
    }

    /// Create one or many sessions and return the resulting session IDs.
    ///
    /// When `CreateSession.parallel` is true, this may return many IDs.
    pub async fn create_sessions(
        &self,
        create: CreateSession,
    ) -> BacktestClientResult<Vec<SessionId>> {
        self.create_sessions_with_progress(create, |_| {}).await
    }

    /// Create one or many sessions and stream each successfully created session ID.
    ///
    /// `on_session_created` is called for each streamed `SessionCreated` response.
    pub async fn create_sessions_with_progress(
        &self,
        create: CreateSession,
        mut on_session_created: impl FnMut(SessionId) + Send,
    ) -> BacktestClientResult<Vec<SessionId>> {
        let request = create.into_request()?;
        let rpc_base_url = http_base_from_ws_url(&self.url);
        let mut session = self.connect().await?;
        match session
            .create_with_request(request, rpc_base_url, Some(&mut on_session_created))
            .await?
        {
            CreateRequestResult::Single { session_id, .. } => Ok(vec![session_id]),
            CreateRequestResult::Parallel { session_ids, .. } => Ok(session_ids),
        }
    }

    /// Like [`Self::create_sessions`], but additionally returns the opaque
    /// per-session `task_id` reported by the server (if any).
    pub async fn create_sessions_with_task_ids(
        &self,
        create: CreateSession,
    ) -> BacktestClientResult<Vec<(SessionId, Option<String>)>> {
        let request = create.into_request()?;
        let rpc_base_url = http_base_from_ws_url(&self.url);
        let mut session = self.connect().await?;
        match session
            .create_with_request(request, rpc_base_url, None)
            .await?
        {
            CreateRequestResult::Single {
                session_id,
                task_id,
            } => Ok(vec![(session_id, task_id)]),
            CreateRequestResult::Parallel {
                session_ids,
                task_ids,
            } => Ok(session_ids.into_iter().zip(task_ids).collect()),
        }
    }

    /// Fetch the slot ranges that can be run, from the server's
    /// `/available-ranges` endpoint.
    pub async fn available_ranges(&self) -> BacktestClientResult<Vec<AvailableRange>> {
        self.fetch_available_ranges(false).await
    }

    /// Like [`Self::available_ranges`], plus the caller's own ranges available
    /// to replay recorded account state. The two are not interchangeable, so
    /// callers planning a run ask for the smaller list.
    pub async fn available_ranges_with_account_state(
        &self,
    ) -> BacktestClientResult<Vec<AvailableRange>> {
        self.fetch_available_ranges(true).await
    }

    async fn fetch_available_ranges(
        &self,
        include_account_state: bool,
    ) -> BacktestClientResult<Vec<AvailableRange>> {
        let base = http_base_from_ws_url(&self.url);
        let url = format!("{base}/available-ranges?include_account_state={include_account_state}");
        // Forwarded (when set) so the endpoint adds this key's own ranges,
        // keeping the client's split in sync with the server's. Omitted when
        // unset so a keyless client gets global ranges, not an empty-key 401.
        let mut request = self.http_client().get(&url);
        if !self.api_key.is_empty() {
            request = request.header("X-API-Key", &self.api_key);
        }
        let ranges = request
            .send()
            .await
            .map_err(|e| BacktestClientError::Http {
                url: url.clone(),
                source: Box::new(e),
            })?
            .error_for_status()
            .map_err(|e| BacktestClientError::Http {
                url: url.clone(),
                source: Box::new(e),
            })?
            .json::<Vec<AvailableRange>>()
            .await
            .map_err(|e| BacktestClientError::Http {
                url: url.clone(),
                source: Box::new(e),
            })?;
        Ok(ranges)
    }

    fn http_client(&self) -> &reqwest::Client {
        self.http.get_or_init(|| {
            reqwest::Client::builder()
                .user_agent(user_agent(
                    self.product,
                    self.product_version,
                    ClientSurface::Raw,
                ))
                .build()
                .unwrap_or_default()
        })
    }

    /// Authenticated request builder for `path`, paired with the URL for errors.
    fn http_request(&self, method: Method, path: &str) -> (String, reqwest::RequestBuilder) {
        let url = format!("{}/{path}", http_base_from_ws_url(&self.url));
        let request = self
            .http_client()
            .request(method, &url)
            .header("X-API-Key", &self.api_key);
        (url, request)
    }

    /// Send `request` and decode a 2xx JSON body; a non-2xx response keeps its
    /// body in the error.
    async fn send_json<T: DeserializeOwned>(
        url: String,
        request: reqwest::RequestBuilder,
    ) -> BacktestClientResult<T> {
        let resp = request
            .send()
            .await
            .map_err(|e| BacktestClientError::Http {
                url: url.clone(),
                source: Box::new(e),
            })?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(BacktestClientError::HttpStatus { url, status, body });
        }
        resp.json::<T>()
            .await
            .map_err(|e| BacktestClientError::Http {
                url,
                source: Box::new(e),
            })
    }

    /// Fetch per-API-key usage metrics from the server's `/usage` endpoint.
    ///
    /// `since` and `until` narrow the reporting window; both default to the
    /// server's configured window when omitted.
    pub async fn usage(
        &self,
        since: Option<DateTime<Utc>>,
        until: Option<DateTime<Utc>>,
    ) -> BacktestClientResult<UsageReport> {
        let (url, mut req) = self.http_request(Method::GET, "usage");
        if let Some(t) = since {
            req = req.query(&[(
                "since",
                t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            )]);
        }
        if let Some(t) = until {
            req = req.query(&[(
                "until",
                t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            )]);
        }
        Self::send_json(url, req).await
    }

    /// Most-recent available snapshot slot (`GET /snapshot-slot`).
    pub async fn get_latest_snapshot_slot(&self) -> BacktestClientResult<SnapshotSlotResponse> {
        let (url, req) = self.http_request(Method::GET, "snapshot-slot");
        Self::send_json(url, req).await
    }

    /// Issue a bundle build (`POST /build-bundle`); the build runs async, so
    /// poll [`Self::get_bundle_status`] for completion.
    pub async fn build_bundle(
        &self,
        request: &BundleBuildRequest,
    ) -> BacktestClientResult<BundleBuildStatusResponse> {
        let (url, req) = self.http_request(Method::POST, "build-bundle");
        Self::send_json(url, req.json(request)).await
    }

    /// Delete one of this key's own bundles (`DELETE /bundles`), by kind and
    /// exact range. A range this key does not own reads as not found.
    pub async fn delete_bundle(
        &self,
        request: &BundleDeleteRequest,
    ) -> BacktestClientResult<BundleDeleteResponse> {
        let (url, req) = self.http_request(Method::DELETE, "bundles");
        Self::send_json(url, req.query(request)).await
    }

    /// List this key's own bundle builds, newest first, together with the
    /// bundles it owns (`GET /build-bundle`). Recovers the `request_id` of a
    /// build whose submit response was lost.
    pub async fn list_bundle_builds(
        &self,
        limit: Option<u32>,
    ) -> BacktestClientResult<BundleBuildListResponse> {
        let (url, mut req) = self.http_request(Method::GET, "build-bundle");
        if let Some(limit) = limit {
            req = req.query(&[("limit", limit)]);
        }
        Self::send_json(url, req).await
    }

    /// Fetch a build's status (`GET /build-bundle/{request_id}`).
    pub async fn get_bundle_status(
        &self,
        request_id: &str,
    ) -> BacktestClientResult<BundleBuildStatusResponse> {
        let (url, req) = self.http_request(Method::GET, &format!("build-bundle/{request_id}"));
        Self::send_json(url, req).await
    }

    /// Attach to an existing backtest session over the control websocket.
    pub async fn attach_session(
        &self,
        session_id: SessionId,
        last_sequence: Option<u64>,
    ) -> BacktestClientResult<BacktestSession> {
        let rpc_base_url = http_base_from_ws_url(&self.url);
        let mut session = self.connect().await?;
        session
            .attach(session_id, last_sequence, rpc_base_url)
            .await?;
        Ok(session)
    }
}

pub(crate) fn user_agent(
    product: ClientProduct,
    product_version: Option<&str>,
    surface: ClientSurface,
) -> String {
    let sdk_version = env!("CARGO_PKG_VERSION");
    render(
        product,
        surface,
        product_version.unwrap_or(sdk_version),
        sdk_version,
    )
}

#[cfg(test)]
mod tests {
    use simulator_api::BundleKind;

    use super::*;

    #[test]
    fn builder_normalizes_bare_hosts_and_keeps_full_urls() {
        let from_host = BacktestClient::builder()
            .url("simulator.termina.technology")
            .build();
        assert_eq!(from_host.url, "wss://simulator.termina.technology/backtest");

        let from_full_url = BacktestClient::builder()
            .url("ws://localhost:8900/backtest".to_string())
            .build();
        assert_eq!(from_full_url.url, "ws://localhost:8900/backtest");
    }

    #[test]
    fn delete_bundle_names_the_bundle_in_the_query() {
        // The serialized form is the wire contract, not an implementation detail.
        let query = |kind| {
            reqwest::Client::new()
                .delete("http://localhost/bundles")
                .query(&BundleDeleteRequest {
                    start_slot: 100,
                    end_slot: 200,
                    kind,
                })
                .build()
                .unwrap()
                .url()
                .query()
                .unwrap()
                .to_string()
        };
        assert_eq!(
            query(BundleKind::Blocks),
            "start_slot=100&end_slot=200&kind=blocks"
        );
        assert_eq!(
            query(BundleKind::AccountState),
            "start_slot=100&end_slot=200&kind=account_state"
        );
    }
}