simulator-client 0.30.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use std::time::Duration;

use bon::Builder;
use chrono::{DateTime, Utc};
use http::{HeaderMap, StatusCode};
use reqwest::Method;
use serde::de::DeserializeOwned;
use simulator_api::{
    AvailableRange, BacktestResponse, BundleBuildListResponse, BundleBuildRequest,
    BundleBuildStatusResponse, BundleDeleteRequest, BundleDeleteResponse,
    DatasetCredentialsResponse, DatasetDeleteRequest, DatasetDeleteResponse,
    DatasetJobListResponse, DatasetJobRequest, DatasetJobStatusResponse, DatasetListQuery,
    DatasetListResponse, DepthUniverseResponse, SessionId, SnapshotSlotResponse,
    client_identity::{ClientProduct, ClientSurface, render},
    session_endpoint::SessionGrant,
    usage::{SessionUsage, SessionUsagePage, UsageReport},
};
use tokio::time::Instant;

use crate::{
    BacktestClientError, BacktestClientResult, BacktestSession, CreateSession,
    endpoint::{ControlConnectError, FirstConnect, connect_control},
    managed::{
        CreateError, Ws,
        grant::{
            AttachError, GrantError, ManagementTarget, SingleCreate, request_attach,
            request_session_grant,
        },
    },
    urls::{backtest_ws_url, http_base_from_ws_url},
};

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

fn rfc3339_secs(at: DateTime<Utc>) -> String {
    at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

/// Client for the server's HTTP endpoints, authenticated with an API key.
///
/// Build with [`BacktestClient::builder`]; only `url` is required. The API key, when set, goes
/// out as the `X-API-Key` header on every request.
///
/// Drive sessions through [`crate::ManagedBacktestSession`], or
/// [`crate::managed::ManagedParallelSession`] for a parallel run.
///
/// # HTTP errors
///
/// The methods that call the server's HTTP endpoints fail with:
///
/// - [`BacktestClientError::HttpStatus`] when the server answers with a non-2xx status. 401 or
///   403 means it rejected the API key.
/// - [`BacktestClientError::Http`] when the request fails or the body does not decode.
#[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,

    /// The product named first in the `User-Agent`. Default [`ClientProduct::Sdk`]; a tool
    /// that wraps this library sets its own.
    #[builder(default = ClientProduct::Sdk)]
    product: ClientProduct,

    /// The release of `product`, for tools wrapping this library (the CLI reports its crate
    /// version here). Leave it unset otherwise; 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 each send and receive on a session, used when a call passes
    /// `None`. Unset: wait indefinitely.
    request_timeout: Option<Duration>,

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

impl BacktestClient {
    fn management(&self) -> ManagementTarget {
        ManagementTarget {
            url: self.url.clone(),
            api_key: self.api_key.clone(),
            extra_headers: HeaderMap::new(),
            user_agent: self.raw_user_agent(),
            connect_timeout: self.connect_timeout,
        }
    }

    fn raw_user_agent(&self) -> String {
        user_agent(self.product, self.product_version, ClientSurface::Raw)
    }

    fn api_key_rejected(&self, status: StatusCode) -> BacktestClientError {
        BacktestClientError::HttpStatus {
            url: self.url.clone(),
            status,
            body: "API key rejected".to_owned(),
        }
    }

    fn grant_failed(&self, error: GrantError) -> BacktestClientError {
        match error {
            GrantError::ApiKeyRejected(status) => self.api_key_rejected(status),
            GrantError::Create(error) => error.into(),
        }
    }

    fn attach_failed(&self, error: AttachError) -> BacktestClientError {
        match error {
            AttachError::ApiKeyRejected(status) => self.api_key_rejected(status),
            AttachError::Connection(reason) => BacktestClientError::Closed { reason },
            AttachError::Protocol(message) => CreateError::Protocol(message).into(),
        }
    }

    /// Connects to the granted session's control socket. A name that does not resolve yet is
    /// retried until the first-connect window closes.
    async fn connect_endpoint(&self, grant: &SessionGrant) -> BacktestClientResult<Ws> {
        let user_agent = self.raw_user_agent();
        let first = FirstConnect::start(Instant::now());
        loop {
            let why = match connect_control(grant, &user_agent, self.connect_timeout).await {
                Ok(ws) => return Ok(ws),
                Err(ControlConnectError::TokenRejected) => {
                    return Err(BacktestClientError::SessionTokenRejected);
                }
                Err(request @ ControlConnectError::Request(_)) => {
                    return Err(CreateError::Protocol(request.to_string()).into());
                }
                Err(ControlConnectError::Failed(why)) => why,
            };
            let Some(delay) = first.retry_after(Instant::now()) else {
                return Err(CreateError::EndpointUnreachable {
                    session_id: grant.session_id,
                    endpoint: grant.endpoint.clone(),
                    reason: why,
                }
                .into());
            };
            tokio::time::sleep(delay).await;
        }
    }

    async fn attach_granted(
        &self,
        grant: SessionGrant,
        last_sequence: Option<u64>,
    ) -> BacktestClientResult<BacktestSession> {
        let ws = self.connect_endpoint(&grant).await?;
        BacktestSession::attached(ws, grant, last_sequence, self.request_timeout, self.log_raw)
            .await
    }

    /// Create one session and attach to it on its own endpoint.
    ///
    /// # Errors
    ///
    /// - [`BacktestClientError::InvalidParams`] when `create` is rejected or sets `parallel`;
    ///   nothing is sent.
    /// - [`BacktestClientError::HttpStatus`] with 401 or 403 for a rejected API key;
    ///   [`BacktestClientError::Closed`] when the server cannot be reached.
    /// - [`BacktestClientError::Create`] with [`CreateError::LostAfterSend`]: a session may have
    ///   started and ends itself when nobody attaches.
    /// - [`BacktestClientError::Remote`] when the server refuses the create.
    /// - [`BacktestClientError::Create`] with [`CreateError::EndpointUnreachable`]: the session
    ///   ends itself later.
    /// - [`BacktestClientError::SessionTokenRejected`] when the endpoint refuses the token.
    #[doc(hidden)]
    pub async fn create_session(
        &self,
        create: CreateSession,
    ) -> BacktestClientResult<BacktestSession> {
        let create = SingleCreate::try_from(create.into_request()?)?;
        let grant = request_session_grant(&self.management(), create)
            .await
            .map_err(|error| self.grant_failed(error))?;
        self.attach_granted(grant, None).await
    }

    /// Fetch the slot ranges that can be run, from the server's
    /// `/available-ranges` endpoint. Narrow the list with [`crate::filter_ranges`].
    ///
    /// The list is sorted by `bundle_start_slot`, oldest first. Take the newest with
    /// `ranges.iter().max_by_key(|r| r.bundle_start_slot)`.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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.
    ///
    /// # Errors
    ///
    /// As [`Self::available_ranges`].
    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);
        }
        Self::send_json(url, request).await
    }

    fn http_client(&self) -> &reqwest::Client {
        self.http.get_or_init(|| {
            reqwest::Client::builder()
                .user_agent(self.raw_user_agent())
                .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` set the reporting window; both default to the
    /// server's configured window when omitted. The report is bucketed by UTC
    /// day, so the window served — and the totals over it — starts at the
    /// midnight at or before `since`.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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");
        for (name, value) in [("since", since), ("until", until)] {
            if let Some(value) = value {
                req = req.query(&[(name, rfc3339_secs(value))]);
            }
        }
        Self::send_json(url, req).await
    }

    /// Every session that ended in the window (`GET /usage/sessions`).
    ///
    /// `since` and `until` set the window as [`Self::usage`] does. Reads every
    /// page. Completeness is the guarantee, not order: sort by `ended_at` for
    /// chronological.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    pub async fn usage_sessions(
        &self,
        since: Option<DateTime<Utc>>,
        until: Option<DateTime<Utc>>,
    ) -> BacktestClientResult<Vec<SessionUsage>> {
        let mut since = since.map(rfc3339_secs);
        let mut until = until.map(rfc3339_secs);
        let mut cursor: Option<String> = None;
        let mut sessions = Vec::new();
        loop {
            let (url, mut req) = self.http_request(Method::GET, "usage/sessions");
            for (name, value) in [("since", &since), ("until", &until), ("cursor", &cursor)] {
                if let Some(value) = value {
                    req = req.query(&[(name, value)]);
                }
            }
            let page: SessionUsagePage = Self::send_json(url, req).await?;
            sessions.extend(page.sessions);
            let Some(next) = page.next_cursor else {
                return Ok(sessions);
            };
            // Pinned from the response so later pages cannot straddle a window
            // that has drifted with `now`.
            (since, until, cursor) = (
                Some(rfc3339_secs(page.since)),
                Some(rfc3339_secs(page.until)),
                Some(next),
            );
        }
    }

    /// Most-recent available snapshot slot (`GET /snapshot-slot`).
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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 job ID (`request_id`) of a
    /// build whose submit response was lost.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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 bundle build job's status (`GET /build-bundle/{request_id}`).
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    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
    }

    /// The markets, venues and size rungs of each depth source.
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    pub async fn depth_universe(&self) -> BacktestClientResult<DepthUniverseResponse> {
        let (url, req) = self.http_request(Method::GET, "dataset-jobs/depth/universe");
        Self::send_json(url, req).await
    }

    /// Temporary, read-only S3 credentials for the shared datasets and this
    /// key's own (`POST /datasets/credentials`).
    ///
    /// # Errors
    ///
    /// See [HTTP errors](BacktestClient#http-errors).
    pub async fn dataset_credentials(&self) -> BacktestClientResult<DatasetCredentialsResponse> {
        let (url, req) = self.http_request(Method::POST, "datasets/credentials");
        Self::send_json(url, req).await
    }

    /// This key's own datasets, plus the shared one of a named dataset.
    pub async fn list_datasets(
        &self,
        query: &DatasetListQuery,
    ) -> BacktestClientResult<DatasetListResponse> {
        let (url, req) = self.http_request(Method::GET, "datasets");
        Self::send_json(url, req.query(query)).await
    }

    /// Remove a slot range of this key's own dataset; refused while one of its jobs replays any of
    /// it.
    pub async fn delete_dataset_range(
        &self,
        request: &DatasetDeleteRequest,
    ) -> BacktestClientResult<DatasetDeleteResponse> {
        let (url, req) = self.http_request(Method::DELETE, "datasets");
        Self::send_json(url, req.query(request)).await
    }

    /// Start a dataset job; resubmitting the same request returns the same job.
    pub async fn create_dataset_job(
        &self,
        request: &DatasetJobRequest,
    ) -> BacktestClientResult<DatasetJobStatusResponse> {
        let (url, req) = self.http_request(Method::POST, "dataset-jobs");
        Self::send_json(url, req.json(request)).await
    }

    /// This key's dataset jobs, newest first.
    pub async fn list_dataset_jobs(&self) -> BacktestClientResult<DatasetJobListResponse> {
        let (url, req) = self.http_request(Method::GET, "dataset-jobs");
        Self::send_json(url, req).await
    }

    /// A dataset job of this key.
    pub async fn get_dataset_job(
        &self,
        job_id: &str,
    ) -> BacktestClientResult<DatasetJobStatusResponse> {
        let (url, req) = self.http_request(Method::GET, &format!("dataset-jobs/{job_id}"));
        Self::send_json(url, req).await
    }

    /// Cancel a dataset job; rows it already wrote stay, and an ended job is returned unchanged.
    pub async fn cancel_dataset_job(
        &self,
        job_id: &str,
    ) -> BacktestClientResult<DatasetJobStatusResponse> {
        let (url, req) = self.http_request(Method::DELETE, &format!("dataset-jobs/{job_id}"));
        Self::send_json(url, req).await
    }

    /// Reattach to a running session over a new connection.
    ///
    /// Pass the `last_sequence` of the lost connection ([`BacktestSession::last_sequence`]); `None`
    /// replays everything the session holds. Reattach within the session's
    /// `disconnect_timeout_secs`.
    ///
    /// # Errors
    ///
    /// - [`BacktestClientError::HttpStatus`] with 401 or 403 for a rejected API key;
    ///   [`BacktestClientError::Closed`] when the server cannot be reached.
    /// - [`BacktestClientError::Remote`]: `SessionNotFound` and `SessionOwnerMismatch` are final.
    ///   `SessionOwnershipBusy` is worth one retry, but never for a child of a parallel run.
    /// - [`BacktestClientError::UnexpectedResponse`] when the server attaches the session itself,
    ///   which this client cannot use.
    /// - [`CreateError::EndpointUnreachable`] and [`BacktestClientError::SessionTokenRejected`] as
    ///   for [`Self::create_session`].
    #[doc(hidden)]
    pub async fn attach_session(
        &self,
        session_id: SessionId,
        last_sequence: Option<u64>,
    ) -> BacktestClientResult<BacktestSession> {
        let response = request_attach(&self.management(), session_id)
            .await
            .map_err(|error| self.attach_failed(error))?;
        match response {
            BacktestResponse::SessionGranted(grant) => {
                self.attach_granted(grant, last_sequence).await
            }
            BacktestResponse::Error(error) => Err(BacktestClientError::Remote(error)),
            BacktestResponse::Status { .. }
            | BacktestResponse::SessionCreated { .. }
            | BacktestResponse::SessionAttached { .. }
            | BacktestResponse::SessionsGranted(_)
            | BacktestResponse::SessionsCreatedV2 { .. }
            | BacktestResponse::ParallelSessionAttachedV2 { .. }
            | BacktestResponse::ReadyForContinue
            | BacktestResponse::SlotNotification(_)
            | BacktestResponse::Paused(_)
            | BacktestResponse::DiscoveryBatch(_)
            | BacktestResponse::Success
            | BacktestResponse::Completed { .. }
            | BacktestResponse::SessionEventV2 { .. } => {
                Err(BacktestClientError::UnexpectedResponse {
                    context: "attaching to a session",
                    response: Box::new(response),
                })
            }
        }
    }
}

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"
        );
    }

    #[test]
    fn list_datasets_names_only_the_filters_it_was_given() {
        let query = |query: &DatasetListQuery| {
            reqwest::Client::new()
                .get("http://localhost/datasets")
                .query(query)
                .build()
                .unwrap()
                .url()
                .query()
                .map(str::to_owned)
        };
        assert_eq!(query(&DatasetListQuery::default()), None);
        assert_eq!(
            query(&DatasetListQuery {
                dataset: Some("modified/depth/onchain/slot/ab12".to_string()),
                version: Some(4),
            })
            .as_deref(),
            Some("dataset=modified%2Fdepth%2Fonchain%2Fslot%2Fab12&version=4")
        );
    }
}