prost_protovalidate/time.rs
1//! Time helpers shared between the runtime validator and code generated
2//! by `prost-protovalidate-build`.
3//!
4//! The single public entry point [`now_systemtime`] returns the current
5//! wall-clock time as a `prost_types::Timestamp`. Generated `Validate`
6//! impls for messages with `lt_now` / `gt_now` / `within` timestamp rules
7//! call this directly — the trait signature `fn validate(&self) -> …` has
8//! no place to inject a `now_fn`, so the compile-time path always reads
9//! `SystemTime::now()`. This matches the runtime `Validator`'s default
10//! configuration, which uses the same `SystemTime::now()` source via
11//! `ValidationConfig::now_fn`.
12//!
13//! **Test determinism**: for tests that need a deterministic `now`, use
14//! the runtime [`Validator`](crate::Validator) with a `now_fn` override.
15//! The compile-time `Validate::validate(&self)` path cannot accept an
16//! injected `now`.
17
18use prost_types::Timestamp;
19
20/// Current wall-clock time as a protobuf `Timestamp`.
21///
22/// Reads `std::time::SystemTime::now()` once per call.
23///
24/// # Pre-epoch fallback
25///
26/// When the system clock is before the Unix epoch (extremely rare,
27/// typically indicating a misconfigured system), `duration_since(UNIX_EPOCH)`
28/// returns an error and this function falls back to the Unix epoch
29/// (`seconds = 0, nanos = 0`) rather than panicking. Validation results
30/// for `timestamp.lt_now` / `timestamp.gt_now` against pre-epoch timestamps
31/// on such systems will be inverted — a pre-epoch `Timestamp` (negative
32/// `seconds`) will compare as "before the (epoch-treated-as) now", which
33/// matches reality only by accident. Use the runtime
34/// [`Validator`](crate::Validator) with a `NowFn` override
35/// ([`ValidatorOption::NowFn`](crate::ValidatorOption) or
36/// [`ValidationOption::NowFn`](crate::ValidationOption)) if you need
37/// defined behaviour on anomalous clocks.
38#[must_use]
39pub fn now_systemtime() -> Timestamp {
40 let now = std::time::SystemTime::now()
41 .duration_since(std::time::UNIX_EPOCH)
42 .unwrap_or_default();
43 // Both casts are semantically safe:
44 // - `as_secs()` since UNIX_EPOCH fits in `i64` for billions of years.
45 // - `subsec_nanos()` is always `< 1_000_000_000` which fits in `i32`.
46 #[allow(clippy::cast_possible_wrap)]
47 Timestamp {
48 seconds: now.as_secs() as i64,
49 nanos: now.subsec_nanos() as i32,
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn now_systemtime_returns_non_zero_after_epoch() {
59 let ts = now_systemtime();
60 // Any plausible wall-clock since 1970 has seconds well above zero.
61 assert!(ts.seconds > 1_000_000_000, "ts.seconds = {}", ts.seconds);
62 assert!(
63 (0..1_000_000_000).contains(&ts.nanos),
64 "ts.nanos = {} out of [0, 1e9)",
65 ts.nanos
66 );
67 }
68}