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