Skip to main content

simulator_client/
ranges.rs

1use std::{error::Error, str::FromStr};
2
3use chrono::{DateTime, NaiveDate, TimeZone, Utc};
4use simulator_api::AvailableRange;
5
6/// A slot number or a UTC timestamp, used to filter available ranges.
7#[derive(Debug, Clone)]
8#[allow(missing_docs)]
9pub enum RangeBound {
10    Slot(u64),
11    Time(DateTime<Utc>),
12}
13
14/// A string that is not a slot number, an RFC 3339 timestamp or a `YYYY-MM-DD` date.
15#[derive(Debug)]
16pub struct ParseRangeBoundError(String);
17
18impl std::fmt::Display for ParseRangeBoundError {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        f.write_str(&self.0)
21    }
22}
23
24impl Error for ParseRangeBoundError {}
25
26impl FromStr for RangeBound {
27    type Err = ParseRangeBoundError;
28
29    /// Parse from a string: tries a raw slot number first, then RFC 3339,
30    /// then date-only "YYYY-MM-DD" (interpreted as midnight UTC).
31    fn from_str(s: &str) -> Result<Self, Self::Err> {
32        if let Ok(slot) = s.parse::<u64>() {
33            return Ok(Self::Slot(slot));
34        }
35        if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
36            return Ok(Self::Time(dt.with_timezone(&Utc)));
37        }
38        if let Ok(date) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
39            let dt = Utc.from_utc_datetime(&date.and_hms_opt(0, 0, 0).unwrap());
40            return Ok(Self::Time(dt));
41        }
42        Err(ParseRangeBoundError(format!(
43            "could not parse {s:?} as a slot number, RFC 3339 timestamp, or YYYY-MM-DD date"
44        )))
45    }
46}
47
48/// Filter `ranges` to those bookended by `[after, before]`:
49/// - `after`: keep only ranges whose start is at or after this bound
50/// - `before`: keep only ranges whose end is at or before this bound
51///
52/// When a bound is a [`RangeBound::Time`], the range's UTC timestamp fields are used;
53/// ranges that have no UTC timestamp for the relevant boundary are kept (conservative).
54/// When a bound is a [`RangeBound::Slot`], slot fields are used directly.
55pub fn filter_ranges(
56    ranges: &[AvailableRange],
57    after: Option<&RangeBound>,
58    before: Option<&RangeBound>,
59) -> Vec<AvailableRange> {
60    let mut out = ranges.to_vec();
61
62    if let Some(bound) = after {
63        out.retain(|r| starts_after(r, bound));
64    }
65    if let Some(bound) = before {
66        out.retain(|r| ends_before(r, bound));
67    }
68
69    out
70}
71
72fn ends_before(r: &AvailableRange, bound: &RangeBound) -> bool {
73    match bound {
74        RangeBound::Slot(slot) => r.max_bundle_end_slot.is_none_or(|end| end <= *slot),
75        RangeBound::Time(time) => match &r.max_bundle_end_slot_utc {
76            None => true, // unbounded or unknown — keep it
77            Some(utc_str) => parse_utc(utc_str).is_none_or(|end| end <= *time),
78        },
79    }
80}
81
82fn starts_after(r: &AvailableRange, bound: &RangeBound) -> bool {
83    match bound {
84        RangeBound::Slot(slot) => r.bundle_start_slot >= *slot,
85        RangeBound::Time(time) => match &r.bundle_start_slot_utc {
86            None => true, // unknown — keep it
87            Some(utc_str) => parse_utc(utc_str).is_none_or(|start| start >= *time),
88        },
89    }
90}
91
92fn parse_utc(s: &str) -> Option<DateTime<Utc>> {
93    DateTime::parse_from_rfc3339(s)
94        .ok()
95        .map(|dt| dt.with_timezone(&Utc))
96}