forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

timestamp.rs190 lines, 7.2 KiBHistoryRawDownload
1//! Time policy for the whole backend, in one place.
2//!
3//! - Every instant is a **unix-millisecond `i64`, always UTC** — stored as a
4//! `BIGINT`, sent over the wire as a plain number. No timezone is ever
5//! stored or parsed, so the server's `TZ`, the client's locale, and the
6//! container's clock configuration cannot change what a value means.
7//! - [`Timestamp::now`] is the **only wall-clock read in the codebase**. The
8//! clippy `disallowed-methods` config (clippy.toml) rejects every other
9//! `now()` source (`chrono::Utc/Local`, `SystemTime`, `time::OffsetDateTime`)
10//! at lint time, so a stray local-time call cannot creep back in.
11//! - Durations that only pace things (rate limiter) use the monotonic
12//! `Instant` clock instead, which NTP adjustments cannot move backwards.
13
14use chrono::Datelike;
15
16use crate::constant::MILLIS_PER_DAY;
17use crate::error::{AppError, ValidationError};
18
19/// The one spelling of "this range is inverted", so the pre-flight check
20/// ([`crate::web::check_time_range`]) and the write-time `WHERE` guard that
21/// re-makes it against the stored row answer a client identically.
22pub(crate) fn range_error() -> AppError {
23 AppError::Validation(ValidationError::Invalid {
24 field: "ends_at",
25 reason: "must be at or after starts_at",
26 })
27}
28
29/// A unix-millisecond instant (UTC by construction). Stored as a `BIGINT`.
30/// Also serializes as its bare number: the fee plan's installments ride the
31/// row as JSON, and a due date must stay a plain millisecond count there too.
32#[derive(
33 Debug,
34 Clone,
35 Copy,
36 PartialEq,
37 Eq,
38 PartialOrd,
39 Ord,
40 sqlx::Type,
41 serde::Serialize,
42 serde::Deserialize,
43)]
44#[sqlx(transparent)]
45pub struct Timestamp(i64);
46
47impl Timestamp {
48 /// The sole wall-clock read. Everything else derives from this.
49 #[allow(clippy::disallowed_methods)] // the one permitted clock call
50 pub fn now() -> Self {
51 Self(chrono::Utc::now().timestamp_millis())
52 }
53
54 /// `now` shifted by whole days. UTC days are a fixed 86 400 000 ms (no
55 /// DST), so plain arithmetic is exact; saturating keeps absurd inputs
56 /// from panicking.
57 pub fn in_days(days: i64) -> Self {
58 Self(
59 Self::now()
60 .0
61 .saturating_add(days.saturating_mul(MILLIS_PER_DAY)),
62 )
63 }
64
65 pub fn from_millis(millis: i64) -> Self {
66 Self(millis)
67 }
68
69 pub fn as_millis(&self) -> i64 {
70 self.0
71 }
72
73 pub fn is_past(&self) -> bool {
74 self.0 < Self::now().0
75 }
76
77 /// Today's calendar date in UTC, derived from [`Timestamp::now`] so the
78 /// clock choke point stays single. Calendar-date validation (birth dates)
79 /// must leave a one-day grace around this — a client living ahead of UTC
80 /// (up to UTC+14) legitimately writes "tomorrow's" date on its wall.
81 pub fn today_utc() -> chrono::NaiveDate {
82 chrono::DateTime::from_timestamp_millis(Self::now().0)
83 .expect("current time is within chrono's representable range")
84 .date_naive()
85 }
86
87 /// *This* instant's UTC calendar day as a stable integer (days since the
88 /// Common Era epoch). The day a stored value can be compared and
89 /// incremented as an `int` — `day == stored + 1` is exactly "the next
90 /// day", with no string parsing and no month/year arithmetic.
91 ///
92 /// Takes the instant instead of reading the clock, which is what makes a
93 /// day-boundary rule testable without sleeping: [`Timestamp::now`] stays
94 /// the single clock read, and the caller derives the day from the same
95 /// stamp it already took. Midnight UTC is the boundary, like every other
96 /// day calculation here ([`Timestamp::today_utc`], menu dates, the meal
97 /// cutoff) — no timezone is stored anywhere, deliberately.
98 pub fn day_number(&self) -> i64 {
99 chrono::DateTime::from_timestamp_millis(self.0)
100 // Reachable only for an instant ±262 000 years from the epoch; the
101 // callers derive this from a server clock read.
102 .expect("timestamp is within chrono's representable range")
103 .date_naive()
104 .num_days_from_ce() as i64
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use super::*;
111
112 #[tokio::test]
113 async fn millis_roundtrip() {
114 assert_eq!(
115 Timestamp::from_millis(1_700_000_000_000).as_millis(),
116 1_700_000_000_000
117 );
118 }
119
120 #[tokio::test]
121 async fn ordering() {
122 assert!(Timestamp::from_millis(1) < Timestamp::from_millis(2));
123 }
124
125 #[tokio::test]
126 async fn expiry_direction() {
127 assert!(!Timestamp::in_days(1).is_past());
128 assert!(Timestamp::in_days(-1).is_past());
129 }
130
131 #[tokio::test]
132 async fn in_days_is_exact_utc_days() {
133 let before = Timestamp::now().as_millis();
134 let shifted = Timestamp::in_days(2).as_millis();
135 let after = Timestamp::now().as_millis();
136 assert!(shifted - before >= 2 * MILLIS_PER_DAY);
137 assert!(shifted - after <= 2 * MILLIS_PER_DAY);
138 }
139
140 #[tokio::test]
141 async fn in_days_saturates_instead_of_panicking() {
142 assert_eq!(Timestamp::in_days(i64::MAX).as_millis(), i64::MAX);
143 }
144
145 #[tokio::test]
146 async fn day_number_is_a_midnight_utc_day_counter() {
147 // The unix epoch, pinned: a drifting origin would silently shift every
148 // stored streak day.
149 let epoch = Timestamp::from_millis(0);
150 assert_eq!(epoch.day_number(), 719_163);
151 // Same UTC day, different hours — one day number.
152 assert_eq!(Timestamp::from_millis(86_399_999).day_number(), 719_163);
153 // The next millisecond is the next day, and a whole day is +1.
154 assert_eq!(Timestamp::from_millis(86_400_000).day_number(), 719_164);
155 assert_eq!(
156 Timestamp::from_millis(1_700_000_000_000 + MILLIS_PER_DAY).day_number(),
157 Timestamp::from_millis(1_700_000_000_000).day_number() + 1
158 );
159 // Before the epoch still counts forward.
160 assert_eq!(Timestamp::from_millis(-1).day_number(), 719_162);
161 // And it agrees with the crate's other day calculation. Not flaky: a
162 // day boundary between the two clock reads still leaves `<=`.
163 assert!(Timestamp::now().day_number() <= Timestamp::today_utc().num_days_from_ce() as i64);
164 }
165
166 #[tokio::test]
167 async fn today_utc_matches_now() {
168 let today = Timestamp::today_utc();
169 let from_millis = chrono::DateTime::from_timestamp_millis(Timestamp::now().as_millis())
170 .unwrap()
171 .date_naive();
172 // Not flaky: both reads happen within the same test, and a UTC day
173 // boundary crossing between them would still satisfy `<=`.
174 assert!(today <= from_millis);
175 }
176
177 /// JSON is part of the storage contract now (embedded installments ride a
178 /// JSONB column): the instant must stay a bare millisecond number, never
179 /// a string or an object.
180 #[test]
181 fn json_form_is_the_bare_millisecond_number() {
182 assert_eq!(
183 serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(),
184 serde_json::json!(1_700_000_000_000i64)
185 );
186 let back: Timestamp =
187 serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap();
188 assert_eq!(back.as_millis(), 1_700_000_000_000);
189 }
190}