Skip to main content

simulator_api/
dataset_jobs.rs

1//! Start, follow and cancel dataset jobs: `POST`, `GET` and `DELETE /dataset-jobs[/{job_id}]`.
2
3use std::{collections::BTreeSet, fmt};
4
5use serde::{Deserialize, Serialize};
6
7use crate::{DepthSelection, SlotRange};
8
9/// Request body of `POST /dataset-jobs`. Resubmitting it answers with the same job, re-running
10/// it if it failed or was cancelled.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct DatasetJobRequest {
13    /// Inclusive; sent as `start_slot` and `end_slot`.
14    #[serde(flatten, with = "crate::slot_range::slot_bounds")]
15    pub slots: SlotRange,
16    /// Which dataset to build.
17    #[serde(flatten)]
18    pub dataset: DatasetJobSpec,
19}
20
21/// The dataset a job builds, tagged by `kind` on the wire.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(tag = "kind", rename_all = "snake_case")]
24pub enum DatasetJobSpec {
25    /// Probes the current curated template set.
26    EstimatedFills,
27    /// World BTC 5-minute prediction-market tables.
28    Predict {
29        /// At least one table.
30        tables: BTreeSet<PredictTable>,
31    },
32    /// What each venue's liquidity would have filled, or the router quoted, at each size across the
33    /// range.
34    Depth(DepthSelection),
35}
36
37impl DatasetJobSpec {
38    /// The wire value of `kind`.
39    pub fn kind(&self) -> &'static str {
40        match self {
41            Self::EstimatedFills => "estimated_fills",
42            Self::Predict { .. } => "predict",
43            Self::Depth(_) => "depth",
44        }
45    }
46}
47
48/// A predict table a dataset job produces.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
50#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
51#[serde(rename_all = "snake_case")]
52pub enum PredictTable {
53    /// The markets the makers quote.
54    Markets,
55    /// The writes to the makers' accounts.
56    Writes,
57    /// Maker quote ladders, per batch that changed a market account.
58    Depth,
59    /// An order per row, with each maker's quote.
60    Orders,
61}
62
63impl PredictTable {
64    /// The table's wire name.
65    pub fn as_str(self) -> &'static str {
66        match self {
67            Self::Markets => "markets",
68            Self::Writes => "writes",
69            Self::Depth => "depth",
70            Self::Orders => "orders",
71        }
72    }
73}
74
75/// A job's request, resolved range, phase and outputs, as `GET /dataset-jobs/{job_id}` answers.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct DatasetJobStatusResponse {
78    /// The id the job is followed and cancelled by.
79    pub job_id: String,
80    /// First slot requested.
81    pub start_slot: u64,
82    /// Last slot requested.
83    pub end_slot: u64,
84    /// The requested range widened to whole bundles.
85    pub capture: SlotRange,
86    /// The dataset the job builds.
87    #[serde(flatten)]
88    pub dataset: DatasetJobSpec,
89    /// Where the job is.
90    #[serde(flatten)]
91    pub phase: DatasetJobPhase,
92    /// Where the job's datasets land; filled in as they are written.
93    pub outputs: Vec<DatasetLocation>,
94    /// When the job was created, in Unix milliseconds.
95    pub created_at_unix_ms: u64,
96}
97
98/// Where a job is, tagged by `phase` on the wire.
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(tag = "phase", rename_all = "snake_case")]
101pub enum DatasetJobPhase {
102    /// Building the bundles the range needs.
103    Building {
104        /// Bundles built so far.
105        bundles: Progress,
106    },
107    /// `sessions` is absent when they cannot be counted.
108    Running {
109        /// Sessions finished so far.
110        #[serde(default, skip_serializing_if = "Option::is_none")]
111        sessions: Option<Progress>,
112        /// The job this one waits on before it measures.
113        #[serde(default, skip_serializing_if = "Option::is_none")]
114        waiting_for: Option<String>,
115    },
116    /// Every output is written.
117    Completed,
118    /// The job stopped without finishing.
119    Failed {
120        /// Why it stopped.
121        reason: String,
122    },
123    /// Rows already written stay.
124    Cancelled,
125}
126
127impl DatasetJobPhase {
128    /// The wire value of `phase`.
129    pub fn as_str(&self) -> &'static str {
130        match self {
131            Self::Building { .. } => "building",
132            Self::Running { .. } => "running",
133            Self::Completed => "completed",
134            Self::Failed { .. } => "failed",
135            Self::Cancelled => "cancelled",
136        }
137    }
138
139    /// Whether the job has stopped for good.
140    pub fn is_terminal(&self) -> bool {
141        match self {
142            Self::Building { .. } | Self::Running { .. } => false,
143            Self::Completed | Self::Failed { .. } | Self::Cancelled => true,
144        }
145    }
146}
147
148/// A count of finished units out of the total.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150pub struct Progress {
151    /// Units finished.
152    pub done: usize,
153    /// Units the job needs.
154    pub total: usize,
155}
156
157/// A dataset under the `user_s3_uri` that `POST /datasets/credentials` returns, at
158/// `<name>/v<version>/`.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct DatasetLocation {
161    /// The dataset's name.
162    pub name: String,
163    /// The dataset's schema version.
164    pub version: u16,
165}
166
167impl fmt::Display for DatasetLocation {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        write!(f, "{}/v{}/", self.name, self.version)
170    }
171}
172
173/// The caller's jobs, as `GET /dataset-jobs` answers.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub struct DatasetJobListResponse {
176    /// Newest first.
177    pub jobs: Vec<DatasetJobStatusResponse>,
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::{DepthGranularity, DepthSource};
184
185    #[test]
186    fn a_status_carries_its_kind_and_phase_beside_its_fields() {
187        let status = DatasetJobStatusResponse {
188            job_id: "j".to_owned(),
189            start_slot: 100,
190            end_slot: 199,
191            capture: SlotRange::new_unchecked(90, 210),
192            dataset: DatasetJobSpec::EstimatedFills,
193            phase: DatasetJobPhase::Running {
194                sessions: Some(Progress { done: 1, total: 3 }),
195                waiting_for: None,
196            },
197            outputs: vec![DatasetLocation {
198                name: "estimated-fills".to_owned(),
199                version: 2,
200            }],
201            created_at_unix_ms: 7,
202        };
203        let wire = serde_json::json!({
204            "job_id": "j",
205            "start_slot": 100,
206            "end_slot": 199,
207            "capture": {"start": 90, "end": 210},
208            "kind": "estimated_fills",
209            "phase": "running",
210            "sessions": {"done": 1, "total": 3},
211            "outputs": [{"name": "estimated-fills", "version": 2}],
212            "created_at_unix_ms": 7,
213        });
214        assert_eq!(serde_json::to_value(&status).unwrap(), wire);
215        assert_eq!(
216            serde_json::from_value::<DatasetJobStatusResponse>(wire).unwrap(),
217            status
218        );
219    }
220
221    #[test]
222    fn a_running_phase_without_a_count_leaves_sessions_out() {
223        let wire = serde_json::json!({"phase": "running"});
224        let phase = DatasetJobPhase::Running {
225            sessions: None,
226            waiting_for: None,
227        };
228        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
229        assert_eq!(
230            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
231            phase
232        );
233    }
234
235    #[test]
236    fn a_waiting_job_names_the_job_it_waits_for() {
237        let phase = DatasetJobPhase::Running {
238            sessions: None,
239            waiting_for: Some("j2".to_owned()),
240        };
241        let wire = serde_json::json!({"phase": "running", "waiting_for": "j2"});
242        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
243        assert_eq!(
244            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
245            phase
246        );
247    }
248
249    #[test]
250    fn a_request_names_its_kind_and_range() {
251        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
252            "start_slot": 1,
253            "end_slot": 2,
254            "kind": "estimated_fills",
255        }))
256        .unwrap();
257        assert_eq!(request.dataset, DatasetJobSpec::EstimatedFills);
258        assert_eq!(request.slots, SlotRange::new_unchecked(1, 2));
259    }
260
261    #[test]
262    fn a_request_with_an_inverted_range_is_refused_as_it_is_read() {
263        let request = serde_json::from_value::<DatasetJobRequest>(serde_json::json!({
264            "start_slot": 2,
265            "end_slot": 1,
266            "kind": "estimated_fills",
267        }));
268
269        assert!(request.is_err());
270    }
271
272    #[test]
273    fn a_request_writes_its_range_as_start_and_end_slots() {
274        let request = DatasetJobRequest {
275            slots: SlotRange::new_unchecked(5, 9),
276            dataset: DatasetJobSpec::EstimatedFills,
277        };
278
279        assert_eq!(
280            serde_json::to_value(&request).unwrap(),
281            serde_json::json!({"start_slot": 5, "end_slot": 9, "kind": "estimated_fills"})
282        );
283    }
284
285    #[test]
286    fn a_predict_request_names_its_tables() {
287        let request = DatasetJobRequest {
288            slots: SlotRange::new_unchecked(1, 2),
289            dataset: DatasetJobSpec::Predict {
290                tables: BTreeSet::from([
291                    PredictTable::Orders,
292                    PredictTable::Depth,
293                    PredictTable::Markets,
294                ]),
295            },
296        };
297        let wire = serde_json::json!({
298            "start_slot": 1,
299            "end_slot": 2,
300            "kind": "predict",
301            "tables": ["markets", "depth", "orders"],
302        });
303        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
304        assert_eq!(
305            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
306            request
307        );
308    }
309
310    #[test]
311    fn a_depth_request_spells_its_options_as_generate_depth_does() {
312        let request = DatasetJobRequest {
313            slots: SlotRange::new_unchecked(1, 2),
314            dataset: DatasetJobSpec::Depth(DepthSelection {
315                source: DepthSource::Onchain,
316                granularity: DepthGranularity::Oracle,
317                markets: vec!["SOL-USDC".to_owned()],
318                ..DepthSelection::default()
319            }),
320        };
321        let wire = serde_json::json!({
322            "start_slot": 1,
323            "end_slot": 2,
324            "kind": "depth",
325            "source": "onchain",
326            "granularity": "oracle",
327            "markets": ["SOL-USDC"],
328        });
329        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
330        assert_eq!(
331            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
332            request
333        );
334    }
335
336    #[test]
337    fn a_depth_request_naming_only_its_kind_measures_every_onchain_market_by_slot() {
338        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
339            "start_slot": 1,
340            "end_slot": 2,
341            "kind": "depth",
342        }))
343        .unwrap();
344        assert_eq!(
345            request.dataset,
346            DatasetJobSpec::Depth(DepthSelection::default())
347        );
348    }
349}