Skip to main content

simulator_api/
datasets.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{InvertedSlotRange, SlotRange};
4
5/// With neither field, every one of the caller's own datasets.
6#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
7pub struct DatasetListQuery {
8    /// Only this dataset (e.g. `estimated-fills`), plus the shared dataset of that name.
9    #[serde(default, skip_serializing_if = "Option::is_none")]
10    pub dataset: Option<String>,
11    /// Only this version; requires `dataset`.
12    #[serde(default, skip_serializing_if = "Option::is_none")]
13    pub version: Option<u16>,
14}
15
16/// Response of `GET /datasets`.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct DatasetListResponse {
19    /// One entry per dataset and scope.
20    pub datasets: Vec<DatasetSummary>,
21}
22
23/// One dataset in one scope.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct DatasetSummary {
26    /// The dataset's name, e.g. `estimated-fills`.
27    pub name: String,
28    /// Whose copy of the dataset this lists.
29    pub scope: DatasetScope,
30    /// What the dataset holds.
31    #[serde(flatten)]
32    pub contents: DatasetContents,
33}
34
35/// Whose copy of a dataset a listing shows.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum DatasetScope {
39    /// Under the `user_s3_uri` of `POST /datasets/credentials`.
40    Own,
41    /// The dataset shared by every key.
42    Shared,
43}
44
45/// What a dataset holds, by how it is laid out.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(tag = "layout", rename_all = "snake_case")]
48pub enum DatasetContents {
49    /// Parquet parts.
50    Partitioned {
51        /// The partition key below each date, as the parts' paths name it.
52        partition_key: String,
53        /// The versions present, each with its own coverage.
54        versions: Vec<DatasetVersion>,
55    },
56    /// Whole files, such as a reroute run's database.
57    Files {
58        /// The files present.
59        files: Vec<DatasetFile>,
60    },
61}
62
63/// One version of a partitioned dataset.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct DatasetVersion {
66    /// The dataset version.
67    pub version: u16,
68    /// Sorted, with touching ranges merged.
69    pub coverage: Vec<SlotRange>,
70    /// Slots measured but waiting for their check: not readable yet, and in neither `coverage`
71    /// nor the parts.
72    #[serde(default, skip_serializing_if = "Vec::is_empty")]
73    pub checking: Vec<SlotRange>,
74    /// Slots measured and held by their check: not readable until the job named passes it, when
75    /// submitted again.
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub held: Vec<HeldSlots>,
78    /// Absent while the version holds only slots waiting for their check.
79    #[serde(flatten)]
80    pub parts: Option<DatasetParts>,
81    /// The version's parts by UTC date.
82    pub dates: Vec<DatasetDate>,
83}
84
85/// A slot range held by a job's check.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct HeldSlots {
88    /// The held slots.
89    pub slots: SlotRange,
90    /// The job whose check held them.
91    pub job_id: String,
92}
93
94/// One UTC date.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub struct DatasetDate {
97    /// The date, `YYYY-MM-DD`.
98    pub date: String,
99    /// The partitions with parts on that date.
100    pub partitions: Vec<DatasetPartition>,
101}
102
103/// The parts under one value of the dataset's partition key.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct DatasetPartition {
106    /// The partition key's value, e.g. a market.
107    pub value: String,
108    /// Sorted, with touching ranges merged.
109    pub coverage: Vec<SlotRange>,
110    /// The partition's parts.
111    #[serde(flatten)]
112    pub parts: DatasetParts,
113}
114
115/// A count and extent of parquet parts.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct DatasetParts {
118    /// How many parts.
119    pub parts: usize,
120    /// Ranges with no rows; their slots still count as covered.
121    pub empty_parts: usize,
122    /// Their total size.
123    pub bytes: u64,
124    /// When the first part was written.
125    pub first_written_unix_ms: u64,
126    /// When the last part was written.
127    pub last_written_unix_ms: u64,
128    /// When the earliest part expires; absent for shared datasets.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub available_until_unix_ms: Option<u64>,
131}
132
133/// One file of a files dataset.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135pub struct DatasetFile {
136    /// Relative to the dataset.
137    pub path: String,
138    /// The session's slots, when its path names them.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub slots: Option<SlotRange>,
141    /// The file's size.
142    pub bytes: u64,
143    /// When the file was written.
144    pub written_unix_ms: u64,
145    /// When the file expires; absent for shared datasets.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub available_until_unix_ms: Option<u64>,
148}
149
150/// Query of `DELETE /datasets`.
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(try_from = "DeleteQuery", into = "DeleteQuery")]
153pub struct DatasetDeleteRequest {
154    /// The dataset as `GET /datasets` names it.
155    pub dataset: String,
156    /// The slots to remove.
157    pub slots: SlotRange,
158    /// Only this version; absent takes the range out of every version.
159    pub version: Option<u16>,
160}
161
162/// Flat form of the request: a query string carries no nested range.
163#[derive(Serialize, Deserialize)]
164struct DeleteQuery {
165    dataset: String,
166    start_slot: u64,
167    end_slot: u64,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    version: Option<u16>,
170}
171
172impl TryFrom<DeleteQuery> for DatasetDeleteRequest {
173    type Error = InvertedSlotRange;
174
175    fn try_from(query: DeleteQuery) -> Result<Self, Self::Error> {
176        let DeleteQuery {
177            dataset,
178            start_slot,
179            end_slot,
180            version,
181        } = query;
182        Ok(Self {
183            dataset,
184            slots: SlotRange::new(start_slot, end_slot)?,
185            version,
186        })
187    }
188}
189
190impl From<DatasetDeleteRequest> for DeleteQuery {
191    fn from(request: DatasetDeleteRequest) -> Self {
192        let DatasetDeleteRequest {
193            dataset,
194            slots,
195            version,
196        } = request;
197        Self {
198            dataset,
199            start_slot: slots.start(),
200            end_slot: slots.end(),
201            version,
202        }
203    }
204}
205
206/// Anything reaching past either end of the range stays.
207#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
208pub struct DatasetDeleteResponse {
209    /// How many parquet parts were removed.
210    pub parts: usize,
211    /// How many of them held no rows.
212    pub empty_parts: usize,
213    /// How many whole files were removed.
214    pub files: usize,
215    /// Their total size.
216    pub bytes: u64,
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    fn round_trips<T>(value: &T, wire: serde_json::Value)
224    where
225        T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug,
226    {
227        assert_eq!(serde_json::to_value(value).unwrap(), wire);
228        assert_eq!(&serde_json::from_value::<T>(wire).unwrap(), value);
229    }
230
231    fn parts(available_until_unix_ms: Option<u64>) -> DatasetParts {
232        DatasetParts {
233            parts: 2,
234            empty_parts: 1,
235            bytes: 300,
236            first_written_unix_ms: 10,
237            last_written_unix_ms: 20,
238            available_until_unix_ms,
239        }
240    }
241
242    #[test]
243    fn a_partitioned_dataset_carries_its_layout_and_part_counts_beside_its_fields() {
244        let coverage = vec![SlotRange::new_unchecked(100, 199)];
245        let summary = DatasetSummary {
246            name: "estimated-fills".to_owned(),
247            scope: DatasetScope::Own,
248            contents: DatasetContents::Partitioned {
249                partition_key: "market".to_owned(),
250                versions: vec![DatasetVersion {
251                    version: 2,
252                    coverage: coverage.clone(),
253                    checking: vec![SlotRange::new_unchecked(200, 299)],
254                    held: Vec::new(),
255                    parts: Some(parts(Some(30))),
256                    dates: vec![DatasetDate {
257                        date: "2026-10-19".to_owned(),
258                        partitions: vec![DatasetPartition {
259                            value: "SOL-USDC".to_owned(),
260                            coverage,
261                            parts: parts(Some(30)),
262                        }],
263                    }],
264                }],
265            },
266        };
267        round_trips(
268            &summary,
269            serde_json::json!({
270                "name": "estimated-fills",
271                "scope": "own",
272                "layout": "partitioned",
273                "partition_key": "market",
274                "versions": [{
275                    "version": 2,
276                    "coverage": [{"start": 100, "end": 199}],
277                    "checking": [{"start": 200, "end": 299}],
278                    "parts": 2,
279                    "empty_parts": 1,
280                    "bytes": 300,
281                    "first_written_unix_ms": 10,
282                    "last_written_unix_ms": 20,
283                    "available_until_unix_ms": 30,
284                    "dates": [{
285                        "date": "2026-10-19",
286                        "partitions": [{
287                            "value": "SOL-USDC",
288                            "coverage": [{"start": 100, "end": 199}],
289                            "parts": 2,
290                            "empty_parts": 1,
291                            "bytes": 300,
292                            "first_written_unix_ms": 10,
293                            "last_written_unix_ms": 20,
294                            "available_until_unix_ms": 30,
295                        }],
296                    }],
297                }],
298            }),
299        );
300    }
301
302    #[test]
303    fn a_version_only_waiting_for_its_check_has_no_parts() {
304        round_trips(
305            &DatasetVersion {
306                version: 2,
307                coverage: Vec::new(),
308                checking: vec![SlotRange::new_unchecked(200, 299)],
309                held: vec![HeldSlots {
310                    slots: SlotRange::new_unchecked(300, 399),
311                    job_id: "j".to_owned(),
312                }],
313                parts: None,
314                dates: Vec::new(),
315            },
316            serde_json::json!({
317                "version": 2,
318                "coverage": [],
319                "checking": [{"start": 200, "end": 299}],
320                "held": [{"slots": {"start": 300, "end": 399}, "job_id": "j"}],
321                "dates": [],
322            }),
323        );
324    }
325
326    #[test]
327    fn a_shared_file_dataset_has_no_end_to_its_availability() {
328        let summary = DatasetSummary {
329            name: "reroute".to_owned(),
330            scope: DatasetScope::Shared,
331            contents: DatasetContents::Files {
332                files: vec![DatasetFile {
333                    path: "my-run.sqlite".to_owned(),
334                    slots: None,
335                    bytes: 5,
336                    written_unix_ms: 7,
337                    available_until_unix_ms: None,
338                }],
339            },
340        };
341        round_trips(
342            &summary,
343            serde_json::json!({
344                "name": "reroute",
345                "scope": "shared",
346                "layout": "files",
347                "files": [{"path": "my-run.sqlite", "bytes": 5, "written_unix_ms": 7}],
348            }),
349        );
350    }
351
352    #[test]
353    fn an_empty_query_lists_everything_of_ones_own() {
354        let query: DatasetListQuery = serde_json::from_value(serde_json::json!({})).unwrap();
355        assert_eq!(query, DatasetListQuery::default());
356        round_trips(
357            &DatasetListQuery {
358                dataset: Some("estimated-fills".to_owned()),
359                version: Some(2),
360            },
361            serde_json::json!({"dataset": "estimated-fills", "version": 2}),
362        );
363    }
364
365    #[test]
366    fn a_delete_names_its_dataset_range_and_any_version() {
367        round_trips(
368            &DatasetDeleteRequest {
369                dataset: "reroute".to_owned(),
370                slots: SlotRange::new_unchecked(1, 22),
371                version: None,
372            },
373            serde_json::json!({"dataset": "reroute", "start_slot": 1, "end_slot": 22}),
374        );
375        round_trips(
376            &DatasetDeleteResponse {
377                parts: 3,
378                empty_parts: 1,
379                files: 0,
380                bytes: 220,
381            },
382            serde_json::json!({"parts": 3, "empty_parts": 1, "files": 0, "bytes": 220}),
383        );
384    }
385
386    #[test]
387    fn a_delete_of_an_inverted_range_is_refused_as_it_is_read() {
388        let request = serde_json::from_value::<DatasetDeleteRequest>(
389            serde_json::json!({"dataset": "reroute", "start_slot": 22, "end_slot": 1}),
390        );
391
392        assert!(request.is_err());
393    }
394}