1use std::{collections::BTreeSet, fmt};
4
5use serde::{Deserialize, Serialize};
6
7use crate::{DepthSelection, SlotRange};
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct DatasetJobRequest {
13 #[serde(flatten, with = "crate::slot_range::slot_bounds")]
15 pub slots: SlotRange,
16 #[serde(flatten)]
18 pub dataset: DatasetJobSpec,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(tag = "kind", rename_all = "snake_case")]
24pub enum DatasetJobSpec {
25 EstimatedFills,
27 Predict {
29 tables: BTreeSet<PredictTable>,
31 },
32 Depth(DepthSelection),
35}
36
37impl DatasetJobSpec {
38 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#[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 Markets,
55 Writes,
57 Depth,
59 Orders,
61}
62
63impl PredictTable {
64 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct DatasetJobStatusResponse {
78 pub job_id: String,
80 pub start_slot: u64,
82 pub end_slot: u64,
84 pub capture: SlotRange,
86 #[serde(flatten)]
88 pub dataset: DatasetJobSpec,
89 #[serde(flatten)]
91 pub phase: DatasetJobPhase,
92 pub outputs: Vec<DatasetLocation>,
94 pub created_at_unix_ms: u64,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100#[serde(tag = "phase", rename_all = "snake_case")]
101pub enum DatasetJobPhase {
102 Building {
104 bundles: Progress,
106 },
107 Running {
109 #[serde(default, skip_serializing_if = "Option::is_none")]
111 sessions: Option<Progress>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
114 waiting_for: Option<String>,
115 },
116 Completed,
118 Failed {
120 reason: String,
122 },
123 Cancelled,
125}
126
127impl DatasetJobPhase {
128 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150pub struct Progress {
151 pub done: usize,
153 pub total: usize,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct DatasetLocation {
161 pub name: String,
163 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175pub struct DatasetJobListResponse {
176 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}