Skip to main content

spoolframe_types/
serde_time.rs

1//! Times and spans on the wire, and in what the SDK keeps on disk, as one
2//! integer each, so every client language reads them without serde's
3//! `{secs, nanos}` struct: `#[serde(with = "serde_time::unix_seconds")]`
4//! on a `SystemTime`, `serde_time::millis` on a `Duration`, and each
5//! one's `option` on an `Option`. A field keeps its old wire name with
6//! `rename` (`position_ms`), so the wire and the stores do not change.
7//!
8//! An `Option` comes two ways, and the module says which:
9//! `option_required` for a field the wire must carry (`null` for none),
10//! `option` for one read as none when left out. Serde cannot give a
11//! `with` field a default, so `option` goes with `#[serde(default)]`; a
12//! test here finds any `option` field in the workspace without it.
13//!
14//! A time this platform cannot hold is refused when read, never a panic:
15//! on wasm32 (the web UI) a `SystemTime` cannot go before the epoch, so a
16//! peer's `-1` is a decode error there.
17
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use serde::{Deserialize, Deserializer, Serialize, Serializer};
21
22/// `at` as a signed span from the Unix epoch, held to `i64` either way.
23/// A time before the epoch truncates toward it: 1.5 s before is `-1`.
24fn from_epoch(at: SystemTime, unit: fn(Duration) -> u128) -> i64 {
25    match at.duration_since(UNIX_EPOCH) {
26        Ok(after) => i64::try_from(unit(after)).unwrap_or(i64::MAX),
27        Err(before) => i64::try_from(unit(before.duration())).map_or(i64::MIN, |n| -n),
28    }
29}
30
31/// `n` units from the Unix epoch; `None` when this platform's
32/// `SystemTime` cannot hold it.
33fn at_epoch(n: i64, unit: fn(u64) -> Duration) -> Option<SystemTime> {
34    let span = unit(n.unsigned_abs());
35    if n < 0 {
36        UNIX_EPOCH.checked_sub(span)
37    } else {
38        UNIX_EPOCH.checked_add(span)
39    }
40}
41
42/// The Unix epoch, for `#[serde(default = "...")]` on a `SystemTime`
43/// (which has no `Default`): older than any time kept.
44pub fn epoch() -> SystemTime {
45    UNIX_EPOCH
46}
47
48/// `n` read off the wire, or the decode error for one this platform
49/// cannot hold.
50fn held<T, E: serde::de::Error>(value: Option<T>, n: impl std::fmt::Display) -> Result<T, E> {
51    value.ok_or_else(|| E::custom(format_args!("time {n} is out of range here")))
52}
53
54/// A module's `serialize`/`deserialize` for `$ty` as `$wire`, and its
55/// `option` and `option_required` modules.
56macro_rules! serde_with {
57    ($ty:ty, $wire:ty) => {
58        pub fn serialize<S: Serializer>(value: &$ty, s: S) -> Result<S::Ok, S::Error> {
59            to_wire(*value).serialize(s)
60        }
61
62        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<$ty, D::Error> {
63            let n = <$wire>::deserialize(d)?;
64            held(try_from_wire(n), n)
65        }
66
67        /// An `Option` read as none when left out: with
68        /// `#[serde(default)]`.
69        pub mod option {
70            use super::*;
71
72            pub fn serialize<S: Serializer>(value: &Option<$ty>, s: S) -> Result<S::Ok, S::Error> {
73                value.map(to_wire).serialize(s)
74            }
75
76            pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
77                Option::<$wire>::deserialize(d)?
78                    .map(|n| held(try_from_wire(n), n))
79                    .transpose()
80            }
81        }
82
83        /// An `Option` the wire must carry, `null` for none.
84        pub mod option_required {
85            pub use super::option::{deserialize, serialize};
86        }
87    };
88}
89
90/// A point in time as a whole count of `$unit` since the Unix epoch.
91macro_rules! unix_time {
92    ($(#[$doc:meta])* $name:ident, $as_units:expr, $from_units:path) => {
93        $(#[$doc])*
94        pub mod $name {
95            use super::*;
96
97            pub fn to_wire(at: SystemTime) -> i64 {
98                from_epoch(at, $as_units)
99            }
100
101            /// `n` as a time; `None` when this platform cannot hold it.
102            pub fn try_from_wire(n: i64) -> Option<SystemTime> {
103                at_epoch(n, $from_units)
104            }
105
106            /// `n` as a time, for a value of this program's own (a
107            /// database row, a store): the epoch for one this platform
108            /// cannot hold. The one way from a stored count to a time.
109            pub fn from_wire(n: i64) -> SystemTime {
110                try_from_wire(n).unwrap_or(UNIX_EPOCH)
111            }
112
113            /// Now, to this unit: what is kept reads back equal.
114            pub fn now() -> SystemTime {
115                from_wire(to_wire(SystemTime::now()))
116            }
117
118            serde_with!(SystemTime, i64);
119        }
120    };
121}
122
123unix_time!(
124    /// A point in time as whole seconds since the Unix epoch.
125    unix_seconds,
126    |d| u128::from(d.as_secs()),
127    Duration::from_secs
128);
129
130unix_time!(
131    /// A point in time as whole milliseconds since the Unix epoch.
132    unix_millis,
133    |d| d.as_millis(),
134    Duration::from_millis
135);
136
137/// A span as whole milliseconds.
138pub mod millis {
139    use super::*;
140
141    pub fn to_wire(span: Duration) -> u64 {
142        u64::try_from(span.as_millis()).unwrap_or(u64::MAX)
143    }
144
145    pub fn from_wire(millis: u64) -> Duration {
146        Duration::from_millis(millis)
147    }
148
149    /// Every count of milliseconds is a `Duration`.
150    fn try_from_wire(millis: u64) -> Option<Duration> {
151        Some(from_wire(millis))
152    }
153
154    /// `span` to the whole millisecond: what is kept reads back equal.
155    pub fn whole(span: Duration) -> Duration {
156        from_wire(to_wire(span))
157    }
158
159    serde_with!(Duration, u64);
160}
161
162#[cfg(test)]
163mod tests {
164    use serde::{Deserialize, Serialize};
165    use serde_json::json;
166
167    use super::*;
168
169    #[derive(Debug, PartialEq, Serialize, Deserialize)]
170    struct Times {
171        #[serde(rename = "at", with = "unix_seconds")]
172        seconds: SystemTime,
173        #[serde(with = "unix_seconds::option_required")]
174        seconds_none: Option<SystemTime>,
175        #[serde(with = "unix_millis")]
176        millis_at: SystemTime,
177        #[serde(default, with = "unix_millis::option")]
178        millis_at_some: Option<SystemTime>,
179        #[serde(with = "millis")]
180        span: Duration,
181        #[serde(default, with = "millis::option")]
182        span_some: Option<Duration>,
183    }
184
185    fn times() -> Times {
186        Times {
187            seconds: UNIX_EPOCH + Duration::from_secs(1_761_700_000),
188            seconds_none: None,
189            millis_at: UNIX_EPOCH + Duration::from_millis(1_761_700_000_123),
190            millis_at_some: Some(UNIX_EPOCH - Duration::from_millis(1_500)),
191            span: Duration::from_millis(258_865),
192            span_some: Some(Duration::from_millis(7)),
193        }
194    }
195
196    /// Each helper writes one integer in its unit and reads it back.
197    #[test]
198    fn each_helper_writes_one_integer_and_reads_it_back() {
199        let wire = json!({
200            "at": 1_761_700_000,
201            "seconds_none": null,
202            "millis_at": 1_761_700_000_123_i64,
203            "millis_at_some": -1_500,
204            "span": 258_865,
205            "span_some": 7,
206        });
207        assert_eq!(serde_json::to_value(times()).unwrap(), wire);
208        assert_eq!(serde_json::from_value::<Times>(wire).unwrap(), times());
209    }
210
211    /// A time before the epoch is negative, truncated toward the epoch.
212    #[test]
213    fn a_time_before_the_epoch_is_negative() {
214        let at = UNIX_EPOCH - Duration::from_secs(90);
215        assert_eq!(unix_seconds::to_wire(at), -90);
216        assert_eq!(unix_seconds::from_wire(-90), at);
217        let between = UNIX_EPOCH - Duration::from_millis(1_500);
218        assert_eq!(unix_seconds::to_wire(between), -1);
219    }
220
221    /// A time the platform cannot hold is a decode error, not a panic.
222    /// On wasm32 that is any time before the epoch; this platform holds
223    /// every `i64` of seconds, so the extremes decode here, and the
224    /// refusal is checked where it is made.
225    #[test]
226    fn a_time_out_of_range_is_refused_not_a_panic() {
227        for n in [i64::MIN, -1, i64::MAX] {
228            let mut wire = serde_json::to_value(times()).unwrap();
229            wire["at"] = json!(n);
230            wire["seconds_none"] = json!(n);
231            wire["millis_at"] = json!(n);
232            serde_json::from_value::<Times>(wire).unwrap();
233        }
234        let refused = held::<SystemTime, serde_json::Error>(None, -1).unwrap_err();
235        assert_eq!(refused.to_string(), "time -1 is out of range here");
236    }
237
238    /// An `Option` with `with` is required, as `required::option` makes
239    /// one: left out, it is refused, not read as none.
240    #[test]
241    fn an_option_left_out_is_refused() {
242        let mut wire = serde_json::to_value(times()).unwrap();
243        wire.as_object_mut().unwrap().remove("seconds_none");
244        let error = serde_json::from_value::<Times>(wire).unwrap_err();
245        assert!(error.to_string().contains("missing field"), "{error}");
246    }
247
248    /// Whole units read back equal: `now` and `whole` drop what a store
249    /// would.
250    #[test]
251    fn whole_units_read_back_equal() {
252        let now = unix_seconds::now();
253        assert_eq!(unix_seconds::from_wire(unix_seconds::to_wire(now)), now);
254        let span = Duration::from_micros(61_234_567);
255        assert_eq!(millis::whole(span), Duration::from_millis(61_234));
256    }
257
258    /// Every `option` field in the workspace has `default`: serde gives a
259    /// `with` field none of its own, and one left out would fail to read.
260    /// A field the wire must carry says `option_required` instead.
261    #[test]
262    fn every_optional_time_field_has_a_default() {
263        let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
264        let mut missing = Vec::new();
265        let mut stack = vec![crates];
266        while let Some(dir) = stack.pop() {
267            for entry in std::fs::read_dir(&dir).unwrap().flatten() {
268                let path = entry.path();
269                let name = entry.file_name();
270                if path.is_dir() && name != "target" && name != "node_modules" {
271                    stack.push(path);
272                } else if path.extension().is_some_and(|e| e == "rs") {
273                    let text = std::fs::read_to_string(&path).unwrap();
274                    let lines: Vec<&str> = text.lines().collect();
275                    for (n, line) in lines.iter().enumerate() {
276                        let optional = ["seconds::option\"", "millis::option\""]
277                            .iter()
278                            .any(|m| line.contains(m));
279                        // The attribute, over the lines it takes.
280                        let from = (0..=n)
281                            .rev()
282                            .take(5)
283                            .find(|&i| lines[i].contains("#[serde("));
284                        let defaulted = from.is_some_and(|from| {
285                            lines[from..=n].iter().any(|l| l.contains("default"))
286                        });
287                        if optional && from.is_some() && !defaulted {
288                            missing.push(format!("{}:{}", path.display(), n + 1));
289                        }
290                    }
291                }
292            }
293        }
294        assert!(
295            missing.is_empty(),
296            "`option` without `default`: {missing:?}"
297        );
298    }
299}