simulator-api 0.30.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
//! An inclusive slot range.
//!
//! Slot bounds travel in pairs through most of the pipeline. As two adjacent
//! `u64` parameters nothing stops a caller transposing them, and the ordering
//! invariant gets re-checked ad hoc (or not at all) at each layer. This carries
//! both together and checks once, at construction.

use std::fmt;

use serde::{Deserialize, Serialize};
use serde_with::{OneOrMany, formats::PreferOne, serde_as};

/// An inclusive `[start, end]` slot range. Construct via [`SlotRange::new`],
/// which rejects an inverted range, or [`SlotRange::new_unchecked`] where the
/// ordering is already guaranteed by the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SlotRange {
    start: u64,
    end: u64,
}

/// Why a pair of bounds isn't a valid range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("invalid range: start_slot {start} > end_slot {end}")]
pub struct InvertedSlotRange {
    #[allow(missing_docs)]
    pub start: u64,
    /// The requested end slot, below `start`.
    pub end: u64,
}

impl SlotRange {
    /// An inclusive range, rejecting `start > end`.
    pub fn new(start: u64, end: u64) -> Result<Self, InvertedSlotRange> {
        if start > end {
            return Err(InvertedSlotRange { start, end });
        }
        Ok(Self { start, end })
    }

    /// A range whose ordering the caller already guarantees — e.g. one derived
    /// from a `start` plus a non-zero count. Prefer [`SlotRange::new`].
    pub const fn new_unchecked(start: u64, end: u64) -> Self {
        Self { start, end }
    }

    /// The range covering `count` slots from `start`. `count` of 0 yields a
    /// single-slot range, matching how the callers' slot counts behave.
    pub const fn from_count(start: u64, count: u64) -> Self {
        Self {
            start,
            end: start.saturating_add(count.saturating_sub(1)),
        }
    }

    #[allow(missing_docs)]
    pub const fn start(&self) -> u64 {
        self.start
    }

    /// The last slot, inclusive.
    pub const fn end(&self) -> u64 {
        self.end
    }

    /// Number of slots covered, inclusive of both bounds.
    pub const fn len(&self) -> u64 {
        self.end - self.start + 1
    }

    /// Never true — an inclusive range always covers at least one slot. Present
    /// so `len()` doesn't trip `clippy::len_without_is_empty`.
    pub const fn is_empty(&self) -> bool {
        false
    }

    #[allow(missing_docs)]
    pub const fn contains(&self, slot: u64) -> bool {
        slot >= self.start && slot <= self.end
    }

    /// Whether the two ranges share at least one slot.
    pub const fn overlaps(&self, other: SlotRange) -> bool {
        self.start <= other.end && other.start <= self.end
    }

    /// Whether `other` lies wholly within this range.
    pub const fn covers(&self, other: SlotRange) -> bool {
        self.start <= other.start && other.end <= self.end
    }

    /// The slots both ranges share.
    pub fn intersection(self, other: SlotRange) -> Option<SlotRange> {
        self.overlaps(other).then(|| Self {
            start: self.start.max(other.start),
            end: self.end.min(other.end),
        })
    }
}

impl fmt::Display for SlotRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}..={}", self.start, self.end)
    }
}

impl From<SlotRange> for std::ops::RangeInclusive<u64> {
    fn from(range: SlotRange) -> Self {
        range.start..=range.end
    }
}

/// The slots an action may fire at: one [`SlotRange`] object or a list of them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "SlotWindowsWire", into = "SlotWindowsWire")]
pub struct SlotWindows(Vec<SlotRange>);

#[serde_as]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
struct SlotWindowsWire(#[serde_as(as = "OneOrMany<_, PreferOne>")] Vec<SlotRange>);

/// Slot windows were built from no range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("slot windows name no range")]
pub struct NoSlotWindows;

/// Why a set of ranges from the wire isn't valid slot windows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum InvalidSlotWindows {
    #[error(transparent)]
    #[allow(missing_docs)]
    Empty(#[from] NoSlotWindows),
    #[error(transparent)]
    #[allow(missing_docs)]
    Inverted(#[from] InvertedSlotRange),
}

impl SlotWindows {
    /// Sorts the ranges and merges those that overlap or touch.
    pub fn new(ranges: impl IntoIterator<Item = SlotRange>) -> Result<Self, NoSlotWindows> {
        let ranges = ranges.into_iter().collect::<Vec<_>>();
        if ranges.is_empty() {
            return Err(NoSlotWindows);
        }
        Ok(Self(merged(ranges)))
    }

    fn window_of(&self, slot: u64) -> Option<SlotRange> {
        let at = self.0.partition_point(|range| range.end < slot);
        self.0.get(at).copied().filter(|range| range.contains(slot))
    }

    #[allow(missing_docs)]
    pub fn contains(&self, slot: u64) -> bool {
        self.window_of(slot).is_some()
    }

    /// Whether a single window holds every slot of `range`.
    pub fn covers(&self, range: SlotRange) -> bool {
        self.window_of(range.start)
            .is_some_and(|window| window.covers(range))
    }

    /// The parts of these windows inside `range`, or `None` when they share no slot.
    pub fn intersection(&self, range: SlotRange) -> Option<Self> {
        Self::new(
            self.0
                .iter()
                .filter_map(|window| window.intersection(range)),
        )
        .ok()
    }
}

fn merged(mut ranges: Vec<SlotRange>) -> Vec<SlotRange> {
    ranges.sort();
    ranges
        .into_iter()
        .fold(Vec::new(), |mut merged: Vec<SlotRange>, next| {
            match merged.last_mut() {
                Some(last) if next.start <= last.end.saturating_add(1) => {
                    last.end = last.end.max(next.end);
                }
                _ => merged.push(next),
            }
            merged
        })
}

impl From<SlotRange> for SlotWindows {
    fn from(range: SlotRange) -> Self {
        Self(vec![range])
    }
}

impl TryFrom<SlotWindowsWire> for SlotWindows {
    type Error = InvalidSlotWindows;

    fn try_from(SlotWindowsWire(ranges): SlotWindowsWire) -> Result<Self, Self::Error> {
        let ranges = ranges
            .into_iter()
            .map(|range| SlotRange::new(range.start, range.end))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self::new(ranges)?)
    }
}

impl From<SlotWindows> for SlotWindowsWire {
    fn from(SlotWindows(ranges): SlotWindows) -> Self {
        Self(ranges)
    }
}

pub(crate) mod slot_bounds {
    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};

    use super::SlotRange;

    #[derive(Serialize, Deserialize)]
    struct SlotBounds {
        start_slot: u64,
        end_slot: u64,
    }

    pub(crate) fn serialize<S: Serializer>(
        slots: &SlotRange,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        SlotBounds {
            start_slot: slots.start,
            end_slot: slots.end,
        }
        .serialize(serializer)
    }

    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<SlotRange, D::Error> {
        let SlotBounds {
            start_slot,
            end_slot,
        } = SlotBounds::deserialize(deserializer)?;
        SlotRange::new(start_slot, end_slot).map_err(D::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    fn windows(ranges: &[(u64, u64)]) -> SlotWindows {
        SlotWindows::new(
            ranges
                .iter()
                .map(|&(start, end)| SlotRange::new_unchecked(start, end)),
        )
        .expect("windows")
    }

    #[test]
    fn one_window_writes_as_a_slot_range_and_several_as_a_list() {
        let one = windows(&[(5, 9)]);
        assert_eq!(
            serde_json::to_value(&one).unwrap(),
            serde_json::to_value(SlotRange::new_unchecked(5, 9)).unwrap()
        );
        let two = windows(&[(5, 9), (20, 30)]);
        let json = serde_json::to_value(&two).unwrap();
        assert!(json.is_array(), "{json}");
        for windows in [one, two] {
            let json = serde_json::to_string(&windows).unwrap();
            assert_eq!(serde_json::from_str::<SlotWindows>(&json).unwrap(), windows);
        }
        let listed = r#"[{"start":5,"end":9}]"#;
        assert_eq!(
            serde_json::from_str::<SlotWindows>(listed).unwrap(),
            windows(&[(5, 9)])
        );
    }

    #[rstest]
    #[case::empty_list("[]")]
    #[case::inverted_object(r#"{"start":10,"end":9}"#)]
    #[case::inverted_in_a_list(r#"[{"start":1,"end":2},{"start":10,"end":9}]"#)]
    fn windows_that_name_no_valid_range_are_rejected(#[case] json: &str) {
        assert!(serde_json::from_str::<SlotWindows>(json).is_err());
    }

    #[rstest]
    #[case::unsorted(&[(20, 30), (5, 9)], &[(5, 9), (20, 30)])]
    #[case::touching(&[(5, 9), (10, 12)], &[(5, 12)])]
    #[case::overlapping(&[(5, 15), (10, 12), (14, 20)], &[(5, 20)])]
    #[case::apart(&[(5, 9), (11, 12)], &[(5, 9), (11, 12)])]
    fn new_sorts_and_merges_ranges(#[case] given: &[(u64, u64)], #[case] kept: &[(u64, u64)]) {
        assert_eq!(windows(given), windows(kept));
    }

    #[test]
    fn no_ranges_make_no_windows() {
        assert_eq!(SlotWindows::new([]), Err(NoSlotWindows));
    }

    #[rstest]
    #[case::first_start(5, true)]
    #[case::first_end(9, true)]
    #[case::between(10, false)]
    #[case::second_start(20, true)]
    #[case::past_all(31, false)]
    #[case::before_all(4, false)]
    fn contains_finds_a_slot_in_any_window(#[case] slot: u64, #[case] expected: bool) {
        assert_eq!(windows(&[(5, 9), (20, 30)]).contains(slot), expected);
    }

    #[rstest]
    #[case::inside_one(22, 25, true)]
    #[case::the_whole_window(5, 9, true)]
    #[case::spans_the_gap(5, 30, false)]
    #[case::hangs_over(8, 12, false)]
    fn covers_needs_one_window_to_hold_the_range(
        #[case] start: u64,
        #[case] end: u64,
        #[case] expected: bool,
    ) {
        let range = SlotRange::new_unchecked(start, end);
        assert_eq!(windows(&[(5, 9), (20, 30)]).covers(range), expected);
    }

    #[rstest]
    #[case::clips_both(7, 25, Some(&[(7, 9), (20, 25)][..]))]
    #[case::inside_one(21, 22, Some(&[(21, 22)][..]))]
    #[case::in_the_gap(10, 19, None)]
    fn intersection_keeps_the_parts_inside_the_range(
        #[case] start: u64,
        #[case] end: u64,
        #[case] expected: Option<&[(u64, u64)]>,
    ) {
        let range = SlotRange::new_unchecked(start, end);
        assert_eq!(
            windows(&[(5, 9), (20, 30)]).intersection(range),
            expected.map(windows)
        );
    }

    #[test]
    fn an_inverted_range_is_rejected() {
        assert_eq!(
            SlotRange::new(10, 9),
            Err(InvertedSlotRange { start: 10, end: 9 })
        );
        assert!(SlotRange::new(10, 10).is_ok());
    }

    #[test]
    fn length_is_inclusive_of_both_bounds() {
        assert_eq!(SlotRange::new(10, 10).expect("range").len(), 1);
        assert_eq!(SlotRange::new(10, 19).expect("range").len(), 10);
    }

    #[test]
    fn from_count_matches_the_start_plus_count_convention() {
        assert_eq!(
            SlotRange::from_count(100, 1),
            SlotRange::new_unchecked(100, 100)
        );
        assert_eq!(
            SlotRange::from_count(100, 10),
            SlotRange::new_unchecked(100, 109)
        );
        // A zero count still covers the anchor slot rather than inverting.
        assert_eq!(
            SlotRange::from_count(100, 0),
            SlotRange::new_unchecked(100, 100)
        );
    }

    #[test]
    fn contains_is_inclusive() {
        let range = SlotRange::new(10, 12).expect("range");
        assert!(range.contains(10) && range.contains(12));
        assert!(!range.contains(9) && !range.contains(13));
    }

    #[rstest]
    #[case::shares_the_lower_bound(5, 10, true)]
    #[case::shares_the_upper_bound(12, 20, true)]
    #[case::lies_inside(11, 11, true)]
    #[case::encloses(0, 20, true)]
    #[case::ends_just_below(5, 9, false)]
    #[case::starts_just_above(13, 20, false)]
    fn overlaps_is_inclusive(#[case] start: u64, #[case] end: u64, #[case] expected: bool) {
        let range = SlotRange::new_unchecked(10, 12);
        let other = SlotRange::new_unchecked(start, end);
        assert_eq!(range.overlaps(other), expected);
        assert_eq!(other.overlaps(range), expected);
    }

    #[rstest]
    #[case::shares_the_lower_bound(5, 10, Some((10, 10)))]
    #[case::lies_inside(11, 11, Some((11, 11)))]
    #[case::encloses(0, 20, Some((10, 12)))]
    #[case::overhangs_the_end(11, 30, Some((11, 12)))]
    #[case::ends_just_below(5, 9, None)]
    fn intersection_keeps_the_shared_slots(
        #[case] start: u64,
        #[case] end: u64,
        #[case] expected: Option<(u64, u64)>,
    ) {
        let range = SlotRange::new_unchecked(10, 12);
        let other = SlotRange::new_unchecked(start, end);
        let expected = expected.map(|(start, end)| SlotRange::new_unchecked(start, end));
        assert_eq!(range.intersection(other), expected);
        assert_eq!(other.intersection(range), expected);
    }
}