simulator-api 0.31.0

Wire-protocol types for the Solana simulator backtest WebSocket 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
//! Start, follow and cancel dataset jobs: `POST`, `GET` and `DELETE /dataset-jobs[/{job_id}]`.

use std::{collections::BTreeSet, fmt, num::NonZeroU64};

use serde::{Deserialize, Serialize};

use crate::{DepthSelection, SlotRange};

/// Request body of `POST /dataset-jobs`. Resubmitting it answers with the same job, re-running
/// it if it failed or was cancelled.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetJobRequest {
    /// Inclusive; sent as `start_slot` and `end_slot`.
    #[serde(flatten, with = "crate::slot_range::slot_bounds")]
    pub slots: SlotRange,
    /// Which dataset to build.
    #[serde(flatten)]
    pub dataset: DatasetJobSpec,
}

/// The dataset a job builds, tagged by `kind` on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DatasetJobSpec {
    /// Probes the current curated template set.
    EstimatedFills,
    /// World BTC 5-minute prediction-market tables.
    Predict {
        /// At least one table.
        tables: BTreeSet<PredictTable>,
    },
    /// What each venue's liquidity would have filled, or the router quoted, at each size across the
    /// range.
    Depth(DepthSelection),
}

impl DatasetJobSpec {
    /// The wire value of `kind`.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::EstimatedFills => "estimated_fills",
            Self::Predict { .. } => "predict",
            Self::Depth(_) => "depth",
        }
    }
}

/// A predict table a dataset job produces.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    strum::IntoStaticStr,
)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PredictTable {
    /// The markets the makers quote.
    Markets,
    /// The writes to the makers' accounts.
    Writes,
    /// Maker quote ladders, per batch that changed a market account.
    Depth,
    /// An order per row, with each maker's quote.
    Orders,
}

impl PredictTable {
    /// The table's wire name.
    pub fn as_str(self) -> &'static str {
        self.into()
    }
}

/// A job's request, resolved range, phase and outputs, as `GET /dataset-jobs/{job_id}` answers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetJobStatusResponse {
    /// The id the job is followed and cancelled by.
    pub job_id: String,
    /// First slot requested.
    pub start_slot: u64,
    /// Last slot requested.
    pub end_slot: u64,
    /// The requested range widened to whole bundles.
    pub capture: SlotRange,
    /// The dataset the job builds.
    #[serde(flatten)]
    pub dataset: DatasetJobSpec,
    /// Where the job is.
    #[serde(flatten)]
    pub phase: DatasetJobPhase,
    /// Where the job's datasets land; filled in as they are written.
    pub outputs: Vec<DatasetLocation>,
    /// When the job was created, in Unix milliseconds.
    pub created_at_unix_ms: u64,
}

/// Where a job is, tagged by `phase` on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "phase", rename_all = "snake_case")]
pub enum DatasetJobPhase {
    /// Building the bundles the range needs.
    Building {
        /// Bundles built so far.
        bundles: Progress,
    },
    /// `sessions` is absent when they cannot be counted.
    Running {
        /// Sessions finished so far.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sessions: Option<Progress>,
        /// Slots the job's sessions have replayed, out of the slots they must replay. It drops when a
        /// failed session is run again. Absent when the job cannot count them yet.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        slots: Option<SlotProgress>,
        /// The job this one waits on before it measures.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        waiting_for: Option<String>,
    },
    /// Every output is written.
    Completed,
    /// The job stopped without finishing.
    Failed {
        /// Why it stopped.
        reason: String,
    },
    /// Rows already written stay.
    Cancelled,
}

impl DatasetJobPhase {
    /// The wire value of `phase`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Building { .. } => "building",
            Self::Running { .. } => "running",
            Self::Completed => "completed",
            Self::Failed { .. } => "failed",
            Self::Cancelled => "cancelled",
        }
    }

    /// Whether the job has stopped for good.
    pub fn is_terminal(&self) -> bool {
        match self {
            Self::Building { .. } | Self::Running { .. } => false,
            Self::Completed | Self::Failed { .. } | Self::Cancelled => true,
        }
    }
}

/// A count of finished units out of the total.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Progress {
    /// Units finished.
    pub done: usize,
    /// Units the job needs.
    pub total: usize,
}

/// Slots a running job's sessions have replayed, out of the slots it owes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlotProgress {
    /// Slots replayed.
    pub done: u64,
    /// Slots the job owes.
    pub total: NonZeroU64,
}

impl SlotProgress {
    /// Whole percent, rounded down, at most 100.
    pub fn percent(&self) -> u64 {
        self.done.min(self.total.get()).saturating_mul(100) / self.total
    }
}

/// A dataset under the `user_s3_uri` that `POST /datasets/credentials` returns, at
/// `<name>/v<version>/`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetLocation {
    /// The dataset's name.
    pub name: String,
    /// The dataset's schema version.
    pub version: u16,
}

impl fmt::Display for DatasetLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/v{}/", self.name, self.version)
    }
}

/// The caller's jobs, as `GET /dataset-jobs` answers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetJobListResponse {
    /// Newest first.
    pub jobs: Vec<DatasetJobStatusResponse>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DepthGranularity, DepthSource};

    #[rstest::rstest]
    #[case::none(0, 8, 0)]
    #[case::rounded_down(3, 8, 37)]
    #[case::all(8, 8, 100)]
    #[case::past_the_total(9, 8, 100)]
    fn the_share_is_a_whole_percent_rounded_down_and_never_over_100(
        #[case] done: u64,
        #[case] total: u64,
        #[case] percent: u64,
    ) {
        let progress = SlotProgress {
            done,
            total: NonZeroU64::new(total).unwrap(),
        };
        assert_eq!(progress.percent(), percent);
    }

    #[test]
    fn a_status_carries_its_kind_and_phase_beside_its_fields() {
        let status = DatasetJobStatusResponse {
            job_id: "j".to_owned(),
            start_slot: 100,
            end_slot: 199,
            capture: SlotRange::new_unchecked(90, 210),
            dataset: DatasetJobSpec::EstimatedFills,
            phase: DatasetJobPhase::Running {
                sessions: Some(Progress { done: 1, total: 3 }),
                slots: None,
                waiting_for: None,
            },
            outputs: vec![DatasetLocation {
                name: "estimated-fills".to_owned(),
                version: 2,
            }],
            created_at_unix_ms: 7,
        };
        let wire = serde_json::json!({
            "job_id": "j",
            "start_slot": 100,
            "end_slot": 199,
            "capture": {"start": 90, "end": 210},
            "kind": "estimated_fills",
            "phase": "running",
            "sessions": {"done": 1, "total": 3},
            "outputs": [{"name": "estimated-fills", "version": 2}],
            "created_at_unix_ms": 7,
        });
        assert_eq!(serde_json::to_value(&status).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobStatusResponse>(wire).unwrap(),
            status
        );
    }

    #[rstest::rstest]
    #[case::without_a_count(
        serde_json::json!({"phase": "running"}),
        DatasetJobPhase::Running { sessions: None, slots: None, waiting_for: None }
    )]
    #[case::with_the_counts(
        serde_json::json!({
            "phase": "running",
            "sessions": {"done": 1, "total": 3},
            "slots": {"done": 1_400, "total": 3_000},
        }),
        DatasetJobPhase::Running {
            sessions: Some(Progress { done: 1, total: 3 }),
            slots: Some(SlotProgress { done: 1_400, total: NonZeroU64::new(3_000).unwrap() }),
            waiting_for: None,
        }
    )]
    fn a_running_phase_leaves_out_the_counts_it_lacks(
        #[case] wire: serde_json::Value,
        #[case] phase: DatasetJobPhase,
    ) {
        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
            phase
        );
    }

    #[test]
    fn a_slot_total_of_zero_fails_to_decode() {
        let wire = serde_json::json!({"done": 0, "total": 0});
        assert!(serde_json::from_value::<SlotProgress>(wire).is_err());
    }

    #[test]
    fn a_waiting_job_names_the_job_it_waits_for() {
        let phase = DatasetJobPhase::Running {
            sessions: None,
            slots: None,
            waiting_for: Some("j2".to_owned()),
        };
        let wire = serde_json::json!({"phase": "running", "waiting_for": "j2"});
        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
            phase
        );
    }

    /// The Prefect `dispatch-dataset-jobs` flow reads this file and must send exactly it.
    #[test]
    fn the_prefect_dispatch_bodies_round_trip() {
        let golden: serde_json::Value =
            serde_json::from_str(include_str!("../tests/data/dataset_job_requests.json")).unwrap();
        let requests: Vec<DatasetJobRequest> = serde_json::from_value(golden.clone()).unwrap();
        assert_eq!(serde_json::to_value(requests).unwrap(), golden);
    }

    #[test]
    fn a_request_names_its_kind_and_range() {
        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "estimated_fills",
        }))
        .unwrap();
        assert_eq!(request.dataset, DatasetJobSpec::EstimatedFills);
        assert_eq!(request.slots, SlotRange::new_unchecked(1, 2));
    }

    #[test]
    fn a_request_with_an_inverted_range_is_refused_as_it_is_read() {
        let request = serde_json::from_value::<DatasetJobRequest>(serde_json::json!({
            "start_slot": 2,
            "end_slot": 1,
            "kind": "estimated_fills",
        }));

        assert!(request.is_err());
    }

    #[test]
    fn a_request_writes_its_range_as_start_and_end_slots() {
        let request = DatasetJobRequest {
            slots: SlotRange::new_unchecked(5, 9),
            dataset: DatasetJobSpec::EstimatedFills,
        };

        assert_eq!(
            serde_json::to_value(&request).unwrap(),
            serde_json::json!({"start_slot": 5, "end_slot": 9, "kind": "estimated_fills"})
        );
    }

    #[test]
    fn a_predict_request_names_its_tables() {
        let request = DatasetJobRequest {
            slots: SlotRange::new_unchecked(1, 2),
            dataset: DatasetJobSpec::Predict {
                tables: BTreeSet::from([
                    PredictTable::Orders,
                    PredictTable::Depth,
                    PredictTable::Markets,
                ]),
            },
        };
        let wire = serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "predict",
            "tables": ["markets", "depth", "orders"],
        });
        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
            request
        );
    }

    #[test]
    fn a_depth_request_spells_its_options_beside_its_slots() {
        let request = DatasetJobRequest {
            slots: SlotRange::new_unchecked(1, 2),
            dataset: DatasetJobSpec::Depth(DepthSelection {
                source: DepthSource::Onchain,
                granularity: DepthGranularity::Oracle,
                markets: vec!["SOL-USDC".to_owned()],
                ..DepthSelection::default()
            }),
        };
        let wire = serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "depth",
            "source": "onchain",
            "granularity": "oracle",
            "markets": ["SOL-USDC"],
        });
        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
            request
        );
    }

    #[test]
    fn a_depth_request_naming_only_its_kind_measures_every_onchain_market_by_slot() {
        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "depth",
        }))
        .unwrap();
        assert_eq!(
            request.dataset,
            DatasetJobSpec::Depth(DepthSelection::default())
        );
    }
}