summaryrefslogtreecommitdiffstats
path: root/src/time.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/time.rs')
-rw-r--r--src/time.rs69
1 files changed, 69 insertions, 0 deletions
diff --git a/src/time.rs b/src/time.rs
new file mode 100644
index 0000000..69fbc3c
--- /dev/null
+++ b/src/time.rs
@@ -0,0 +1,69 @@
+//! Clock helpers.
+//!
+//! DESIGN.md ยง16: "use DB time (`strftime` at write) for all ordering and audit
+//! stamps". We store timestamps as UTC ISO-8601 with second resolution so that
+//! lexicographic ordering equals chronological ordering, and every write path
+//! funnels through [`now`] so a test can pin the clock.
+
+use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
+
+/// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`.
+pub fn now() -> String {
+ // A test may pin the clock (see `pin`); production reads the real clock.
+ if let Some(pinned) = pinned() {
+ return pinned;
+ }
+ fmt(Utc::now())
+}
+
+fn fmt(t: DateTime<Utc>) -> String {
+ t.to_rfc3339_opts(SecondsFormat::Secs, true)
+}
+
+fn pinned() -> Option<String> {
+ CLOCK.with(|c| c.borrow().clone())
+}
+
+thread_local! {
+ static CLOCK: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
+}
+
+/// Pin the clock for the current thread (tests only). Returns the previous value.
+pub fn pin(ts: &str) -> Option<String> {
+ CLOCK.with(|c| {
+ let mut slot = c.borrow_mut();
+ (*slot).replace(ts.to_string())
+ })
+}
+
+/// Unpin the clock for the current thread.
+pub fn unpin() {
+ CLOCK.with(|c| *c.borrow_mut() = None);
+}
+
+/// Parse a DB timestamp back into a `DateTime<Utc>`.
+pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(ts)
+ .ok()
+ .map(|d| d.with_timezone(&Utc))
+ .or_else(|| {
+ chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S")
+ .ok()
+ .map(|n| Utc.from_utc_datetime(&n))
+ })
+}
+
+/// Whole seconds between two timestamps (`b - a`), or `None` if unparseable.
+pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
+ Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds())
+}
+
+/// A timestamp `secs` seconds in the past, canonical format.
+pub fn secs_ago(secs: i64) -> String {
+ fmt(Utc::now() - chrono::Duration::seconds(secs))
+}
+
+/// A timestamp `secs` seconds in the future, canonical format.
+pub fn secs_ahead(secs: i64) -> String {
+ fmt(Utc::now() + chrono::Duration::seconds(secs))
+}