diff --git a/CLAUDE.md b/CLAUDE.md index cc88ca4f..58e96585 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,6 +22,7 @@ Keep it practical: commands that work, where code lives, and project-specific co - Keep CI green: `cargo fmt --all -- --check`, `cargo clippy --all-targets --all-features -- -D warnings`, and `cargo test --all-features` must pass. - Don’t commit secrets. Local profiles like `settings/dev.toml` are intentionally gitignored. - Treat `src/entity/` and SeaORM active enums as generated artifacts unless you are intentionally regenerating them. +- Dates and times use `jiff`. `chrono` is not a direct dependency: SeaORM's `DateTime` and `DateTimeUtc` are chrono types, so convert them with `src/util/time.rs` as a value leaves an entity or enters a query, and don't call chrono methods on them anywhere else. - If you need to change DB schema expectations, update migrations/tests/scripts accordingly (they’re tightly coupled). ## Development Workflow (TDD) diff --git a/Cargo.lock b/Cargo.lock index 63aab71c..e21b9b1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -737,7 +737,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b9f7252833d5ed4b00aa9604b563529dd5e11de9c23615de2dcdf91eb87b52" dependencies = [ "async-compression", - "chrono", "crc32fast", "futures-lite", "pin-project", @@ -2172,7 +2171,6 @@ version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6be833b323a56361118a747470a45a1bcd5c52a2ec9b1e40c83dafe687e453" dependencies = [ - "chrono", "deunicode", "dummy", "either", @@ -7928,7 +7926,6 @@ dependencies = [ "bcrypt", "bytes", "chacha20poly1305", - "chrono", "config", "dashmap", "dotenvy", @@ -7944,6 +7941,7 @@ dependencies = [ "insta", "ipnet", "itertools 0.15.0", + "jiff", "jsonschema", "jsonwebtoken", "libc", diff --git a/Cargo.toml b/Cargo.toml index f62ee449..2b0c416c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,12 +68,12 @@ rustls-acme = { version = "0.15", features = ["axum", "tokio", "tower"] } base64 = "0.23" chacha20poly1305 = { version = "0.11", features = ["alloc"] } bcrypt = "0.19" -chrono = "0.4" +jiff = { version = "0.2", features = ["serde"] } # Resolve the host OS IANA timezone name for GET /system/locale (#33). iana-time-zone = "0.1" config = "0.15" dotenvy = "0.15" -fake = { version = "5", features = ["derive", "uuid", "chrono"] } +fake = { version = "5", features = ["derive", "uuid"] } futures = "0.3" futures-util = "0.3" # Not "full": that would pull phone-number (RUSTSEC-flagged quick-xml 0.38 via @@ -163,7 +163,7 @@ ipnet = "2.12" # Low-level libc bindings for PR_SET_PDEATHSIG libc = "0.2" -async_zip = { version = "0.0.17", features = ["tokio", "deflate", "chrono"] } +async_zip = { version = "0.0.17", features = ["tokio", "deflate"] } [dependencies.sea-orm] version = "2" diff --git a/src/daemon/ipc/socket.rs b/src/daemon/ipc/socket.rs index 4be3f1fd..a59729a7 100644 --- a/src/daemon/ipc/socket.rs +++ b/src/daemon/ipc/socket.rs @@ -1,5 +1,6 @@ //! Unix domain socket server for legacy IPC compatibility. +use jiff::civil::DateTime as Civil; use std::path::PathBuf; use std::sync::Arc; @@ -335,20 +336,31 @@ async fn execute_command(cmd: DaemonCommand, manager: &Arc) -> Da } } +/// The local wall-clock at which a process with this uptime started. The +/// subtraction is on the instant, so a DST change in between does not shift it. +fn started_at(now: jiff::Timestamp, uptime_seconds: u64, zone: &jiff::tz::TimeZone) -> Civil { + let uptime = jiff::SignedDuration::from_secs(i64::try_from(uptime_seconds).unwrap_or(i64::MAX)); + now.saturating_sub(uptime) + .unwrap_or(now) + .to_zoned(zone.clone()) + .datetime() +} + /// zmdc.pl's `status` output, line for line: the web console looks for /// `'' running` in it (#83). fn legacy_status_text(status: &SystemStatus) -> String { - let now = chrono::Local::now(); + let now = jiff::Timestamp::now(); + let zone = jiff::tz::TimeZone::system(); status .daemons .iter() .map(|d| match d.state { ProcessState::Running | ProcessState::Starting => { - let since = now - chrono::Duration::seconds(d.uptime_seconds.unwrap_or(0) as i64); + let since = started_at(now, d.uptime_seconds.unwrap_or(0), &zone); format!( "'{}' running since {}, pid = {}", d.id, - since.format("%y/%m/%d %H:%M:%S"), + since.strftime("%y/%m/%d %H:%M:%S"), d.pid.unwrap_or(0) ) } @@ -362,6 +374,20 @@ fn legacy_status_text(status: &SystemStatus) -> String { #[cfg(test)] mod tests { use super::*; + + /// 03:30 in New York just after the clocks went forward: two hours earlier + /// was 00:30, not the 01:30 that wall-clock subtraction gives. + #[test] + fn a_start_time_is_right_across_a_dst_change() { + let zone = jiff::tz::TimeZone::get("America/New_York").unwrap(); + let now: jiff::Timestamp = "2026-03-08T07:30:00Z".parse().unwrap(); + assert_eq!( + started_at(now, 2 * 3600, &zone), + jiff::civil::date(2026, 3, 8).at(0, 30, 0, 0) + ); + // An uptime too large to subtract leaves the earliest instant jiff has. + assert!(started_at(now, u64::MAX, &zone) < jiff::civil::date(1, 1, 1).at(0, 0, 0, 0)); + } use crate::daemon::config::DaemonConfig; use crate::daemon::ManagedProcess; diff --git a/src/daemon/onvif_event_listener.rs b/src/daemon/onvif_event_listener.rs index a3aff089..ed0a728f 100644 --- a/src/daemon/onvif_event_listener.rs +++ b/src/daemon/onvif_event_listener.rs @@ -324,18 +324,17 @@ impl MonitorEventListener { /// Insert a new ZM `Events` row for an opened alarm, returning its id. async fn open_event(&self, msg: &NotificationMessage) -> Result { - let start = - parse_utc(msg.utc_time.as_deref()).unwrap_or_else(|| chrono::Utc::now().naive_utc()); + let start = parse_utc(msg.utc_time.as_deref()).unwrap_or_else(crate::util::time::utc_now); let active = events::ActiveModel { monitor_id: Set(self.monitor_id), name: Set(format!( "ONVIF-{}-{}", self.monitor_id, - start.format("%Y%m%d%H%M%S") + start.strftime("%Y%m%d%H%M%S") )), cause: Set(Some(self.alarm_cause.clone())), - start_date_time: Set(Some(start)), + start_date_time: Set(Some(crate::util::time::db_datetime(start))), notes: Set(msg.topic.clone()), ..Default::default() }; @@ -351,14 +350,17 @@ impl MonitorEventListener { return Ok(()); }; - let end = chrono::Utc::now().naive_utc(); + let end = crate::util::time::utc_now(); let length = event .start_date_time - .map(|start| (end - start).num_milliseconds().max(0) as f64 / 1000.0) + .map(|start| { + let elapsed = end.duration_since(crate::util::time::civil(start)); + elapsed.as_millis().max(0) as f64 / 1000.0 + }) .unwrap_or(0.0); let mut active: events::ActiveModel = event.into(); - active.end_date_time = Set(Some(end)); + active.end_date_time = Set(Some(crate::util::time::db_datetime(end))); active.length = Set(rust_decimal::Decimal::from_f64_retain(length).unwrap_or_default()); events_repo::update(&self.state, active).await?; Ok(()) @@ -409,11 +411,11 @@ impl AlarmTracker { /// Parse an ONVIF UTC time attribute (RFC 3339 / ISO 8601) into a naive UTC /// datetime. Returns `None` for absent or unparseable values. -fn parse_utc(s: Option<&str>) -> Option { +fn parse_utc(s: Option<&str>) -> Option { let s = s?; - chrono::DateTime::parse_from_rfc3339(s) + s.parse::() .ok() - .map(|dt| dt.naive_utc()) + .map(crate::util::time::utc_civil) } #[cfg(test)] @@ -475,8 +477,8 @@ mod tests { #[test] fn parse_utc_handles_rfc3339_and_garbage() { assert_eq!( - parse_utc(Some("2026-06-20T07:50:49Z")).map(|d| d.to_string()), - Some("2026-06-20 07:50:49".to_string()) + parse_utc(Some("2026-06-20T07:50:49Z")), + Some(jiff::civil::date(2026, 6, 20).at(7, 50, 49, 0)) ); assert_eq!(parse_utc(Some("not a time")), None); assert_eq!(parse_utc(None), None); diff --git a/src/daemon/zmdc_client.rs b/src/daemon/zmdc_client.rs index a752a34a..1662ca86 100644 --- a/src/daemon/zmdc_client.rs +++ b/src/daemon/zmdc_client.rs @@ -46,14 +46,14 @@ fn message(command: &str, spec: Option<&str>) -> String { /// The processes listed in a `status` reply. zmdc.pl writes one line per /// running process, `'zmc -m 1' running since 26/10/18 10:00:00, pid = 1234, /// valid`, then one per pending one, `'zmc -m 2' pending at 26/10/18 …`. -pub fn parse_status(reply: &str, now: chrono::NaiveDateTime) -> Vec { +pub fn parse_status(reply: &str, now: jiff::civil::DateTime) -> Vec { reply .lines() .filter_map(|line| parse_line(line, now)) .collect() } -fn parse_line(line: &str, now: chrono::NaiveDateTime) -> Option { +fn parse_line(line: &str, now: jiff::civil::DateTime) -> Option { let rest = line.trim().strip_prefix('\'')?; let (command, rest) = rest.split_once('\'')?; let rest = rest.trim_start(); @@ -63,9 +63,9 @@ fn parse_line(line: &str, now: chrono::NaiveDateTime) -> Option { .split(|c: char| !c.is_ascii_digit()) .next() .and_then(|p| p.parse().ok()); - let uptime = chrono::NaiveDateTime::parse_from_str(since.trim(), "%y/%m/%d %H:%M:%S") + let uptime = jiff::civil::DateTime::strptime("%y/%m/%d %H:%M:%S", since.trim()) .ok() - .and_then(|t| (now - t).num_seconds().try_into().ok()); + .and_then(|t| now.duration_since(t).as_secs().try_into().ok()); (ProcessState::Running, pid, uptime) } else if rest.starts_with("pending at ") { (ProcessState::Restarting, None, None) @@ -105,8 +105,8 @@ fn monitor_id(command: &str) -> Option { mod tests { use super::*; - fn now() -> chrono::NaiveDateTime { - chrono::NaiveDateTime::parse_from_str("26/10/18 10:01:40", "%y/%m/%d %H:%M:%S").unwrap() + fn now() -> jiff::civil::DateTime { + jiff::civil::date(2026, 10, 18).at(10, 1, 40, 0) } #[test] diff --git a/src/dto/request/notifications.rs b/src/dto/request/notifications.rs index af904f09..7f6596f3 100644 --- a/src/dto/request/notifications.rs +++ b/src/dto/request/notifications.rs @@ -1,8 +1,8 @@ //! Requests for ZoneMinder 1.39's Notifications, push token registrations //! (#175). -use chrono::{DateTime, Utc}; use garde::Validate; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -104,7 +104,7 @@ pub struct CreateNotificationRequest { /// RFC 3339. #[schema(value_type = Option, format = DateTime)] #[garde(skip)] - pub last_notified_at: Option>, + pub last_notified_at: Option, /// The owner. Only a System editor may set it; otherwise it is the caller. #[garde(skip)] pub user_id: Option, @@ -138,7 +138,7 @@ pub struct UpdateNotificationRequest { #[serde(default, deserialize_with = "crate::dto::serde_helpers::double_option")] #[schema(value_type = Option, format = DateTime)] #[garde(skip)] - pub last_notified_at: Option>>, + pub last_notified_at: Option>, /// System editors only. #[garde(skip)] pub user_id: Option, diff --git a/src/dto/request/snapshots.rs b/src/dto/request/snapshots.rs index 0731b2a6..c0aff695 100644 --- a/src/dto/request/snapshots.rs +++ b/src/dto/request/snapshots.rs @@ -1,5 +1,5 @@ -use chrono::NaiveDateTime; use garde::Validate; +use jiff::civil::DateTime as Civil; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -13,7 +13,8 @@ pub struct CreateSnapshotRequest { pub created_by: Option, #[schema(value_type = Option, example = "2025-01-15T10:30:00")] #[garde(skip)] - pub created_on: Option, + #[serde(default, with = "crate::util::datetime_format::optional")] + pub created_on: Option, } #[derive(Debug, Clone, Deserialize, Serialize, ToSchema, Validate)] @@ -26,5 +27,6 @@ pub struct UpdateSnapshotRequest { pub created_by: Option, #[schema(value_type = Option, example = "2025-01-15T10:30:00")] #[garde(skip)] - pub created_on: Option, + #[serde(default, with = "crate::util::datetime_format::optional")] + pub created_on: Option, } diff --git a/src/dto/request/tags.rs b/src/dto/request/tags.rs index 51fb3d8a..865ee926 100644 --- a/src/dto/request/tags.rs +++ b/src/dto/request/tags.rs @@ -1,5 +1,5 @@ use garde::Validate; -use sea_orm::prelude::DateTimeUtc; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; @@ -9,7 +9,8 @@ pub struct CreateTagRequest { pub name: String, #[schema(value_type = Option, example = "2025-01-15T10:30:00Z")] #[garde(skip)] - pub create_date: Option, + #[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")] + pub create_date: Option, } #[derive(Debug, Clone, Deserialize, Serialize, ToSchema, Validate)] @@ -18,7 +19,8 @@ pub struct UpdateTagRequest { pub name: Option, #[schema(value_type = Option, example = "2025-01-15T10:30:00Z")] #[garde(skip)] - pub create_date: Option, + #[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")] + pub create_date: Option, } /// Query params for tag detail with paginated events diff --git a/src/dto/response/event_data.rs b/src/dto/response/event_data.rs index 25816164..e22deb20 100644 --- a/src/dto/response/event_data.rs +++ b/src/dto/response/event_data.rs @@ -22,7 +22,7 @@ impl From<&EventDataModel> for EventDataResponse { frame_id: model.frame_id, timestamp: model .timestamp - .map(|dt| crate::util::timestamp_to_utc(dt).to_rfc3339()), + .map(|dt| crate::util::time::rfc3339_offset(crate::util::timestamp_to_utc(dt))), data: model.data.clone(), } } diff --git a/src/dto/response/events.rs b/src/dto/response/events.rs index 7f210180..ab51c710 100644 --- a/src/dto/response/events.rs +++ b/src/dto/response/events.rs @@ -126,7 +126,7 @@ impl From for EventResponse { fn from(model: EventModel) -> Self { // ZoneMinder stores DATETIME in server-local time; convert to true UTC // (GH #16). - let to_utc = crate::util::naive_local_to_utc; + let to_utc = crate::util::datetime_to_utc; Self { id: model.id, diff --git a/src/dto/response/events_tags.rs b/src/dto/response/events_tags.rs index 69d2f5e3..7b82b383 100644 --- a/src/dto/response/events_tags.rs +++ b/src/dto/response/events_tags.rs @@ -1,4 +1,4 @@ -use sea_orm::prelude::DateTimeUtc; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -15,7 +15,8 @@ pub struct EventTagResponse { #[schema(example = 1)] pub event_id: u64, #[schema(value_type = Option, example = "2025-01-15T10:30:00Z")] - pub assigned_date: Option, + #[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")] + pub assigned_date: Option, #[schema(example = 1)] pub assigned_by: Option, } @@ -88,7 +89,7 @@ impl From<&EventModel> for EventSummary { fn from(model: &EventModel) -> Self { // ZoneMinder stores DATETIME in server-local time; convert to true UTC // (GH #16). - let to_utc = crate::util::naive_local_to_utc; + let to_utc = crate::util::datetime_to_utc; Self { id: model.id, @@ -109,7 +110,8 @@ pub struct TagDetailResponse { #[schema(example = "Important")] pub name: String, #[schema(value_type = Option, example = "2025-01-15T10:30:00Z")] - pub create_date: Option, + #[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")] + pub create_date: Option, pub events: Vec, #[schema(example = 100)] pub total_events: u64, diff --git a/src/dto/response/frames.rs b/src/dto/response/frames.rs index 323b7081..5a3df775 100644 --- a/src/dto/response/frames.rs +++ b/src/dto/response/frames.rs @@ -33,7 +33,9 @@ impl From<&FrameModel> for FrameResponse { event_id: model.event_id, frame_id: model.frame_id, r#type: model.r#type.clone(), - time_stamp: crate::util::timestamp_to_utc(model.time_stamp).to_string(), + time_stamp: crate::util::time::utc_display(crate::util::timestamp_to_utc( + model.time_stamp, + )), delta: model.delta, score: model.score, audio_level: model.audio_level, diff --git a/src/dto/response/media_jobs.rs b/src/dto/response/media_jobs.rs index 117914aa..1f7663fb 100644 --- a/src/dto/response/media_jobs.rs +++ b/src/dto/response/media_jobs.rs @@ -27,8 +27,8 @@ pub struct MediaJobResponse { pub finished_at: Option, } -fn utc(t: chrono::NaiveDateTime) -> DateTimeWrapper { - DateTimeWrapper(t.and_utc()) +fn utc(t: sea_orm::prelude::DateTime) -> DateTimeWrapper { + DateTimeWrapper(crate::util::time::utc_instant(t)) } impl From<&Model> for MediaJobResponse { diff --git a/src/dto/response/monitor_pipeline.rs b/src/dto/response/monitor_pipeline.rs index d697a023..f986fe56 100644 --- a/src/dto/response/monitor_pipeline.rs +++ b/src/dto/response/monitor_pipeline.rs @@ -20,6 +20,11 @@ pub struct MonitorPipelineResponse { pub updated_at: String, } +/// The column holds UTC digits; label them as the instant they are. +fn rfc3339(column: sea_orm::prelude::DateTime) -> String { + crate::util::time::rfc3339_offset(crate::util::time::utc_instant(column)) +} + impl From for MonitorPipelineResponse { fn from(m: monitor_pipeline::Model) -> Self { // The stored graph is validated on write, so it parses; fall back to Null @@ -29,8 +34,8 @@ impl From for MonitorPipelineResponse { monitor_id: m.monitor_id, version: m.version, graph, - created_at: m.created_at.and_utc().to_rfc3339(), - updated_at: m.updated_at.and_utc().to_rfc3339(), + created_at: rfc3339(m.created_at), + updated_at: rfc3339(m.updated_at), } } } diff --git a/src/dto/response/monitor_status.rs b/src/dto/response/monitor_status.rs index 4414d11c..13b5a34f 100644 --- a/src/dto/response/monitor_status.rs +++ b/src/dto/response/monitor_status.rs @@ -33,7 +33,9 @@ impl From<&MonitorStatusModel> for MonitorStatusResponse { capture_fps: model.capture_fps.to_string(), analysis_fps: model.analysis_fps.to_string(), capture_bandwidth: model.capture_bandwidth, - updated_on: crate::util::timestamp_to_utc(model.updated_on).to_rfc3339(), + updated_on: crate::util::time::rfc3339_offset(crate::util::timestamp_to_utc( + model.updated_on, + )), alarm_state: None, alarms_disabled: None, analysing: None, @@ -87,9 +89,7 @@ mod tests { /// UTC, not as that wall-clock labelled UTC. #[test] fn updated_on_is_the_local_column_value_in_utc() { - let instant = chrono::DateTime::parse_from_rfc3339("2026-10-23T21:30:15Z") - .unwrap() - .with_timezone(&chrono::Utc); + let instant: jiff::Timestamp = "2026-10-23T21:30:15Z".parse().unwrap(); let model = MonitorStatusModel { monitor_id: 1, status: Status::Connected, @@ -99,7 +99,9 @@ mod tests { updated_on: crate::util::utc_to_timestamp(instant), }; let resp = MonitorStatusResponse::from(&model); - let parsed = chrono::DateTime::parse_from_rfc3339(&resp.updated_on).unwrap(); + let parsed: jiff::Timestamp = resp.updated_on.parse().unwrap(); assert_eq!(parsed, instant); + // The numeric-offset spelling clients already receive. + assert_eq!(resp.updated_on, "2026-10-23T21:30:15+00:00"); } } diff --git a/src/dto/response/notifications.rs b/src/dto/response/notifications.rs index f74af25d..75c04a30 100644 --- a/src/dto/response/notifications.rs +++ b/src/dto/response/notifications.rs @@ -6,7 +6,7 @@ use utoipa::ToSchema; use crate::dto::request::notifications::{PushPlatform, PushState}; use crate::dto::wrappers::DateTimeWrapper; use crate::entity::notifications::Model; -use crate::util::naive_local_to_utc; +use crate::util::datetime_to_utc; #[derive(Debug, Serialize, ToSchema)] pub struct NotificationResponse { @@ -42,8 +42,8 @@ impl From<&Model> for NotificationResponse { badge_count: m.badge_count, last_notified_at: m .last_notified_at - .map(|t| DateTimeWrapper(naive_local_to_utc(t))), - created_on: m.created_on.map(|t| DateTimeWrapper(naive_local_to_utc(t))), + .map(|t| DateTimeWrapper(datetime_to_utc(t))), + created_on: m.created_on.map(|t| DateTimeWrapper(datetime_to_utc(t))), updated_on: DateTimeWrapper(crate::util::timestamp_to_utc(m.updated_on)), } } diff --git a/src/dto/response/reports.rs b/src/dto/response/reports.rs index 36181074..33d59321 100644 --- a/src/dto/response/reports.rs +++ b/src/dto/response/reports.rs @@ -17,14 +17,19 @@ pub struct ReportResponse { pub created_by: Option, } +/// The column's digits labelled UTC, as this endpoint has always reported them. +fn rfc3339(column: sea_orm::prelude::DateTime) -> String { + crate::util::time::rfc3339_offset(crate::util::time::utc_instant(column)) +} + impl From<&ReportModel> for ReportResponse { fn from(model: &ReportModel) -> Self { Self { id: model.id, name: model.name.clone(), filter_id: model.filter_id, - start_date_time: model.start_date_time.map(|dt| dt.and_utc().to_rfc3339()), - end_date_time: model.end_date_time.map(|dt| dt.and_utc().to_rfc3339()), + start_date_time: model.start_date_time.map(rfc3339), + end_date_time: model.end_date_time.map(rfc3339), interval: model.interval, created_by: model.created_by, } diff --git a/src/dto/response/server_stats.rs b/src/dto/response/server_stats.rs index e3bb0d47..c23c312b 100644 --- a/src/dto/response/server_stats.rs +++ b/src/dto/response/server_stats.rs @@ -25,7 +25,9 @@ impl From<&ServerStatModel> for ServerStatResponse { Self { id: model.id, server_id: model.server_id, - time_stamp: crate::util::timestamp_to_utc(model.time_stamp).to_rfc3339(), + time_stamp: crate::util::time::rfc3339_offset(crate::util::timestamp_to_utc( + model.time_stamp, + )), cpu_load: model.cpu_load.map(|d| d.to_string()), cpu_user_percent: model.cpu_user_percent.map(|d| d.to_string()), cpu_nice_percent: model.cpu_nice_percent.map(|d| d.to_string()), diff --git a/src/dto/response/snapshots.rs b/src/dto/response/snapshots.rs index 4032a6b2..721331f0 100644 --- a/src/dto/response/snapshots.rs +++ b/src/dto/response/snapshots.rs @@ -1,6 +1,6 @@ use crate::dto::PaginatedResponse; use crate::entity::snapshots::Model as SnapshotModel; -use chrono::NaiveDateTime; +use jiff::civil::DateTime as Civil; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -11,7 +11,8 @@ pub struct SnapshotResponse { pub description: Option, pub created_by: Option, #[schema(value_type = Option, example = "2025-01-15T10:30:00")] - pub created_on: Option, + #[serde(default, with = "crate::util::datetime_format::optional")] + pub created_on: Option, } impl From<&SnapshotModel> for SnapshotResponse { @@ -21,7 +22,7 @@ impl From<&SnapshotModel> for SnapshotResponse { name: model.name.clone(), description: model.description.clone(), created_by: model.created_by, - created_on: model.created_on, + created_on: model.created_on.map(crate::util::time::civil), } } } @@ -47,3 +48,29 @@ impl From> for PaginatedSnapshotsResponse { } } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The fraction keeps chrono's width, and a body without the field parses. + #[test] + fn created_on_keeps_its_spelling() { + let mut r = SnapshotResponse { + id: 1, + name: None, + description: None, + created_by: None, + created_on: Some("2025-01-15T10:30:00.5".parse().unwrap()), + }; + let json = serde_json::to_value(&r).unwrap(); + assert_eq!(json["created_on"], "2025-01-15T10:30:00.500"); + r.created_on = Some("2025-01-15T10:30:00".parse().unwrap()); + let json = serde_json::to_value(&r).unwrap(); + assert_eq!(json["created_on"], "2025-01-15T10:30:00"); + let back: SnapshotResponse = serde_json::from_value(json).unwrap(); + assert_eq!(back.created_on, r.created_on); + let bare: SnapshotResponse = serde_json::from_str(r#"{"id":1}"#).unwrap(); + assert_eq!(bare.created_on, None); + } +} diff --git a/src/dto/response/tags.rs b/src/dto/response/tags.rs index 99beb299..54d950e9 100644 --- a/src/dto/response/tags.rs +++ b/src/dto/response/tags.rs @@ -1,4 +1,4 @@ -use sea_orm::prelude::DateTimeUtc; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -10,7 +10,8 @@ pub struct TagResponse { pub id: u64, pub name: String, #[schema(value_type = Option, example = "2025-01-15T10:30:00Z")] - pub create_date: Option, + #[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")] + pub create_date: Option, /// Number of events with this tag #[serde(skip_serializing_if = "Option::is_none")] pub event_count: Option, @@ -60,3 +61,24 @@ impl From> for PaginatedTagsResponse { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn create_date_keeps_its_spelling() { + let mut r = TagResponse { + id: 1, + name: "t".into(), + create_date: Some("2025-01-15T10:30:00.5Z".parse().unwrap()), + event_count: None, + }; + let json = serde_json::to_value(&r).unwrap(); + assert_eq!(json["create_date"], "2025-01-15T10:30:00.500Z"); + let back: TagResponse = serde_json::from_value(json).unwrap(); + assert_eq!(back.create_date, r.create_date); + r.create_date = None; + assert!(serde_json::to_value(&r).unwrap()["create_date"].is_null()); + } +} diff --git a/src/dto/wrappers.rs b/src/dto/wrappers.rs index 04ac96f4..90d51012 100644 --- a/src/dto/wrappers.rs +++ b/src/dto/wrappers.rs @@ -1,13 +1,28 @@ use crate::entity::sea_orm_active_enums::Scheme; -use chrono::{DateTime, NaiveDateTime, Utc}; use fake::Dummy; +use jiff::civil::DateTime as Civil; +use jiff::Timestamp; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; -#[derive(Debug, Serialize, Deserialize, ToSchema, Dummy, Clone)] +#[derive(Debug, Deserialize, ToSchema, Clone)] #[schema(value_type = String, format = "date-time", example = "2025-04-24T12:34:56Z")] -pub struct DateTimeWrapper(pub DateTime); +pub struct DateTimeWrapper(pub Timestamp); + +impl Serialize for DateTimeWrapper { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&crate::util::time::rfc3339_z(self.0)) + } +} + +impl Dummy for DateTimeWrapper { + fn dummy_with_rng(_: &fake::Faker, rng: &mut R) -> Self { + // Any second from 1970 to 2100. + let secs = rng.random_range(0..4_102_444_800_i64); + DateTimeWrapper(Timestamp::from_second(secs).unwrap_or(Timestamp::UNIX_EPOCH)) + } +} /// A ZoneMinder `DATETIME` — wall-clock local time on the recording host, with /// no timezone offset. The value is exactly the digits the column holds. @@ -17,38 +32,42 @@ pub struct DateTimeWrapper(pub DateTime); /// offset-aware parser that then rejects every value this API actually sends. /// A plain string is the honest description; interpret it in the server's /// timezone, which `GET /api/v3/system/locale` reports. -#[derive(Debug, Serialize, Deserialize, ToSchema, Clone)] +#[derive(Debug, Deserialize, ToSchema, Clone)] #[schema( value_type = String, example = "2025-04-24T12:34:56", description = "Local wall-clock time with no offset, as stored by ZoneMinder" )] -pub struct NaiveDateTimeWrapper(pub NaiveDateTime); +pub struct NaiveDateTimeWrapper(pub Civil); + +impl Serialize for NaiveDateTimeWrapper { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&crate::util::time::civil_string(self.0)) + } +} // Add conversion implementations for NaiveDateTimeWrapper -impl From for NaiveDateTime { +impl From for Civil { fn from(wrapper: NaiveDateTimeWrapper) -> Self { wrapper.0 } } -impl From for NaiveDateTimeWrapper { - fn from(dt: NaiveDateTime) -> Self { +impl From for NaiveDateTimeWrapper { + fn from(dt: Civil) -> Self { NaiveDateTimeWrapper(dt) } } // Add reference conversion implementations -impl<'a> From<&'a NaiveDateTimeWrapper> for &'a NaiveDateTime { +impl<'a> From<&'a NaiveDateTimeWrapper> for &'a Civil { fn from(wrapper: &'a NaiveDateTimeWrapper) -> Self { &wrapper.0 } } // Helper function to convert Option to Option -pub fn unwrap_naive_datetime_wrapper( - opt_wrapper: &Option, -) -> Option { +pub fn unwrap_naive_datetime_wrapper(opt_wrapper: &Option) -> Option { opt_wrapper.as_ref().map(|wrapper| wrapper.0) } @@ -72,8 +91,8 @@ impl From for SchemeWrapper { } } -impl From> for DateTimeWrapper { - fn from(dt: DateTime) -> Self { +impl From for DateTimeWrapper { + fn from(dt: Timestamp) -> Self { DateTimeWrapper(dt) } } @@ -83,7 +102,6 @@ pub mod naive_datetime_option { use super::NaiveDateTimeWrapper; use crate::util::datetime_format::optional as base; use serde::{self, Deserializer, Serializer}; - // use chrono::NaiveDateTime; // Unused import pub fn serialize( val: &Option, @@ -92,7 +110,7 @@ pub mod naive_datetime_option { where S: Serializer, { - // Explicitly handle Option and serialize the inner NaiveDateTime + // Explicitly handle Option and serialize the inner datetime match val { Some(wrapper) => base::serialize(&Some(wrapper.0), serializer), None => base::serialize::(&None, serializer), // Specify type for None case diff --git a/src/handlers/event_export.rs b/src/handlers/event_export.rs index d8583d7b..3aa3ba08 100644 --- a/src/handlers/event_export.rs +++ b/src/handlers/event_export.rs @@ -66,7 +66,7 @@ pub async fn export_events( let name = format!( "attachment; filename=\"zm-events-{}.zip\"", - chrono::Local::now().format("%Y%m%d-%H%M%S") + crate::util::time::local_now().strftime("%Y%m%d-%H%M%S") ); let mut res = Body::from_stream(tokio_util::io::ReaderStream::new(reader)).into_response(); let h = res.headers_mut(); diff --git a/src/handlers/event_stream.rs b/src/handlers/event_stream.rs index 61cd1c4a..98a562b7 100644 --- a/src/handlers/event_stream.rs +++ b/src/handlers/event_stream.rs @@ -139,7 +139,7 @@ pub async fn stream_events( let mut sub = Subscriber { expires: tokio::time::Instant::now() - + Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(0) as u64), + + Duration::from_secs((claims.exp - crate::util::time::unix_now()).max(0) as u64), state: state.clone(), claims, scope, diff --git a/src/handlers/events.rs b/src/handlers/events.rs index d6deb8e6..1ff5da50 100644 --- a/src/handlers/events.rs +++ b/src/handlers/events.rs @@ -3,7 +3,6 @@ use axum::{ http::StatusCode, Json, }; -// use chrono::Utc; // not needed in this module use garde::Validate; use tracing::{debug, instrument}; diff --git a/src/handlers/live.rs b/src/handlers/live.rs index f06acea9..eb177695 100644 --- a/src/handlers/live.rs +++ b/src/handlers/live.rs @@ -711,7 +711,7 @@ pub async fn webrtc_websocket_handler( }, (None, Some(g)) => Viewer { uid: g.uid, - since: chrono::Utc::now().timestamp(), + since: crate::util::time::unix_now(), }, (None, None) => { return Err(AppError::UnauthorizedError( @@ -1542,7 +1542,7 @@ pub async fn stream_monitor_events( }, (None, Some(g)) => Viewer { uid: g.uid, - since: chrono::Utc::now().timestamp(), + since: crate::util::time::unix_now(), }, (None, None) => { return Err(AppError::UnauthorizedError( @@ -1688,7 +1688,7 @@ mod tests { let db = sea_orm::MockDatabase::new(sea_orm::DatabaseBackend::MySql).into_connection(); let state = AppState::for_test_with_db(db); let (tx, rx) = tokio::sync::broadcast::channel(4); - let since = chrono::Utc::now().timestamp(); + let since = crate::util::time::unix_now(); state.revocations.revoke(9, since + 1); let stream = status_changes( diff --git a/src/handlers/media_links.rs b/src/handlers/media_links.rs index aad9bcea..bfb16758 100644 --- a/src/handlers/media_links.rs +++ b/src/handlers/media_links.rs @@ -35,7 +35,7 @@ fn link( .ttl_seconds .map(Duration::from_secs) .unwrap_or(LINK_DEFAULT_TTL); - let expires_at = chrono::Utc::now().timestamp() + ttl.as_secs() as i64; + let expires_at = crate::util::time::unix_now() + ttl.as_secs() as i64; let token = media_url::sign_until(resource, uid, expires_at); Ok(MediaLinkResponse { playlist_url: format!( diff --git a/src/handlers/synopsis.rs b/src/handlers/synopsis.rs index 53772d86..377574da 100644 --- a/src/handlers/synopsis.rs +++ b/src/handlers/synopsis.rs @@ -408,12 +408,12 @@ pub async fn get_range_synopsis( "`to` must be >= `from`".to_string(), )); } - let from = chrono::DateTime::from_timestamp(query.from, 0) - .ok_or_else(|| AppError::BadRequestError("invalid `from` timestamp".to_string()))? - .naive_utc(); - let to = chrono::DateTime::from_timestamp(query.to, 0) - .ok_or_else(|| AppError::BadRequestError("invalid `to` timestamp".to_string()))? - .naive_utc(); + let from = jiff::Timestamp::from_second(query.from) + .map(crate::util::time::utc_civil) + .map_err(|_| AppError::BadRequestError("invalid `from` timestamp".to_string()))?; + let to = jiff::Timestamp::from_second(query.to) + .map(crate::util::time::utc_civil) + .map_err(|_| AppError::BadRequestError("invalid `to` timestamp".to_string()))?; let classes = parse_classes(&query.class); let jpeg = match svc diff --git a/src/migration/stamp.rs b/src/migration/stamp.rs index ab9b1b3b..58e8fcbe 100644 --- a/src/migration/stamp.rs +++ b/src/migration/stamp.rs @@ -123,7 +123,7 @@ async fn config_value(conn: &DatabaseConnection, name: &str) -> Result Result<(), DbErr> { Migrator::install(conn).await?; - let now = chrono::Utc::now().timestamp(); + let now = crate::util::time::unix_now(); for name in names { if migration_recorded(conn, name).await? { continue; diff --git a/src/onvif/security.rs b/src/onvif/security.rs index 82ec081f..6c442fe5 100644 --- a/src/onvif/security.rs +++ b/src/onvif/security.rs @@ -41,7 +41,9 @@ pub fn password_digest(nonce: &[u8], created: &str, password: &str) -> String { pub fn generate_nonce_created() -> (Vec, String) { let mut nonce = [0u8; 16]; rand::rng().fill_bytes(&mut nonce); - let created = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + let created = jiff::Timestamp::now() + .strftime("%Y-%m-%dT%H:%M:%SZ") + .to_string(); (nonce.to_vec(), created) } @@ -151,7 +153,7 @@ mod tests { assert_eq!(nonce.len(), 16); assert!(created.ends_with('Z')); // Round-trips as an RFC3339/ISO-8601 instant. - assert!(chrono::DateTime::parse_from_rfc3339(&created).is_ok()); + assert!(created.parse::().is_ok()); } #[test] diff --git a/src/repo/event_data.rs b/src/repo/event_data.rs index ef6743cb..cbdf9b88 100644 --- a/src/repo/event_data.rs +++ b/src/repo/event_data.rs @@ -4,7 +4,7 @@ use crate::entity::event_data::{ ActiveModel, Column, Entity as EventData, Model as EventDataModel, }; use crate::error::{AppError, AppResult}; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use sea_orm::*; pub async fn find_all( @@ -59,8 +59,8 @@ pub async fn create( .timestamp .as_ref() .map(|s| { - DateTime::parse_from_rfc3339(s) - .map(|dt| crate::util::utc_to_timestamp(dt.with_timezone(&Utc))) + s.parse::() + .map(crate::util::utc_to_timestamp) .map_err(|e| AppError::BadRequestError(format!("Invalid timestamp format: {}", e))) }) .transpose()?; diff --git a/src/repo/event_synopsis.rs b/src/repo/event_synopsis.rs index 93fa0493..84daaf36 100644 --- a/src/repo/event_synopsis.rs +++ b/src/repo/event_synopsis.rs @@ -1,5 +1,6 @@ //! DB query layer for the zm-api-owned `event_synopsis` table. +use crate::util::time::db_datetime; use sea_orm::*; use crate::entity::event_synopsis; @@ -71,14 +72,14 @@ pub async fn update_status( pub async fn find_by_monitor_created_between( db: &DatabaseConnection, monitor_id: u32, - from: chrono::NaiveDateTime, - to: chrono::NaiveDateTime, + from: jiff::civil::DateTime, + to: jiff::civil::DateTime, limit: u64, ) -> Result, DbErr> { EventSynopsis::find() .filter(event_synopsis::Column::MonitorId.eq(monitor_id)) - .filter(event_synopsis::Column::CreatedAt.gte(from)) - .filter(event_synopsis::Column::CreatedAt.lte(to)) + .filter(event_synopsis::Column::CreatedAt.gte(db_datetime(from))) + .filter(event_synopsis::Column::CreatedAt.lte(db_datetime(to))) .order_by_desc(event_synopsis::Column::CreatedAt) .limit(limit) .all(db) @@ -90,13 +91,13 @@ pub async fn find_by_monitor_created_between( pub async fn count_by_monitor_created_between( db: &DatabaseConnection, monitor_id: u32, - from: chrono::NaiveDateTime, - to: chrono::NaiveDateTime, + from: jiff::civil::DateTime, + to: jiff::civil::DateTime, ) -> Result { EventSynopsis::find() .filter(event_synopsis::Column::MonitorId.eq(monitor_id)) - .filter(event_synopsis::Column::CreatedAt.gte(from)) - .filter(event_synopsis::Column::CreatedAt.lte(to)) + .filter(event_synopsis::Column::CreatedAt.gte(db_datetime(from))) + .filter(event_synopsis::Column::CreatedAt.lte(db_datetime(to))) .count(db) .await } @@ -104,11 +105,11 @@ pub async fn count_by_monitor_created_between( /// All rows whose `expires_at` is in the past relative to `now` (retention job). pub async fn find_expired( db: &DatabaseConnection, - now: chrono::NaiveDateTime, + now: jiff::civil::DateTime, ) -> Result, DbErr> { EventSynopsis::find() .filter(event_synopsis::Column::ExpiresAt.is_not_null()) - .filter(event_synopsis::Column::ExpiresAt.lt(now)) + .filter(event_synopsis::Column::ExpiresAt.lt(db_datetime(now))) .all(db) .await } diff --git a/src/repo/events.rs b/src/repo/events.rs index 8dac5fc4..dde75e33 100644 --- a/src/repo/events.rs +++ b/src/repo/events.rs @@ -368,9 +368,7 @@ pub async fn get_counts_by_monitor( use sea_orm::Statement; // Calculate time boundary - let now = chrono::Utc::now(); - let time_boundary = now - chrono::Duration::hours(hours_back); - let time_boundary_str = time_boundary.format("%Y-%m-%d %H:%M:%S").to_string(); + let time_boundary_str = hours_ago(hours_back); let mut select = Query::select(); select @@ -409,7 +407,7 @@ pub async fn get_counts_by_hour( state: &AppState, hours_back: i64, monitor_filter: Option<&[u32]>, -) -> Result, DbErr> { +) -> Result, DbErr> { use sea_orm::sea_query::{Expr, Query}; use sea_orm::{FromQueryResult, Statement}; @@ -420,9 +418,7 @@ pub async fn get_counts_by_hour( } // Calculate time boundary - let now = chrono::Utc::now(); - let time_boundary = now - chrono::Duration::hours(hours_back); - let time_boundary_str = time_boundary.format("%Y-%m-%d %H:%M:%S").to_string(); + let time_boundary_str = hours_ago(hours_back); // Raw SQL for better performance on complex aggregation with grouping by hour let hour_alias = Alias::new("hour"); @@ -451,12 +447,8 @@ pub async fn get_counts_by_hour( let counts = results .into_iter() .map(|r| { - let naive_date = chrono::NaiveDateTime::parse_from_str(&r.hour, "%Y-%m-%d %H:%M:%S") - .unwrap_or_else(|_| { - chrono::DateTime::::from_timestamp(0, 0) - .unwrap() - .naive_utc() - }); + let naive_date = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M:%S", &r.hour) + .unwrap_or_else(|_| jiff::civil::date(1970, 1, 1).at(0, 0, 0, 0)); (naive_date, r.count as u64) }) .collect(); @@ -525,6 +517,17 @@ pub async fn find_by_id_with_tags( } } +/// The UTC wall-clock `hours_back` hours ago, as `YYYY-MM-DD HH:MM:SS`. +fn hours_ago(hours_back: i64) -> String { + let span = jiff::SignedDuration::from_secs(hours_back.saturating_mul(3600)); + let boundary = jiff::Timestamp::now() + .saturating_sub(span) + .unwrap_or(jiff::Timestamp::UNIX_EPOCH); + crate::util::time::utc_civil(boundary) + .strftime("%Y-%m-%d %H:%M:%S") + .to_string() +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/repo/events_tags.rs b/src/repo/events_tags.rs index 4d64221c..05f6daca 100644 --- a/src/repo/events_tags.rs +++ b/src/repo/events_tags.rs @@ -1,4 +1,4 @@ -use chrono::Utc; +use jiff::Timestamp; use sea_orm::*; use crate::dto::request::events_tags::CreateEventTagRequest; @@ -67,7 +67,7 @@ pub async fn create( let am = ActiveModel { tag_id: Set(req.tag_id), event_id: Set(req.event_id), - assigned_date: Set(Some(crate::util::utc_to_timestamp(Utc::now()))), + assigned_date: Set(Some(crate::util::utc_to_timestamp(Timestamp::now()))), assigned_by: Set(req.assigned_by), }; Ok(am.insert(db).await?) diff --git a/src/repo/frames.rs b/src/repo/frames.rs index fc2d3c6d..78b08418 100644 --- a/src/repo/frames.rs +++ b/src/repo/frames.rs @@ -2,7 +2,7 @@ use crate::dto::request::frames::{CreateFrameRequest, UpdateFrameRequest}; use crate::dto::PaginationParams; use crate::entity::frames::{ActiveModel, Column, Entity as FrameEntity, Model as FrameModel}; use crate::error::AppResult; -use chrono::DateTime; +use jiff::Timestamp; use sea_orm::{ ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder, Set, @@ -102,15 +102,15 @@ pub async fn find_at_or_before( /// Create a new frame pub async fn create(db: &DatabaseConnection, req: &CreateFrameRequest) -> AppResult { // Parse timestamp - let time_stamp = DateTime::parse_from_rfc3339(&req.time_stamp) - .map_err(|e| crate::error::AppError::BadRequestError(format!("Invalid timestamp: {}", e)))? - .naive_utc(); + let time_stamp = req.time_stamp.parse::().map_err(|e| { + crate::error::AppError::BadRequestError(format!("Invalid timestamp: {}", e)) + })?; let frame = ActiveModel { event_id: Set(req.event_id), frame_id: Set(req.frame_id), r#type: Set(req.r#type.clone()), - time_stamp: Set(crate::util::utc_to_timestamp(time_stamp.and_utc())), + time_stamp: Set(crate::util::utc_to_timestamp(time_stamp)), delta: Set(req.delta), score: Set(req.score), ..Default::default() diff --git a/src/repo/monitor_pipeline.rs b/src/repo/monitor_pipeline.rs index 58598259..4bba1b45 100644 --- a/src/repo/monitor_pipeline.rs +++ b/src/repo/monitor_pipeline.rs @@ -23,8 +23,9 @@ pub async fn upsert( monitor_id: u32, graph_json: String, version: u32, - now: chrono::NaiveDateTime, + now: jiff::civil::DateTime, ) -> Result { + let now = crate::util::time::db_datetime(now); match MonitorPipeline::find_by_id(monitor_id).one(db).await? { Some(existing) => { let mut active: monitor_pipeline::ActiveModel = existing.into(); diff --git a/src/repo/reports.rs b/src/repo/reports.rs index 2bbc1234..5a920546 100644 --- a/src/repo/reports.rs +++ b/src/repo/reports.rs @@ -2,7 +2,7 @@ use crate::dto::request::reports::{CreateReportRequest, UpdateReportRequest}; use crate::dto::PaginationParams; use crate::entity::reports::{ActiveModel, Entity as Reports, Model as ReportModel}; use crate::error::{AppError, AppResult}; -use chrono::NaiveDateTime; +use jiff::civil::DateTime as Civil; use sea_orm::*; pub async fn find_all(db: &DatabaseConnection) -> AppResult> { @@ -33,20 +33,14 @@ pub async fn create( let start_date_time = req .start_date_time .as_ref() - .map(|s| { - NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%SZ") - .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")) - }) + .map(|s| parse_report_time(s)) .transpose() .map_err(|e| AppError::BadRequestError(format!("Invalid start_date_time format: {}", e)))?; let end_date_time = req .end_date_time .as_ref() - .map(|s| { - NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%SZ") - .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")) - }) + .map(|s| parse_report_time(s)) .transpose() .map_err(|e| AppError::BadRequestError(format!("Invalid end_date_time format: {}", e)))?; @@ -85,20 +79,16 @@ pub async fn update( } if let Some(s) = &req.start_date_time { - let dt = NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%SZ") - .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")) - .map_err(|e| { - AppError::BadRequestError(format!("Invalid start_date_time format: {}", e)) - })?; + let dt = parse_report_time(s).map_err(|e| { + AppError::BadRequestError(format!("Invalid start_date_time format: {}", e)) + })?; am.start_date_time = Set(Some(dt)); } if let Some(s) = &req.end_date_time { - let dt = NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%SZ") - .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")) - .map_err(|e| { - AppError::BadRequestError(format!("Invalid end_date_time format: {}", e)) - })?; + let dt = parse_report_time(s).map_err(|e| { + AppError::BadRequestError(format!("Invalid end_date_time format: {}", e)) + })?; am.end_date_time = Set(Some(dt)); } @@ -110,3 +100,11 @@ pub async fn delete_by_id(db: &DatabaseConnection, id: u32) -> AppResult { let res = Reports::delete_by_id(id).exec(db).await?; Ok(res.rows_affected > 0) } + +/// A report bound as the client sends it: `2026-01-02T03:04:05Z` or +/// `2026-01-02 03:04:05`. Either way the digits go to the column unchanged. +fn parse_report_time(s: &str) -> Result { + Civil::strptime("%Y-%m-%dT%H:%M:%SZ", s) + .or_else(|_| Civil::strptime("%Y-%m-%d %H:%M:%S", s)) + .map(crate::util::time::db_datetime) +} diff --git a/src/repo/server_stats.rs b/src/repo/server_stats.rs index 6ed7d3e5..97095858 100644 --- a/src/repo/server_stats.rs +++ b/src/repo/server_stats.rs @@ -2,7 +2,7 @@ use crate::dto::request::server_stats::CreateServerStatRequest; use crate::dto::PaginationParams; use crate::entity::server_stats::{ActiveModel, Entity as ServerStats, Model as ServerStatModel}; use crate::error::{AppError, AppResult}; -use chrono::Utc; +use jiff::Timestamp; use rust_decimal::Decimal; use sea_orm::*; use std::str::FromStr; @@ -76,7 +76,7 @@ pub async fn create( let am = ActiveModel { id: Default::default(), server_id: Set(req.server_id), - time_stamp: Set(crate::util::utc_to_timestamp(Utc::now())), + time_stamp: Set(crate::util::utc_to_timestamp(Timestamp::now())), cpu_load: Set(cpu_load), cpu_user_percent: Set(cpu_user_percent), cpu_nice_percent: Set(cpu_nice_percent), diff --git a/src/repo/snapshots.rs b/src/repo/snapshots.rs index 12a977b3..a0d24295 100644 --- a/src/repo/snapshots.rs +++ b/src/repo/snapshots.rs @@ -33,7 +33,7 @@ pub async fn create( name: Set(req.name.clone()), description: Set(req.description.clone()), created_by: Set(req.created_by), - created_on: Set(req.created_on), + created_on: Set(req.created_on.map(crate::util::time::db_datetime)), }; Ok(am.insert(db).await?) } @@ -58,7 +58,7 @@ pub async fn update( am.created_by = Set(Some(v)); } if let Some(v) = req.created_on { - am.created_on = Set(Some(v)); + am.created_on = Set(Some(crate::util::time::db_datetime(v))); } let updated = am.update(db).await?; diff --git a/src/repo/zmnext_secret.rs b/src/repo/zmnext_secret.rs index 3a654427..9c45b343 100644 --- a/src/repo/zmnext_secret.rs +++ b/src/repo/zmnext_secret.rs @@ -21,8 +21,9 @@ pub async fn upsert( monitor_id: u32, name: &str, ciphertext: String, - now: chrono::NaiveDateTime, + now: jiff::civil::DateTime, ) -> Result<(), DbErr> { + let now = crate::util::time::db_datetime(now); let existing = zmnext_secret::Entity::find_by_id((monitor_id, name.to_string())) .one(db) .await?; diff --git a/src/service/auth.rs b/src/service/auth.rs index 7a34cc55..c1b0bc88 100644 --- a/src/service/auth.rs +++ b/src/service/auth.rs @@ -40,7 +40,7 @@ pub async fn login(state: &AppState, req: LoginRequest) -> AppResult AppRes pub async fn logout(state: &AppState, uid: u32) -> AppResult<()> { // Floor at now+1 so tokens minted earlier in the *current* second (e.g. // the one authenticating this very logout) are revoked too. - let floor = chrono::Utc::now().timestamp() + 1; + let floor = crate::util::time::unix_now() + 1; user::set_token_min_expiry(&state.db, uid, floor as u64).await?; state.revocations.revoke(uid, floor); info!("Revoked all tokens for user id {uid} issued before {floor}"); @@ -186,7 +186,7 @@ mod tests { let state = AppState::for_test_with_db(db); // As logout and a role change do: the floor is the next second. The // password check may run into that second; the token works either way. - let before = chrono::Utc::now().timestamp(); + let before = crate::util::time::unix_now(); state.revocations.revoke(1, before + 1); let resp = login( @@ -385,7 +385,7 @@ mod tests { #[tokio::test] async fn test_refresh_rejected_when_issued_before_token_min_expiry() { let mut user_row = mk_user("dave", "irrelevant-hash"); - user_row.token_min_expiry = (chrono::Utc::now().timestamp() + 10_000) as u64; + user_row.token_min_expiry = (crate::util::time::unix_now() + 10_000) as u64; let db = MockDatabase::new(DatabaseBackend::MySql) .append_query_results::(vec![vec![user_row]]) .into_connection(); @@ -452,7 +452,7 @@ mod tests { token::generate_tokens("dave".to_string(), 1, UserPermissions::default()).unwrap(); state .revocations - .revoke(1, chrono::Utc::now().timestamp() + 10_000); + .revoke(1, crate::util::time::unix_now() + 10_000); let err = refresh_token( &state, RefreshTokenRequest { diff --git a/src/service/daemon.rs b/src/service/daemon.rs index 833a3a7a..fe4e6c05 100644 --- a/src/service/daemon.rs +++ b/src/service/daemon.rs @@ -30,7 +30,7 @@ async fn zmdc_status(state: &AppState) -> AppResult, - last_end: Option, - prev_end: Option, + first_start: Option, + last_end: Option, + prev_end: Option, min_gap: Option, max_gap: Option, missing: Vec, @@ -58,13 +59,13 @@ struct Acc { } impl Acc { - fn push(&mut self, id: u64, start: Option, end: Option) { + fn push(&mut self, id: u64, start: Option, end: Option) { if self.count == 0 { self.first_id = id; self.first_start = start; } if let (Some(prev), Some(start)) = (self.prev_end, start) { - let gap = (start - prev).num_seconds(); + let gap = start.duration_since(prev).as_secs(); self.min_gap = Some(self.min_gap.map_or(gap, |g| g.min(gap))); self.max_gap = Some(self.max_gap.map_or(gap, |g| g.max(gap))); } @@ -76,14 +77,16 @@ impl Acc { } /// A local-time column value, as UTC, the way every event response reports it. -fn rfc3339(t: NaiveDateTime) -> String { - crate::util::naive_local_to_utc(t).to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +fn rfc3339(t: Civil) -> String { + crate::util::naive_local_to_utc(t) + .strftime("%Y-%m-%dT%H:%M:%SZ") + .to_string() } pub async fn event_audit( state: &AppState, - start: NaiveDateTime, - end: NaiveDateTime, + start: Civil, + end: Civil, monitor_id: Option, scope: &MonitorScope, ) -> AppResult { @@ -92,8 +95,8 @@ pub async fn event_audit( } // Events overlapping the window, as legacy selects them. let mut query = events::Entity::find() - .filter(events::Column::EndDateTime.gt(start)) - .filter(events::Column::StartDateTime.lt(end)); + .filter(events::Column::EndDateTime.gt(time::db_datetime(start))) + .filter(events::Column::StartDateTime.lt(time::db_datetime(end))); match monitor_id { Some(id) if scope.allows(id, Level::View) => { query = query.filter(events::Column::MonitorId.eq(id)); @@ -121,7 +124,11 @@ pub async fn event_audit( let mut by_monitor: BTreeMap = BTreeMap::new(); for e in &rows { let acc = by_monitor.entry(e.monitor_id).or_default(); - acc.push(e.id, e.start_date_time, e.end_date_time); + acc.push( + e.id, + e.start_date_time.map(time::civil), + e.end_date_time.map(time::civil), + ); let root = match roots.get(&e.storage_id) { Some(root) => root.clone(), @@ -173,12 +180,12 @@ pub async fn event_audit( } /// The default window, as legacy's: the hour ending an hour ago. -pub fn default_window() -> (NaiveDateTime, NaiveDateTime) { +pub fn default_window() -> (Civil, Civil) { // In the server-local time the event columns hold (#173). - let now = crate::util::utc_to_naive_local(Utc::now()); + let now = time::local_now(); ( - now - chrono::Duration::hours(2), - now - chrono::Duration::hours(1), + now.saturating_sub(jiff::SignedDuration::from_hours(2)), + now.saturating_sub(jiff::SignedDuration::from_hours(1)), ) } @@ -186,8 +193,8 @@ pub fn default_window() -> (NaiveDateTime, NaiveDateTime) { mod tests { use super::*; - fn t(s: &str) -> Option { - Some(NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").unwrap()) + fn t(s: &str) -> Option { + Some(Civil::strptime("%Y-%m-%d %H:%M:%S", s).unwrap()) } #[test] diff --git a/src/service/event_export.rs b/src/service/event_export.rs index c330df8c..7da245a5 100644 --- a/src/service/event_export.rs +++ b/src/service/event_export.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; use async_zip::tokio::write::ZipFileWriter; -use async_zip::{Compression, ZipDateTime, ZipEntryBuilder}; +use async_zip::{Compression, ZipDateTime, ZipDateTimeBuilder, ZipEntryBuilder}; use futures::io::AsyncWriteExt; use tokio::io::{AsyncWrite, DuplexStream}; use tokio_util::compat::TokioAsyncReadCompatExt; @@ -101,7 +101,7 @@ async fn write_zip( out: W, ) -> Result<(), Box> { let mut zip = ZipFileWriter::with_tokio(out); - let now = ZipDateTime::from_chrono(&chrono::Utc::now()); + let now = zip_time(jiff::Timestamp::now()); for ex in exports { let folder = ex.event.id.to_string(); if parts.contains(&ExportPart::Details) { @@ -154,8 +154,9 @@ async fn write_zip( let modified = tokio::fs::metadata(&path) .await? .modified() - .map(chrono::DateTime::::from) - .map(|t| ZipDateTime::from_chrono(&t)) + .ok() + .and_then(|t| jiff::Timestamp::try_from(t).ok()) + .map(zip_time) .unwrap_or(now); let entry = ZipEntryBuilder::new(format!("{folder}/{name}").into(), Compression::Stored) @@ -171,10 +172,39 @@ async fn write_zip( Ok(()) } +/// An instant as a ZIP entry date: its UTC wall-clock, to the 2 s the format keeps. +fn zip_time(t: jiff::Timestamp) -> ZipDateTime { + let utc = crate::util::time::utc_civil(t); + ZipDateTimeBuilder::new() + .year(i32::from(utc.year())) + .month(utc.month() as u32) + .day(utc.day() as u32) + .hour(utc.hour() as u32) + .minute(utc.minute() as u32) + .second(utc.second() as u32) + .build() +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_zip_date_carries_the_utc_wall_clock() { + let z = zip_time("2026-10-23T21:30:14Z".parse().unwrap()); + assert_eq!( + ( + z.year(), + z.month(), + z.day(), + z.hour(), + z.minute(), + z.second() + ), + (2026, 10, 23, 21, 30, 14) + ); + } + #[test] fn files_are_sorted_into_parts_by_extension() { assert_eq!(classify("00001-capture.jpg"), ExportPart::Images); diff --git a/src/service/event_storage.rs b/src/service/event_storage.rs index 8f2cb035..0b61049c 100644 --- a/src/service/event_storage.rs +++ b/src/service/event_storage.rs @@ -11,7 +11,6 @@ use std::io::ErrorKind; use std::path::{Path, PathBuf}; -use chrono::{Datelike, Timelike}; use tracing::{debug, info, warn}; use crate::entity::events::Model as EventModel; @@ -111,9 +110,10 @@ pub(crate) fn build_event_directory_path( storage_path: &str, monitor_id: u32, event_id: u64, - start_time: Option, + start_time: Option, scheme: &Scheme, ) -> PathBuf { + let start_time = start_time.map(crate::util::time::civil); let base = PathBuf::from(storage_path).join(monitor_id.to_string()); match scheme { @@ -287,11 +287,12 @@ pub(crate) async fn remove_event_dir(storage_path: &str, event: &EventModel) -> mod tests { use super::*; - fn sample_dt() -> chrono::NaiveDateTime { - chrono::NaiveDate::from_ymd_opt(2024, 3, 9) - .unwrap() - .and_hms_opt(14, 5, 6) - .unwrap() + fn column(s: &str) -> sea_orm::prelude::DateTime { + crate::util::time::db_datetime(s.parse().unwrap()) + } + + fn sample_dt() -> sea_orm::prelude::DateTime { + column("2024-03-09T14:05:06") } #[test] @@ -315,10 +316,7 @@ mod tests { #[test] fn deep_zero_pads_and_wraps_year_to_two_digits() { // Year 2008 -> "08"; single-digit month/day/time zero-padded. - let dt = chrono::NaiveDate::from_ymd_opt(2008, 1, 2) - .unwrap() - .and_hms_opt(0, 0, 0) - .unwrap(); + let dt = column("2008-01-02T00:00:00"); let p = build_event_directory_path("/srv", 1, 5, Some(dt), &Scheme::Deep); assert_eq!(p, PathBuf::from("/srv/1/08/01/02/00/00/00")); } @@ -385,8 +383,7 @@ mod tests { fn deep_event(id: u64, monitor_id: u32, start: &str) -> EventModel { let mut e = mk_event(id, monitor_id, Some(1), Scheme::Deep); - e.start_date_time = - Some(chrono::NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S").unwrap()); + e.start_date_time = Some(column(start)); e } diff --git a/src/service/event_stream.rs b/src/service/event_stream.rs index 89c33d92..be914457 100644 --- a/src/service/event_stream.rs +++ b/src/service/event_stream.rs @@ -64,7 +64,7 @@ pub struct EventInfo { impl From<&events::Model> for EventInfo { fn from(m: &events::Model) -> Self { - use crate::util::naive_local_to_utc as utc; + use crate::util::datetime_to_utc as utc; Self { event_id: m.id, monitor_id: m.monitor_id, @@ -500,10 +500,7 @@ mod tests { fn event(id: u64, monitor_id: u32, ended: bool, notes: Option<&str>) -> events::Model { use crate::entity::sea_orm_active_enums::{Orientation, Scheme}; - let t = chrono::NaiveDate::from_ymd_opt(2026, 10, 24) - .unwrap() - .and_hms_opt(10, 0, 0) - .unwrap(); + let t = crate::util::time::db_datetime("2026-10-24T10:00:00".parse().unwrap()); events::Model { id, monitor_id, diff --git a/src/service/events.rs b/src/service/events.rs index e17ab73a..1f3e436d 100644 --- a/src/service/events.rs +++ b/src/service/events.rs @@ -1,4 +1,4 @@ -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use sea_orm::ActiveValue::Set; use tracing::instrument; @@ -50,11 +50,11 @@ pub async fn list( start_time: params .start_time .as_ref() - .map(|dt| crate::util::utc_to_naive_local(dt.0)), + .map(|dt| crate::util::utc_to_datetime(dt.0)), end_time: params .end_time .as_ref() - .map(|dt| crate::util::utc_to_naive_local(dt.0)), + .map(|dt| crate::util::utc_to_datetime(dt.0)), sort_field: params.sort.unwrap_or_default(), sort_direction: params.direction.unwrap_or_default(), alarm_frames_min: params.alarm_frames_min, @@ -152,8 +152,8 @@ pub async fn list_by_monitor( monitor_id: u32, page: Option, page_size: Option, - start_time: Option>, - end_time: Option>, + start_time: Option, + end_time: Option, scope: &MonitorScope, ) -> AppResult { use crate::dto::wrappers::DateTimeWrapper; @@ -245,10 +245,10 @@ pub async fn create( cause: Set(event.cause), start_date_time: Set(event .start_date_time - .map(|dt| crate::util::utc_to_naive_local(dt.0))), + .map(|dt| crate::util::utc_to_datetime(dt.0))), end_date_time: Set(event .end_date_time - .map(|dt| crate::util::utc_to_naive_local(dt.0))), + .map(|dt| crate::util::utc_to_datetime(dt.0))), width: Set(event.width), height: Set(event.height), length: Set(event.length.0), @@ -425,7 +425,7 @@ pub async fn get_event_counts_by_monitor( mod tests { use super::*; use crate::entity::events::Model as EventModel; - use chrono::DateTime; + use crate::util::time; use rust_decimal::Decimal; use sea_orm::{DatabaseBackend, MockDatabase, MockExecResult}; @@ -438,7 +438,7 @@ mod tests { secondary_storage_id: None, name: name.into(), cause: None, - start_date_time: DateTime::from_timestamp(1_700_000_000, 0).map(|dt| dt.naive_utc()), + start_date_time: Some(time::db_datetime("2023-11-14T22:13:20".parse().unwrap())), end_date_time: None, width: 1920, height: 1080, diff --git a/src/service/filter_build.rs b/src/service/filter_build.rs index 5a0831d2..978c8ee3 100644 --- a/src/service/filter_build.rs +++ b/src/service/filter_build.rs @@ -124,12 +124,11 @@ fn scalar_one(v: &serde_json::Value, kind: ValueKind) -> AppResult() .map_err(|_| bad("invalid datetime; expected ISO-8601 / RFC-3339"))?; // Event date columns are server-local wall-clock time (#173). - sea_orm::Value::from(crate::util::utc_to_naive_local( - dt.with_timezone(&chrono::Utc), - )) + sea_orm::Value::from(crate::util::utc_to_datetime(dt)) } ValueKind::Bool => { let b = match v { diff --git a/src/service/maintenance/audit/filesystem.rs b/src/service/maintenance/audit/filesystem.rs index f09512c3..84232a2a 100644 --- a/src/service/maintenance/audit/filesystem.rs +++ b/src/service/maintenance/audit/filesystem.rs @@ -441,20 +441,21 @@ pub fn quarantine_target( } /// Parse the `YYYYmmddTHHMMSS` stamp a quarantine batch is filed under. -pub fn parse_quarantine_stamp(name: &str) -> Option { - chrono::NaiveDateTime::parse_from_str(name, "%Y%m%dT%H%M%S").ok() +pub fn parse_quarantine_stamp(name: &str) -> Option { + jiff::civil::DateTime::strptime("%Y%m%dT%H%M%S", name).ok() } /// Quarantine batches older than the retention window. pub fn expired_quarantine_batches( quarantine_root: &Path, - now: chrono::NaiveDateTime, + now: jiff::civil::DateTime, retention_days: u64, ) -> Vec { if retention_days == 0 { return Vec::new(); } - let cutoff = now - chrono::Duration::days(retention_days as i64); + let window = jiff::SignedDuration::from_secs((retention_days as i64).saturating_mul(86_400)); + let cutoff = now.saturating_sub(window); let Ok(entries) = std::fs::read_dir(quarantine_root) else { return Vec::new(); }; @@ -719,8 +720,7 @@ mod tests { std::fs::create_dir_all(root.join("20260822T000000")).unwrap(); std::fs::create_dir_all(root.join("not-a-stamp")).unwrap(); - let now = - chrono::NaiveDateTime::parse_from_str("20260823T120000", "%Y%m%dT%H%M%S").unwrap(); + let now = jiff::civil::date(2026, 8, 23).at(12, 0, 0, 0); let expired = expired_quarantine_batches(&root, now, 7); assert_eq!(expired.len(), 1, "only the batch older than 7 days"); diff --git a/src/service/maintenance/audit/mod.rs b/src/service/maintenance/audit/mod.rs index e4285d0f..c0318597 100644 --- a/src/service/maintenance/audit/mod.rs +++ b/src/service/maintenance/audit/mod.rs @@ -147,7 +147,7 @@ struct EventLocation { id: u64, monitor_id: u32, scheme: String, - start_date_time: Option, + start_date_time: Option, } impl AuditService { @@ -468,7 +468,7 @@ impl AuditService { storages: &[crate::entity::storage::Model], ) -> u64 { let fs = &self.config.filesystem; - let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%S").to_string(); + let stamp = jiff::Timestamp::now().strftime("%Y%m%dT%H%M%S").to_string(); let cap = self.config.max_deletes_per_pass; let mut moved = 0u64; @@ -555,7 +555,7 @@ impl AuditService { if self.config.dry_run || fs.quarantine_retention_days == 0 { return; } - let now = chrono::Utc::now().naive_utc(); + let now = crate::util::time::utc_now(); for st in storages { let qroot = std::path::PathBuf::from(&st.path).join(&fs.quarantine_dir); for batch in diff --git a/src/service/maintenance/stats.rs b/src/service/maintenance/stats.rs index dec6c85f..5d5ed370 100644 --- a/src/service/maintenance/stats.rs +++ b/src/service/maintenance/stats.rs @@ -561,7 +561,7 @@ impl StatsService { /// These are the PHP web UI's sessions, which nothing else expires. async fn prune_sessions(&self) -> Result<(), DbErr> { let lifetime = self.cookie_lifetime_secs().await; - let cutoff = (chrono::Utc::now().timestamp() as u64).saturating_sub(lifetime); + let cutoff = (crate::util::time::unix_now() as u64).saturating_sub(lifetime); let backend = self.db.get_database_backend(); loop { let removed = self diff --git a/src/service/maintenance/telemetry.rs b/src/service/maintenance/telemetry.rs index aac81781..95890805 100644 --- a/src/service/maintenance/telemetry.rs +++ b/src/service/maintenance/telemetry.rs @@ -166,7 +166,7 @@ impl TelemetryService { } let interval = self.effective_interval().await; let last = self.last_upload().await.unwrap_or(0); - let now = chrono::Utc::now().timestamp(); + let now = crate::util::time::unix_now(); // `>=` rather than `>`: with a timer that fires exactly on the // interval, strict greater-than skips almost every send. @@ -260,7 +260,7 @@ impl TelemetryService { country: UNKNOWN.to_string(), latitude: UNKNOWN.to_string(), longitude: UNKNOWN.to_string(), - timestamp: chrono::Utc::now().to_rfc3339(), + timestamp: crate::util::time::rfc3339_offset(jiff::Timestamp::now()), monitor_count, event_count, architecture: std::env::consts::ARCH.to_string(), diff --git a/src/service/media_grant.rs b/src/service/media_grant.rs index 53cb9e49..c0c3fe18 100644 --- a/src/service/media_grant.rs +++ b/src/service/media_grant.rs @@ -251,7 +251,7 @@ pub fn uri_signer( resource: MediaResource, ttl: Duration, ) -> Option { - let now = chrono::Utc::now().timestamp(); + let now = crate::util::time::unix_now(); let media_exp = |cred_exp: i64| (now + ttl.as_secs() as i64).min(cred_exp); if let Some(grant) = grant { return Some(UriSigner { diff --git a/src/service/media_job_store.rs b/src/service/media_job_store.rs index c8f3008d..6d059935 100644 --- a/src/service/media_job_store.rs +++ b/src/service/media_job_store.rs @@ -7,6 +7,7 @@ //! systemd's `StateDirectory=` creates). Which one is decided once, by a //! read-only look at `information_schema`. +use crate::util::time; use std::path::PathBuf; use std::sync::Arc; @@ -36,7 +37,7 @@ pub struct NewJob { pub monitor_id: u32, pub params: String, pub created_by: Option, - pub created_at: chrono::NaiveDateTime, + pub created_at: sea_orm::prelude::DateTime, } /// Which jobs a listing wants. @@ -169,7 +170,7 @@ impl JobStore { &self, db: &DatabaseConnection, id: u32, - at: chrono::NaiveDateTime, + at: sea_orm::prelude::DateTime, ) -> AppResult { match self { JobStore::Table => Ok(media_jobs::Entity::update_many() @@ -220,7 +221,7 @@ impl JobStore { &self, db: &DatabaseConnection, id: u32, - at: chrono::NaiveDateTime, + at: sea_orm::prelude::DateTime, ) -> AppResult { match self { JobStore::Table => Ok(media_jobs::Entity::update_many() @@ -299,14 +300,14 @@ struct Stored { finished_at: Option, } -fn to_ms(t: chrono::NaiveDateTime) -> i64 { - t.and_utc().timestamp_millis() +/// The columns hold UTC digits. A stored job keeps them as epoch milliseconds. +fn to_ms(t: sea_orm::prelude::DateTime) -> i64 { + time::utc_instant(t).as_millisecond() } -fn from_ms(ms: i64) -> chrono::NaiveDateTime { - chrono::DateTime::from_timestamp_millis(ms) - .unwrap_or_default() - .naive_utc() +fn from_ms(ms: i64) -> sea_orm::prelude::DateTime { + let t = jiff::Timestamp::from_millisecond(ms).unwrap_or(jiff::Timestamp::UNIX_EPOCH); + time::db_datetime(time::utc_civil(t)) } impl From<&Model> for Stored { diff --git a/src/service/media_jobs.rs b/src/service/media_jobs.rs index f9e84943..8cb4683e 100644 --- a/src/service/media_jobs.rs +++ b/src/service/media_jobs.rs @@ -34,8 +34,9 @@ const FAILED: &str = "failed"; /// A generation that takes longer than this is stopped. const VIDEO_TIMEOUT: Duration = Duration::from_secs(30 * 60); -fn now() -> chrono::NaiveDateTime { - chrono::Utc::now().naive_utc() +/// The current time as the UTC digits the job columns hold. +fn now() -> sea_orm::prelude::DateTime { + crate::util::time::db_utc_now() } fn event_not_found(id: u64) -> AppError { diff --git a/src/service/monitor.rs b/src/service/monitor.rs index 1f0e5a79..423e9cf6 100644 --- a/src/service/monitor.rs +++ b/src/service/monitor.rs @@ -957,7 +957,7 @@ pub async fn audio_level( let monitor = repo::monitors::find_by_id(state.db(), id) .await? .ok_or_else(|| monitor_not_found(id))?; - let until = (chrono::Utc::now().timestamp() + 10) as u32; + let until = (crate::util::time::unix_now() + 10) as u32; let live = tokio::task::spawn_blocking(move || { crate::zm_shm::MonitorShm::connect(id) .ok() diff --git a/src/service/monitor_pipeline.rs b/src/service/monitor_pipeline.rs index 9b7bfaf6..6224fa92 100644 --- a/src/service/monitor_pipeline.rs +++ b/src/service/monitor_pipeline.rs @@ -84,7 +84,7 @@ pub async fn replace( ) .await?; let body = serde_json::to_string(&graph_doc)?; - let now = chrono::Utc::now().naive_utc(); + let now = crate::util::time::utc_now(); let row = repo::monitor_pipeline::upsert(state.db(), monitor_id, body, 1, now).await?; if let WorkerApply::Refused(errors) = apply_to_worker(state, monitor_id).await { @@ -161,7 +161,7 @@ pub async fn enable_zmnext( synopsis, ); let body = serde_json::to_string(&graph)?; - let now = chrono::Utc::now().naive_utc(); + let now = crate::util::time::utc_now(); repo::monitor_pipeline::upsert(state.db(), monitor_id, body, 1, now).await? } }; @@ -221,7 +221,7 @@ async fn restore_graph( state: &AppState, monitor_id: u32, previous: Option, - now: chrono::NaiveDateTime, + now: jiff::civil::DateTime, ) -> AppResult<()> { match previous { Some(old) => { diff --git a/src/service/notifications.rs b/src/service/notifications.rs index 00999120..4052680d 100644 --- a/src/service/notifications.rs +++ b/src/service/notifications.rs @@ -2,6 +2,7 @@ //! `NotificationsController` serves them: every user manages their own push //! tokens, and a System editor sees and manages everyone's. +use crate::util::time::db_datetime; use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, NotSet, QueryFilter, QueryOrder, Set}; use crate::dto::request::notifications::{ @@ -11,7 +12,7 @@ use crate::dto::response::notifications::NotificationResponse; use crate::entity::notifications; use crate::error::{AppError, AppResult, Resource, ResourceType}; use crate::server::state::AppState; -use crate::util::utc_to_naive_local; +use crate::util::utc_to_datetime; /// Who is asking: their id, and whether they are a System editor. #[derive(Debug, Clone, Copy)] @@ -86,7 +87,7 @@ pub async fn upsert( true, notifications::ActiveModel { id: NotSet, - created_on: Set(Some(chrono::Local::now().naive_local())), + created_on: Set(Some(db_datetime(crate::util::time::local_now()))), token: Set(req.token.clone()), interval: Set(0), push_state: Set(PushState::Enabled.as_str().into()), @@ -116,7 +117,7 @@ pub async fn upsert( am.badge_count = Set(v); } if let Some(v) = req.last_notified_at { - am.last_notified_at = Set(Some(utc_to_naive_local(v))); + am.last_notified_at = Set(Some(utc_to_datetime(v))); } let saved = if created { am.insert(state.db()).await? @@ -170,7 +171,7 @@ pub async fn update( am.badge_count = Set(v); } if let Some(v) = req.last_notified_at { - am.last_notified_at = Set(v.map(utc_to_naive_local)); + am.last_notified_at = Set(v.map(utc_to_datetime)); } if let (Some(uid), true) = (req.user_id, caller.admin) { am.user_id = Set(Some(uid)); diff --git a/src/service/retention/mod.rs b/src/service/retention/mod.rs index 03b12cfd..1e568486 100644 --- a/src/service/retention/mod.rs +++ b/src/service/retention/mod.rs @@ -255,7 +255,8 @@ pub(crate) async fn reap_candidates( let protected: HashSet = newest.into_values().collect(); let age_cutoff = (cfg.max_age_days > 0).then(|| { - chrono::Local::now().naive_local() - chrono::Duration::days(cfg.max_age_days as i64) + let age = jiff::SignedDuration::from_secs((cfg.max_age_days as i64).saturating_mul(86_400)); + crate::util::time::local_now().saturating_sub(age) }); let mut stats = ReapStats::default(); @@ -273,7 +274,7 @@ pub(crate) async fn reap_candidates( let over_bytes = cfg.max_bytes > 0 && used > cfg.max_bytes; let too_old = age_cutoff .zip(ev.start_date_time) - .is_some_and(|(cut, start)| start < cut); + .is_some_and(|(cut, start)| crate::util::time::civil(start) < cut); if !(over_free || over_bytes || too_old) { // Oldest-first: nothing further can be over-age, and space/quota @@ -460,11 +461,9 @@ mod tests { fn event(id: u64, monitor_id: u32, disk_space: Option) -> events::Model { use rust_decimal::Decimal; - let start = chrono::NaiveDate::from_ymd_opt(2026, 1, 1) - .unwrap() - .and_hms_opt(0, 0, 0) - .unwrap() - + chrono::Duration::minutes(id as i64); + let column = crate::util::time::db_datetime; + let start = jiff::civil::date(2026, 1, 1).at(0, 0, 0, 0) + + jiff::SignedDuration::from_mins(id as i64); events::Model { id, monitor_id, @@ -472,8 +471,8 @@ mod tests { secondary_storage_id: None, name: "ev".into(), cause: None, - start_date_time: Some(start), - end_date_time: Some(start + chrono::Duration::minutes(1)), + start_date_time: Some(column(start)), + end_date_time: Some(column(start + jiff::SignedDuration::from_mins(1))), width: 0, height: 0, length: Decimal::new(0, 0), @@ -666,7 +665,9 @@ mod tests { c.max_age_days = 1; let mut events = fifty_events_no_disk_space(); // all dated January 2026 let mut fresh = event(99, 1, Some(1)); - fresh.start_date_time = Some(chrono::Local::now().naive_local()); + fresh.start_date_time = Some(crate::util::time::db_datetime( + crate::util::time::local_now(), + )); events.push(fresh); let stats = reap_candidates(&c, &io, &storage(), events, 0) .await diff --git a/src/service/roles.rs b/src/service/roles.rs index c8f2fea9..eef20412 100644 --- a/src/service/roles.rs +++ b/src/service/roles.rs @@ -143,7 +143,7 @@ async fn revoke_tokens(state: &AppState, user_ids: &[u32]) -> AppResult<()> { return Ok(()); } // now+1, as logout does: it covers tokens minted in the current second. - let floor = chrono::Utc::now().timestamp() + 1; + let floor = crate::util::time::unix_now() + 1; // In memory first, so the tokens are dead even if the write below fails. for uid in user_ids { state.revocations.revoke(*uid, floor); @@ -227,7 +227,7 @@ mod tests { .append_exec_results(vec![done()]) .into_connection(); let state = AppState::for_test_with_db(db); - let issued = chrono::Utc::now().timestamp(); + let issued = crate::util::time::unix_now(); update( &state, @@ -272,7 +272,7 @@ mod tests { assert!(!state .revocations - .is_revoked(5, chrono::Utc::now().timestamp())); + .is_revoked(5, crate::util::time::unix_now())); } #[tokio::test] @@ -282,7 +282,7 @@ mod tests { .append_exec_results(vec![done(), done()]) .into_connection(); let state = AppState::for_test_with_db(db); - let issued = chrono::Utc::now().timestamp(); + let issued = crate::util::time::unix_now(); delete(&state, 7).await.unwrap(); diff --git a/src/service/server.rs b/src/service/server.rs index 73e77281..b5cd3210 100644 --- a/src/service/server.rs +++ b/src/service/server.rs @@ -19,9 +19,9 @@ pub async fn get_locale(state: &AppState) -> AppResult { let timezone = zm_tz.or_else(|| iana_time_zone::get_timezone().ok()); // Current offset of the process's local zone. - let now = chrono::Local::now(); - let utc_offset_seconds = now.offset().local_minus_utc(); - let utc_offset = now.format("%:z").to_string(); + let now = jiff::Zoned::now(); + let utc_offset_seconds = now.offset().seconds(); + let utc_offset = now.strftime("%:z").to_string(); Ok(LocaleResponse { timezone, diff --git a/src/service/synopsis/mod.rs b/src/service/synopsis/mod.rs index 31c9aef0..b5c0db29 100644 --- a/src/service/synopsis/mod.rs +++ b/src/service/synopsis/mod.rs @@ -67,7 +67,8 @@ pub struct SynopsisStatusView { pub url: Option, pub tube_count: u32, #[schema(value_type = Option, format = "date-time", example = "2026-07-02T12:34:56")] - pub expires_at: Option, + #[serde(with = "crate::util::datetime_format::optional")] + pub expires_at: Option, } /// How many stills are composited at once: one per core, at least two. The @@ -233,7 +234,7 @@ impl SynopsisService { status: row.status, url, tube_count: row.tube_count, - expires_at: row.expires_at, + expires_at: row.expires_at.map(crate::util::time::civil), }) } @@ -322,8 +323,8 @@ impl SynopsisService { pub async fn overview_still( &self, monitor_id: u32, - from: chrono::NaiveDateTime, - to: chrono::NaiveDateTime, + from: jiff::civil::DateTime, + to: jiff::civil::DateTime, class_filter: Vec, ) -> Result, SynopsisError> { let rows = repo::event_synopsis::find_by_monitor_created_between( @@ -372,7 +373,7 @@ impl SynopsisService { /// the DB row for every synopsis whose `expires_at` has passed. Returns the /// number of rows cleaned. pub async fn run_retention_once(&self) -> Result { - let now = chrono::Utc::now().naive_utc(); + let now = crate::util::time::utc_now(); let expired = repo::event_synopsis::find_expired(&self.db, now).await?; let mut cleaned = 0usize; for row in expired { diff --git a/src/service/token.rs b/src/service/token.rs index ff746c0d..b0b65b79 100644 --- a/src/service/token.rs +++ b/src/service/token.rs @@ -15,7 +15,7 @@ pub fn generate_tokens( user_id: u32, perms: UserPermissions, ) -> AppResult { - generate_tokens_issued_at(chrono::Utc::now().timestamp(), username, user_id, perms) + generate_tokens_issued_at(crate::util::time::unix_now(), username, user_id, perms) } /// [`generate_tokens`] with the issue time given. See diff --git a/src/service/users.rs b/src/service/users.rs index a791c9c5..e7c3c283 100644 --- a/src/service/users.rs +++ b/src/service/users.rs @@ -42,7 +42,7 @@ async fn ensure_role_exists(state: &AppState, role_id: u32) -> AppResult<()> { /// A revocation floor that kills every token issued up to now, including /// those minted earlier in the current second (see `service::auth::logout`). fn revoke_now_floor() -> u64 { - (chrono::Utc::now().timestamp() + 1) as u64 + (crate::util::time::unix_now() + 1) as u64 } pub async fn update( @@ -260,7 +260,7 @@ mod tests { .append_query_results::(vec![vec![user]]) .into_connection(); let state = AppState::for_test_with_db(db); - let issued = chrono::Utc::now().timestamp(); + let issued = crate::util::time::unix_now(); assert!(!state.revocations.is_revoked(6, issued)); update( &state, @@ -298,7 +298,7 @@ mod tests { }]) .into_connection(); let state = AppState::for_test_with_db(db); - let issued = chrono::Utc::now().timestamp(); + let issued = crate::util::time::unix_now(); delete(&state, 9).await.unwrap(); assert!(state.revocations.is_revoked(9, issued)); } diff --git a/src/service/zmnext/ingest.rs b/src/service/zmnext/ingest.rs index 4324efb1..ce0a14cd 100644 --- a/src/service/zmnext/ingest.rs +++ b/src/service/zmnext/ingest.rs @@ -29,7 +29,8 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; -use chrono::{DateTime, Duration, NaiveDateTime, Utc}; +use crate::util::time; +use jiff::civil::DateTime as Civil; use rust_decimal::Decimal; use sea_orm::{ ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QueryOrder, Set, @@ -54,7 +55,7 @@ use crate::streaming::source::{protocol, MonitorEvent, MonitorEventEnvelope}; struct OpenEvent { event_id: u64, monitor_id: u32, - start: NaiveDateTime, + start: Civil, frames: u32, alarm_frames: u32, tot_score: u64, @@ -65,7 +66,7 @@ struct OpenEvent { } impl OpenEvent { - fn new(event_id: u64, monitor_id: u32, start: NaiveDateTime) -> Self { + fn new(event_id: u64, monitor_id: u32, start: Civil) -> Self { Self { event_id, monitor_id, @@ -247,12 +248,12 @@ impl EventIngestor { (frame_no, open.clone()) }; - let delta = decimal_seconds((when - agg.start).num_milliseconds() as f64 / 1000.0); + let delta = decimal_seconds(when.duration_since(agg.start).as_millis() as f64 / 1000.0); frames::ActiveModel { event_id: Set(event_id), frame_id: Set(frame_no), r#type: Set(FrameType::Alarm), - time_stamp: Set(crate::util::utc_to_timestamp(when.and_utc())), + time_stamp: Set(crate::util::utc_to_timestamp(time::civil_utc(when))), delta: Set(delta), score: Set(score), ..Default::default() @@ -305,13 +306,7 @@ impl EventIngestor { /// Push an event's description text to the NL/semantic search index. No-op /// when search is disabled or the text is empty. Indexing failures are /// logged and swallowed — they must never break event ingest. - async fn index_for_search( - &self, - monitor_id: u32, - event_id: u64, - when: NaiveDateTime, - text: String, - ) { + async fn index_for_search(&self, monitor_id: u32, event_id: u64, when: Civil, text: String) { let Some(search) = self.search.as_ref() else { return; }; @@ -323,7 +318,7 @@ impl EventIngestor { .get(&monitor_id) .map(|o| o.labels.iter().cloned().collect()) .unwrap_or_default(); - let ts = when.and_utc().timestamp(); + let ts = time::civil_utc(when).as_second(); if let Err(e) = search .index_text(event_id, monitor_id, ts, classes, text) .await @@ -427,7 +422,7 @@ impl EventIngestor { let mut model = events::ActiveModel { id: Set(event_id), - end_date_time: Set(Some(end)), + end_date_time: Set(Some(time::db_datetime(end))), default_video: Set(detail.file_name().to_string()), ..Default::default() }; @@ -500,9 +495,13 @@ impl EventIngestor { let event_id = manifest.assigned_event_id(); let clip_token = manifest.clip_token.clone(); let tube_count = manifest.tubes.len() as u32; - let now = Utc::now().naive_utc(); + let now = time::utc_now(); let expires_at = (self.synopsis.retention_days > 0) - .then(|| now + Duration::days(self.synopsis.retention_days as i64)); + .then(|| { + let days = self.synopsis.retention_days as i64; + now.saturating_add(jiff::SignedDuration::from_secs(days.saturating_mul(86_400))) + }) + .map(time::db_datetime); // Locate an existing row: the (monitor, clip_token) key is stable across // the handshake; fall back to event_id when no token was sent. @@ -551,7 +550,7 @@ impl EventIngestor { tube_count: Set(tube_count), source_w: Set(manifest.source_w), source_h: Set(manifest.source_h), - created_at: Set(now), + created_at: Set(time::db_datetime(now)), expires_at: Set(expires_at), ..Default::default() }; @@ -571,7 +570,7 @@ impl EventIngestor { async fn ensure_open_event( &mut self, monitor_id: u32, - start: NaiveDateTime, + start: Civil, cause: Option, ) -> AppResult { if let Some(open) = self.open.get(&monitor_id) { @@ -584,7 +583,7 @@ impl EventIngestor { monitor_id: Set(monitor_id), name: Set(self.config.event_name.clone()), cause: Set(cause), - start_date_time: Set(Some(start)), + start_date_time: Set(Some(time::db_datetime(start))), state_id: Set(state_id), width: Set(dims.width), height: Set(dims.height), @@ -660,10 +659,10 @@ impl EventIngestor { dims: &MonitorDims, monitor_id: u32, event_id: u64, - start: NaiveDateTime, + start: Civil, ) -> Option<(String, String)> { let root = dims.storage_path.as_deref()?; - let date = start.format("%Y-%m-%d"); + let date = start.strftime("%Y-%m-%d"); let dir = format!( "{}/{monitor_id}/{date}/{event_id}", root.trim_end_matches('/') @@ -674,17 +673,18 @@ impl EventIngestor { } /// EVENT timestamp to use for a row: the wall-clock TLV when present, else now. -fn event_time(ev: &MonitorEvent) -> NaiveDateTime { +fn event_time(ev: &MonitorEvent) -> Civil { ev.wall_clock_us .and_then(micros_to_naive) - .unwrap_or_else(|| Utc::now().naive_utc()) + .unwrap_or_else(time::utc_now) } /// Convert unix-epoch microseconds to a naive-UTC datetime. -fn micros_to_naive(us: u64) -> Option { - let secs = (us / 1_000_000) as i64; - let nanos = ((us % 1_000_000) * 1_000) as u32; - DateTime::::from_timestamp(secs, nanos).map(|dt| dt.naive_utc()) +fn micros_to_naive(us: u64) -> Option { + let us = i64::try_from(us).ok()?; + jiff::Timestamp::from_microsecond(us) + .ok() + .map(time::utc_civil) } /// Seconds (possibly fractional) as a ZoneMinder `Decimal`, clamped at 0. @@ -744,7 +744,7 @@ mod tests { fn micros_round_trip_to_known_instant() { // 2023-11-14T22:13:20 UTC let dt = micros_to_naive(1_700_000_000_000_000).unwrap(); - assert_eq!(dt.and_utc().timestamp(), 1_700_000_000); + assert_eq!(time::civil_utc(dt).as_second(), 1_700_000_000); } #[test] diff --git a/src/service/zmnext/secrets.rs b/src/service/zmnext/secrets.rs index 6faf41ab..6f091e03 100644 --- a/src/service/zmnext/secrets.rs +++ b/src/service/zmnext/secrets.rs @@ -306,7 +306,7 @@ pub async fn stash_secrets( if !literals.is_empty() { let key = SecretKey::load_or_create(key_file).map_err(|e| key_error(key_file, e))?; - let now = chrono::Utc::now().naive_utc(); + let now = crate::util::time::utc_now(); for (name, value) in &literals { let sealed = key.seal(monitor_id, name, value); crate::repo::zmnext_secret::upsert(db, monitor_id, name, sealed, now).await?; @@ -342,7 +342,7 @@ pub async fn migrate_row( return Ok(row); } stash_secrets(db, key_file, row.monitor_id, &mut graph).await?; - let now = chrono::Utc::now().naive_utc(); + let now = crate::util::time::utc_now(); let saved = crate::repo::monitor_pipeline::upsert( db, row.monitor_id, diff --git a/src/streaming/live/webrtc.rs b/src/streaming/live/webrtc.rs index 9d8ae832..31ca1827 100644 --- a/src/streaming/live/webrtc.rs +++ b/src/streaming/live/webrtc.rs @@ -325,7 +325,8 @@ pub struct WebRtcSessionStats { pub state: WebRtcSessionState, pub packets_sent: u64, pub bytes_sent: u64, - pub created_at: chrono::DateTime, + #[serde(serialize_with = "crate::util::time::serialize_rfc3339_z")] + pub created_at: jiff::Timestamp, } /// One outgoing media track and what `write_sample` needs to address it. @@ -484,7 +485,7 @@ pub struct WebRtcLiveSession { /// Audio track — present when the monitor delivers audio the session /// can carry (G.711 pass-through or transcoded Opus) pub audio_track: Option, - pub created_at: chrono::DateTime, + pub created_at: jiff::Timestamp, packets_sent: AtomicU64, bytes_sent: AtomicU64, /// Candidates the viewer has sent so far. @@ -1081,7 +1082,7 @@ impl WebRtcLiveManager { peer_connection, video_track, audio_track, - created_at: chrono::Utc::now(), + created_at: jiff::Timestamp::now(), packets_sent: AtomicU64::new(0), bytes_sent: AtomicU64::new(0), remote_candidates: AtomicU64::new(0), diff --git a/src/streaming/live/whep.rs b/src/streaming/live/whep.rs index ca6070e3..7cebb53a 100644 --- a/src/streaming/live/whep.rs +++ b/src/streaming/live/whep.rs @@ -238,7 +238,7 @@ async fn run( } = handshake; let monitor_id = source.monitor_id(); // The credential check below counts from the session's start. - let started = chrono::Utc::now().timestamp(); + let started = crate::util::time::unix_now(); let connected = tokio::select! { r = tokio::time::timeout( diff --git a/src/streaming/rtsp/session.rs b/src/streaming/rtsp/session.rs index 223c4141..896012a1 100644 --- a/src/streaming/rtsp/session.rs +++ b/src/streaming/rtsp/session.rs @@ -409,7 +409,7 @@ async fn stream( Err(broadcast::error::RecvError::Closed) => break, }, _ = reauth.tick() => { - let expired = chrono::Utc::now().timestamp() >= exp; + let expired = crate::util::time::unix_now() >= exp; if expired || backend.authorize(&token, monitor_id).await.is_err() { info!("rtsp: monitor {monitor_id}: link no longer valid; closing"); break; diff --git a/src/streaming/rtsp/session_tests.rs b/src/streaming/rtsp/session_tests.rs index ce1322ac..2587c9a1 100644 --- a/src/streaming/rtsp/session_tests.rs +++ b/src/streaming/rtsp/session_tests.rs @@ -98,7 +98,7 @@ impl Backend for Fake { match (token, monitor_id) { ("good", 1) if self.valid.load(Ordering::SeqCst) => Ok(Grant { uid: 7, - exp: chrono::Utc::now().timestamp() + 3600, + exp: crate::util::time::unix_now() + 3600, }), ("good", 1) => Err(401), ("good", _) => Err(404), diff --git a/src/streaming/source/worker_status.rs b/src/streaming/source/worker_status.rs index 5472c21c..e485d564 100644 --- a/src/streaming/source/worker_status.rs +++ b/src/streaming/source/worker_status.rs @@ -88,7 +88,7 @@ pub struct StatusChange { } fn now_ms() -> i64 { - chrono::Utc::now().timestamp_millis() + jiff::Timestamp::now().as_millisecond() } fn str_field(d: &Map, k: &str) -> Option { diff --git a/src/util/assertion.rs b/src/util/assertion.rs index 5a802689..0046e78d 100644 --- a/src/util/assertion.rs +++ b/src/util/assertion.rs @@ -1,5 +1,5 @@ -use chrono::{DateTime, Utc}; use itertools::Itertools; +use jiff::Timestamp; use std::{collections::HashMap, hash::Hash}; use crate::dto::request::Direction; @@ -25,8 +25,8 @@ pub fn vecs_match(a: &[T], b: &[T]) -> bool { a.len() == b.len() && !a.iter().zip(b.iter()).any(|(a, b)| *a != *b) } -pub fn compare_datetime(left: &DateTime, right: &DateTime) -> bool { - left.format("%d/%m/%Y %H:%M").to_string() == right.format("%d/%m/%Y %H:%M").to_string() +pub fn compare_datetime(left: &Timestamp, right: &Timestamp) -> bool { + left.strftime("%d/%m/%Y %H:%M").to_string() == right.strftime("%d/%m/%Y %H:%M").to_string() } pub fn exist(haystack: &[T], needle: &T) -> bool @@ -112,11 +112,11 @@ fn vecs_match_is_order_sensitive() { #[test] fn compare_datetime_matches_to_the_minute() { - let base: DateTime = DateTime::from_timestamp(1_700_000_000, 0).unwrap(); + let base = Timestamp::from_second(1_700_000_000).unwrap(); // 30 seconds apart — same minute, considered equal. - let same_minute = DateTime::from_timestamp(1_700_000_030, 0).unwrap(); + let same_minute = Timestamp::from_second(1_700_000_030).unwrap(); // 120 seconds apart — different minute. - let next_minute = DateTime::from_timestamp(1_700_000_120, 0).unwrap(); + let next_minute = Timestamp::from_second(1_700_000_120).unwrap(); assert!(compare_datetime(&base, &same_minute)); assert!(!compare_datetime(&base, &next_minute)); } diff --git a/src/util/claim.rs b/src/util/claim.rs index 85bc3d6e..16714309 100644 --- a/src/util/claim.rs +++ b/src/util/claim.rs @@ -9,7 +9,6 @@ use axum_extra::{ use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::RequestPartsExt; -use chrono::Utc; use dashmap::DashMap; use fake::Dummy; use jsonwebtoken::Header; @@ -80,7 +79,7 @@ impl UserClaims { typ: TokenType, ) -> Self { Self::issued_at( - Utc::now().timestamp(), + crate::util::time::unix_now(), duration, username, user_id, diff --git a/src/util/datetime_format.rs b/src/util/datetime_format.rs deleted file mode 100644 index 69776ad8..00000000 --- a/src/util/datetime_format.rs +++ /dev/null @@ -1,84 +0,0 @@ -use chrono::{DateTime, NaiveDateTime, TimeZone, Utc}; -use serde::{Deserialize, Deserializer, Serializer}; -use std::fmt; - -pub mod iso8601 { - use super::*; - - const FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.3fZ"; - - pub fn serialize(datetime: &DateTime, serializer: S) -> Result - where - S: Serializer, - { - let s = datetime.format(FORMAT).to_string(); - serializer.serialize_str(&s) - } - - pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> - where - D: Deserializer<'de>, - { - struct DateTimeVisitor; - - impl<'de> serde::de::Visitor<'de> for DateTimeVisitor { - type Value = DateTime; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "an ISO 8601 formatted string") - } - - fn visit_str(self, value: &str) -> Result - where - E: serde::de::Error, - { - match NaiveDateTime::parse_from_str(value, FORMAT) { - Ok(dt) => Ok(Utc.from_utc_datetime(&dt)), - Err(_) => Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(value), - &"ISO 8601 formatted datetime string", - )), - } - } - } - - deserializer.deserialize_str(DateTimeVisitor) - } -} - -pub mod option_iso8601 { - use super::*; - - pub fn serialize( - opt_datetime: &Option>, - serializer: S, - ) -> Result - where - S: Serializer, - { - match opt_datetime { - Some(datetime) => super::iso8601::serialize(datetime, serializer), - None => serializer.serialize_none(), - } - } - - pub fn deserialize<'de, D>(deserializer: D) -> Result>, D::Error> - where - D: Deserializer<'de>, - { - #[derive(Deserialize)] - #[serde(untagged)] - enum DateTimeOrNull { - DateTime(String), - Null, - } - - match DateTimeOrNull::deserialize(deserializer)? { - DateTimeOrNull::DateTime(s) => { - let datetime = super::iso8601::deserialize(&s).map_err(serde::de::Error::custom)?; - Ok(Some(datetime)) - } - DateTimeOrNull::Null => Ok(None), - } - } -} \ No newline at end of file diff --git a/src/util/media_url.rs b/src/util/media_url.rs index d2a8fc17..c9e4de12 100644 --- a/src/util/media_url.rs +++ b/src/util/media_url.rs @@ -171,7 +171,7 @@ pub fn sign(resource: MediaResource, uid: u32, ttl: Duration) -> String { sign_until( resource, uid, - chrono::Utc::now().timestamp() + ttl.as_secs() as i64, + crate::util::time::unix_now() + ttl.as_secs() as i64, ) } @@ -182,7 +182,7 @@ pub fn sign_until(resource: MediaResource, uid: u32, exp: i64) -> String { &SignedGrant { resource, uid, - iat: chrono::Utc::now().timestamp(), + iat: crate::util::time::unix_now(), exp, }, ) @@ -190,7 +190,7 @@ pub fn sign_until(resource: MediaResource, uid: u32, exp: i64) -> String { /// Verify a signed URL token against the current time. pub fn verify(token: &str) -> Result { - verify_with(&KEY, token, chrono::Utc::now().timestamp()) + verify_with(&KEY, token, crate::util::time::unix_now()) } #[cfg(test)] diff --git a/src/util/mod.rs b/src/util/mod.rs index 4cb95cef..5506355e 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -17,8 +17,12 @@ pub mod result; pub mod retry; pub mod revocation; pub mod task; +pub mod time; pub mod ws; +use jiff::civil::DateTime as Civil; +use jiff::Timestamp; + /// Convert a ZoneMinder `DATETIME` value to true UTC. /// /// ZoneMinder stores `DATETIME` columns in the database in the **server's local @@ -31,11 +35,15 @@ pub mod ws; /// DST edge cases: an ambiguous local time (the "fall back" hour) takes the /// earlier instant; a non-existent local time (the "spring forward" gap) falls /// back to treating the value as already-UTC rather than failing. -pub fn naive_local_to_utc(ndt: chrono::NaiveDateTime) -> chrono::DateTime { - use chrono::{Local, LocalResult, TimeZone, Utc}; - match Local.from_local_datetime(&ndt) { - LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => dt.with_timezone(&Utc), - LocalResult::None => chrono::DateTime::::from_naive_utc_and_offset(ndt, Utc), +pub fn naive_local_to_utc(local: Civil) -> Timestamp { + use jiff::tz::{AmbiguousOffset, TimeZone}; + let ambiguous = TimeZone::system().into_ambiguous_zoned(local); + match ambiguous.offset() { + AmbiguousOffset::Gap { .. } => time::civil_utc(local), + _ => match ambiguous.earlier() { + Ok(zoned) => zoned.timestamp(), + Err(_) => time::civil_utc(local), + }, } } @@ -43,8 +51,20 @@ pub fn naive_local_to_utc(ndt: chrono::NaiveDateTime) -> chrono::DateTime) -> chrono::NaiveDateTime { - dt.with_timezone(&chrono::Local).naive_local() +pub fn utc_to_naive_local(t: Timestamp) -> Civil { + t.to_zoned(jiff::tz::TimeZone::system()).datetime() +} + +/// The true instant of a ZoneMinder `DATETIME` column, read straight off an +/// entity: [`naive_local_to_utc`] for a value that is still SeaORM's type. +pub fn datetime_to_utc(column: sea_orm::prelude::DateTime) -> Timestamp { + naive_local_to_utc(time::civil(column)) +} + +/// The value to bind to a ZoneMinder `DATETIME` column for a true instant: the +/// inverse of [`datetime_to_utc`]. +pub fn utc_to_datetime(t: Timestamp) -> sea_orm::prelude::DateTime { + time::db_datetime(utc_to_naive_local(t)) } /// The true instant of a ZoneMinder `TIMESTAMP` column (`Monitor_Status.UpdatedOn`, @@ -55,36 +75,35 @@ pub fn utc_to_naive_local(dt: chrono::DateTime) -> chrono::NaiveDat /// `DateTime` and labels those digits UTC, which put every value off by /// the UTC offset (zm-web showed every monitor Offline: its status row looked /// hours old, #216). This reads the digits as the local time they are. -pub fn timestamp_to_utc(column: chrono::DateTime) -> chrono::DateTime { - naive_local_to_utc(column.naive_utc()) +pub fn timestamp_to_utc(column: sea_orm::prelude::DateTimeUtc) -> Timestamp { + naive_local_to_utc(time::utc_civil(time::instant(column))) } /// The value to bind to a ZoneMinder `TIMESTAMP` column for a true instant: /// the inverse of [`timestamp_to_utc`]. MariaDB reads bound values in the /// session zone, so it must carry the local wall-clock. -pub fn utc_to_timestamp(dt: chrono::DateTime) -> chrono::DateTime { - utc_to_naive_local(dt).and_utc() +pub fn utc_to_timestamp(t: Timestamp) -> sea_orm::prelude::DateTimeUtc { + time::db_instant(time::civil_utc(utc_to_naive_local(t))) } #[cfg(test)] mod timestamp_column_tests { - use super::{timestamp_to_utc, utc_to_timestamp}; + use super::{time, timestamp_to_utc, utc_to_timestamp}; + use jiff::Timestamp; #[test] fn a_written_instant_reads_back_unchanged() { - let now = chrono::DateTime::parse_from_rfc3339("2026-10-23T21:30:15Z") - .unwrap() - .with_timezone(&chrono::Utc); + let now: Timestamp = "2026-10-23T21:30:15Z".parse().unwrap(); assert_eq!(timestamp_to_utc(utc_to_timestamp(now)), now); } /// The column carries local digits: what `NOW()` stores in a SYSTEM session. #[test] fn the_column_holds_local_wall_clock() { - let now = chrono::Utc::now(); + let now = Timestamp::now(); assert_eq!( - utc_to_timestamp(now).naive_utc(), - now.with_timezone(&chrono::Local).naive_local() + time::utc_civil(time::instant(utc_to_timestamp(now))), + now.to_zoned(jiff::tz::TimeZone::system()).datetime() ); } } @@ -92,68 +111,83 @@ mod timestamp_column_tests { #[cfg(test)] mod naive_local_to_utc_tests { use super::{naive_local_to_utc, utc_to_naive_local}; + use jiff::civil::date; + use jiff::tz::TimeZone; /// A client's UTC instant reaches the column as the wall-clock the column /// stores, whatever the server's zone. #[test] fn utc_to_local_inverts_local_to_utc() { - let ndt = chrono::NaiveDate::from_ymd_opt(2026, 10, 18) - .unwrap() - .and_hms_opt(11, 21, 23) - .unwrap(); - assert_eq!(utc_to_naive_local(naive_local_to_utc(ndt)), ndt); + let local = date(2026, 10, 18).at(11, 21, 23, 0); + assert_eq!(utc_to_naive_local(naive_local_to_utc(local)), local); } - use chrono::{Local, NaiveDate, TimeZone}; /// TZ-independent: interpreting the result back in the local zone must yield /// the original naive wall-clock. (Regression for the old code that stamped /// server-local time as UTC, shifting it by the offset.) #[test] fn round_trips_through_local() { - let ndt = NaiveDate::from_ymd_opt(2026, 8, 21) - .unwrap() - .and_hms_opt(0, 40, 11) - .unwrap(); - let utc = naive_local_to_utc(ndt); + let local = date(2026, 8, 21).at(0, 40, 11, 0); + let utc = naive_local_to_utc(local); // Convert back to local and compare the naive wall-clock. - assert_eq!(utc.with_timezone(&Local).naive_local(), ndt); - // And the absolute instant matches what Local says that wall-clock is - // (single, unambiguous for this date in any fixed zone). - if let chrono::LocalResult::Single(expected) = Local.from_local_datetime(&ndt) { - assert_eq!(utc, expected.with_timezone(&chrono::Utc)); + assert_eq!(utc.to_zoned(TimeZone::system()).datetime(), local); + // And the absolute instant matches what the zone says that wall-clock + // is (single, unambiguous for this date in any fixed zone). + let ambiguous = TimeZone::system().into_ambiguous_zoned(local); + if !ambiguous.is_ambiguous() { + assert_eq!(utc, ambiguous.compatible().unwrap().timestamp()); } } + + /// A wall-clock that the zone skips is read as UTC digits, and one that + /// occurs twice takes the earlier instant. + #[test] + fn dst_edges_resolve_the_documented_way() { + use jiff::tz::AmbiguousOffset; + let tz = TimeZone::get("America/New_York").unwrap(); + let gap = date(2026, 3, 8).at(2, 30, 0, 0); + assert!(matches!( + tz.to_ambiguous_zoned(gap).offset(), + AmbiguousOffset::Gap { .. } + )); + let fold = date(2026, 11, 1).at(1, 30, 0, 0); + let earlier = tz.to_ambiguous_zoned(fold).earlier().unwrap(); + assert_eq!(earlier.offset().seconds(), -4 * 3600); + } } pub mod datetime_format { - use chrono::NaiveDateTime; + use jiff::civil::DateTime as Civil; use serde::{self, Deserialize, Deserializer, Serializer}; - // Format for serializing/deserializing NaiveDateTime + // Format for serializing/deserializing a civil datetime const FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f"; - // For regular NaiveDateTime fields - pub fn serialize(date: &NaiveDateTime, serializer: S) -> Result + fn parse(s: &str) -> Result { + Civil::strptime(FORMAT, s).map_err(serde::de::Error::custom) + } + + // For regular civil datetime fields + pub fn serialize(date: &Civil, serializer: S) -> Result where S: Serializer, { - let s = format!("{}", date.format(FORMAT)); - serializer.serialize_str(&s) + serializer.serialize_str(&super::time::civil_string(*date)) } - pub fn deserialize<'de, D>(deserializer: D) -> Result + pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; - NaiveDateTime::parse_from_str(&s, FORMAT).map_err(serde::de::Error::custom) + parse(&s) } - // For Option fields + // For Option fields pub mod optional { use super::*; - pub fn serialize(date: &Option, serializer: S) -> Result + pub fn serialize(date: &Option, serializer: S) -> Result where S: Serializer, { @@ -163,14 +197,12 @@ pub mod datetime_format { } } - pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { Option::::deserialize(deserializer)? - .map(|s| { - NaiveDateTime::parse_from_str(&s, FORMAT).map_err(serde::de::Error::custom) - }) + .map(|s| parse(&s)) .transpose() } } diff --git a/src/util/time.rs b/src/util/time.rs new file mode 100644 index 00000000..5d558507 --- /dev/null +++ b/src/util/time.rs @@ -0,0 +1,239 @@ +//! Clock helpers, and the one place zm-api's jiff types meet SeaORM's. +//! +//! zm-api's own code uses jiff. SeaORM and sqlx still decode date columns into +//! chrono types, so the entities and anything bound to a query carry +//! `sea_orm::prelude::DateTime` (a chrono `NaiveDateTime`) and `DateTimeUtc` +//! (a chrono `DateTime`). The four converters below are the only code that +//! touches chrono's API. Convert as a value leaves an entity or enters a query, +//! and use jiff everywhere else. + +use jiff::civil::DateTime as Civil; +use jiff::tz::TimeZone; +use jiff::{SignedDuration, Timestamp, Zoned}; +use sea_orm::prelude::{DateTime as DbDateTime, DateTimeUtc as DbDateTimeUtc}; + +/// Seconds since the Unix epoch, for token claims and expiry checks. +pub fn unix_now() -> i64 { + Timestamp::now().as_second() +} + +/// The wall-clock time in UTC, with no offset attached. +pub fn utc_now() -> Civil { + utc_civil(Timestamp::now()) +} + +/// The wall-clock time in the server's zone, as ZoneMinder's `DATETIME` +/// columns store it. +pub fn local_now() -> Civil { + Zoned::now().datetime() +} + +/// The current UTC wall-clock as a value to bind to a `DATETIME` column that +/// zm-api keeps in UTC (its own tables, not ZoneMinder's local-time ones). +pub fn db_utc_now() -> DbDateTime { + db_datetime(utc_now()) +} + +/// The UTC wall-clock digits of an instant. +pub fn utc_civil(t: Timestamp) -> Civil { + t.to_zoned(TimeZone::UTC).datetime() +} + +/// The instant whose UTC wall-clock digits are `c`. +pub fn civil_utc(c: Civil) -> Timestamp { + match c.to_zoned(TimeZone::UTC) { + Ok(z) => z.timestamp(), + // Only the last hours of year 9999 or the first of -9999 fail. + Err(_) if c.year() < 0 => Timestamp::MIN, + Err(_) => Timestamp::MAX, + } +} + +const EPOCH: Civil = Civil::constant(1970, 1, 1, 0, 0, 0, 0); + +/// A `DATETIME` column value as a jiff civil datetime. The digits are unchanged. +/// +/// This counts from the epoch in civil arithmetic and never goes through +/// [`Timestamp`], whose range stops short of the last day MySQL can store +/// (`9999-12-31`). +pub fn civil(column: DbDateTime) -> Civil { + let utc = column.and_utc(); + let since_epoch = SignedDuration::new(utc.timestamp(), utc.timestamp_subsec_nanos() as i32); + match EPOCH.checked_add(since_epoch) { + Ok(c) => c, + // chrono's range is wider than jiff's (years -9999 to 9999). + Err(_) if since_epoch.is_negative() => Civil::MIN, + Err(_) => Civil::MAX, + } +} + +/// The instant of a `DATETIME` column that holds UTC digits, as zm-api's own +/// tables do. ZoneMinder's columns hold local time: use +/// [`crate::util::datetime_to_utc`] for those. +pub fn utc_instant(column: DbDateTime) -> Timestamp { + civil_utc(civil(column)) +} + +/// A jiff civil datetime as a value to bind to a `DATETIME` column. +pub fn db_datetime(c: Civil) -> DbDateTime { + let since_epoch = c.duration_since(EPOCH); + let nanos = since_epoch.as_nanos(); + let secs = nanos.div_euclid(1_000_000_000) as i64; + let sub = nanos.rem_euclid(1_000_000_000) as u32; + // jiff's range sits inside chrono's, so this always succeeds. + DbDateTimeUtc::from_timestamp(secs, sub) + .unwrap_or_default() + .naive_utc() +} + +/// A chrono UTC instant as a jiff timestamp. No zone arithmetic: see +/// [`crate::util::timestamp_to_utc`] for reading a `TIMESTAMP` column. +pub fn instant(t: DbDateTimeUtc) -> Timestamp { + let secs = t.timestamp(); + match Timestamp::new(secs, t.timestamp_subsec_nanos() as i32) { + Ok(ts) => ts, + // chrono's range is wider than jiff's (years -9999 to 9999). + Err(_) if secs < 0 => Timestamp::MIN, + Err(_) => Timestamp::MAX, + } +} + +/// A jiff timestamp as a chrono UTC instant. +pub fn db_instant(t: Timestamp) -> DbDateTimeUtc { + let nanos = t.as_nanosecond(); + let secs = nanos.div_euclid(1_000_000_000) as i64; + let sub = nanos.rem_euclid(1_000_000_000) as u32; + // jiff's range sits inside chrono's, so this always succeeds. + DbDateTimeUtc::from_timestamp(secs, sub).unwrap_or_default() +} + +/// The fraction chrono printed: none for whole seconds, otherwise 3, 6 or 9 +/// digits. zm-api's JSON kept this shape when it moved to jiff, whose own +/// output trims trailing zeros instead. +fn fraction(nanos: i32) -> String { + let nanos = nanos.unsigned_abs(); + if nanos == 0 { + String::new() + } else if nanos.is_multiple_of(1_000_000) { + format!(".{:03}", nanos / 1_000_000) + } else if nanos.is_multiple_of(1_000) { + format!(".{:06}", nanos / 1_000) + } else { + format!(".{nanos:09}") + } +} + +/// `2026-10-23T21:30:15`, the digits of a civil datetime. +pub fn civil_string(c: Civil) -> String { + format!( + "{}{}", + c.strftime("%Y-%m-%dT%H:%M:%S"), + fraction(c.subsec_nanosecond()) + ) +} + +/// `2026-10-23T21:30:15Z`, an instant in RFC 3339 with the `Z` suffix. +pub fn rfc3339_z(t: Timestamp) -> String { + format!("{}Z", civil_string(utc_civil(t))) +} + +/// `2026-10-23T21:30:15+00:00`, an instant in RFC 3339 with a numeric offset. +pub fn rfc3339_offset(t: Timestamp) -> String { + format!("{}+00:00", civil_string(utc_civil(t))) +} + +/// `2026-10-23 21:30:15 UTC`, the spelling `GET /frames` has always used for +/// `time_stamp` (chrono's `Display`). Kept so existing clients still parse it. +pub fn utc_display(t: Timestamp) -> String { + let c = utc_civil(t); + format!( + "{}{} UTC", + c.strftime("%Y-%m-%d %H:%M:%S"), + fraction(c.subsec_nanosecond()) + ) +} + +/// `serialize_with` for a field that must keep [`rfc3339_z`]'s spelling. +pub fn serialize_rfc3339_z(t: &Timestamp, s: S) -> Result { + s.serialize_str(&rfc3339_z(*t)) +} + +/// `serialize_with` for an optional instant, in [`rfc3339_z`]'s spelling. +pub fn serialize_option_rfc3339_z( + t: &Option, + s: S, +) -> Result { + match t { + Some(t) => s.serialize_str(&rfc3339_z(*t)), + None => s.serialize_none(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_datetime_column_keeps_its_digits_both_ways() { + let c: Civil = "2026-10-23T21:30:15.25".parse().unwrap(); + let column = db_datetime(c); + assert_eq!(column.to_string(), "2026-10-23 21:30:15.250"); + assert_eq!(civil(column), c); + } + + /// MySQL's whole `DATETIME` range, including the day jiff's `Timestamp` + /// cannot reach, and a value before the epoch. + #[test] + fn a_datetime_column_keeps_its_digits_at_the_edges() { + for (text, chrono_text) in [ + ("9999-12-31T12:00:00", "9999-12-31 12:00:00"), + ("9999-12-31T23:59:59.999999", "9999-12-31 23:59:59.999999"), + ("1000-01-01T00:00:00", "1000-01-01 00:00:00"), + ("1969-12-31T23:59:59.5", "1969-12-31 23:59:59.500"), + ] { + let c: Civil = text.parse().unwrap(); + let column = db_datetime(c); + assert_eq!(column.to_string(), chrono_text); + assert_eq!(civil(column), c); + } + } + + #[test] + fn an_instant_survives_the_round_trip() { + let t: Timestamp = "2026-10-23T21:30:15.000000001Z".parse().unwrap(); + assert_eq!(instant(db_instant(t)), t); + } + + #[test] + fn an_instant_before_the_epoch_survives_the_round_trip() { + let t: Timestamp = "1969-12-31T23:59:59.5Z".parse().unwrap(); + let column = db_instant(t); + assert_eq!(column.timestamp(), -1); + assert_eq!(column.timestamp_subsec_nanos(), 500_000_000); + assert_eq!(instant(column), t); + } + + #[test] + fn civil_and_instant_agree_on_utc_digits() { + let t: Timestamp = "2026-01-02T03:04:05Z".parse().unwrap(); + assert_eq!(utc_civil(t).to_string(), "2026-01-02T03:04:05"); + assert_eq!(civil_utc(utc_civil(t)), t); + } + + #[test] + fn strings_keep_the_fraction_widths_clients_already_see() { + let whole: Timestamp = "2026-10-23T21:30:15Z".parse().unwrap(); + assert_eq!(rfc3339_z(whole), "2026-10-23T21:30:15Z"); + assert_eq!(rfc3339_offset(whole), "2026-10-23T21:30:15+00:00"); + let millis: Timestamp = "2026-10-23T21:30:15.5Z".parse().unwrap(); + assert_eq!(rfc3339_z(millis), "2026-10-23T21:30:15.500Z"); + let micros: Timestamp = "2026-10-23T21:30:15.000250Z".parse().unwrap(); + assert_eq!(rfc3339_z(micros), "2026-10-23T21:30:15.000250Z"); + let nanos: Timestamp = "2026-10-23T21:30:15.000000001Z".parse().unwrap(); + assert_eq!(rfc3339_offset(nanos), "2026-10-23T21:30:15.000000001+00:00"); + assert_eq!(utc_display(whole), "2026-10-23 21:30:15 UTC"); + assert_eq!(utc_display(millis), "2026-10-23 21:30:15.500 UTC"); + let c: Civil = "2025-04-24T12:34:56.120".parse().unwrap(); + assert_eq!(civil_string(c), "2025-04-24T12:34:56.120"); + } +} diff --git a/tests/handlers_monitors_events_frames_integration.rs b/tests/handlers_monitors_events_frames_integration.rs index 68e5090a..92dc2459 100644 --- a/tests/handlers_monitors_events_frames_integration.rs +++ b/tests/handlers_monitors_events_frames_integration.rs @@ -332,7 +332,7 @@ async fn create_event_db_now( monitor_id: Set(monitor_id), state_id: Set(1), name: Set(name), - start_date_time: Set(Some(chrono::Utc::now().naive_utc())), + start_date_time: Set(Some(zm_api::util::time::db_utc_now())), ..Default::default() }; model.insert(db).await diff --git a/tests/it_event_delete.rs b/tests/it_event_delete.rs index 37b5de29..b53d45fc 100644 --- a/tests/it_event_delete.rs +++ b/tests/it_event_delete.rs @@ -34,7 +34,7 @@ async fn insert_event_on_storage( scheme: Scheme, label: &str, ) -> u64 { - let now = chrono::Utc::now().naive_utc(); + let now = zm_api::util::time::db_utc_now(); zm_api::entity::events::ActiveModel { monitor_id: Set(monitor_id), storage_id: Set(Some(storage_id)), diff --git a/tests/it_event_filters.rs b/tests/it_event_filters.rs index 5dc5a2c1..ff45a0cf 100644 --- a/tests/it_event_filters.rs +++ b/tests/it_event_filters.rs @@ -18,7 +18,7 @@ async fn insert_event(db: &DatabaseConnection, monitor_id: u32, name: &str, caus state_id: Set(1), name: Set(unique_name(name)), cause: Set(Some(cause.to_string())), - start_date_time: Set(Some(chrono::Utc::now().naive_utc())), + start_date_time: Set(Some(zm_api::util::time::db_utc_now())), ..Default::default() } .insert(db) diff --git a/tests/it_event_media.rs b/tests/it_event_media.rs index f444cd1b..26de5f09 100644 --- a/tests/it_event_media.rs +++ b/tests/it_event_media.rs @@ -51,12 +51,12 @@ async fn recorded(label: &str) -> Option { width: Set(160), height: Set(120), default_video: Set(String::new()), - start_date_time: Set(Some( - chrono::Utc::now().naive_utc() - chrono::Duration::seconds(60), - )), - end_date_time: Set(Some( - chrono::Utc::now().naive_utc() - chrono::Duration::seconds(58), - )), + start_date_time: Set(Some(zm_api::util::time::db_datetime( + zm_api::util::time::utc_now() - jiff::SignedDuration::from_secs(60), + ))), + end_date_time: Set(Some(zm_api::util::time::db_datetime( + zm_api::util::time::utc_now() - jiff::SignedDuration::from_secs(58), + ))), ..Default::default() } .insert(&app.db) diff --git a/tests/it_event_stream.rs b/tests/it_event_stream.rs index 9f87f921..065708ac 100644 --- a/tests/it_event_stream.rs +++ b/tests/it_event_stream.rs @@ -51,7 +51,7 @@ async fn an_event_starts_ends_and_gets_notes() { let monitor = insert_monitor(&db, "EvStreamMon").await.expect("monitor"); let _m = RowGuard::monitor(monitor.id); - let now = chrono::Utc::now().naive_utc(); + let now = zm_api::util::time::db_utc_now(); let event = zm_api::entity::events::ActiveModel { monitor_id: Set(monitor.id), state_id: Set(1), diff --git a/tests/it_events_list_filters.rs b/tests/it_events_list_filters.rs index 2fc85e6c..1bebe69b 100644 --- a/tests/it_events_list_filters.rs +++ b/tests/it_events_list_filters.rs @@ -348,7 +348,7 @@ async fn hourly_counts_can_be_for_one_monitor() { let _ma = RowGuard::monitor(a.id); let b = insert_monitor(&app.db, "HistB").await.expect("monitor b"); let _mb = RowGuard::monitor(b.id); - let now = chrono::Utc::now().naive_utc(); + let now = zm_api::util::time::db_utc_now(); let mut guards = Vec::new(); for (mid, n) in [(a.id, 2), (b.id, 3)] { for _ in 0..n { @@ -408,12 +408,8 @@ async fn the_event_audit_finds_gaps_and_missing_or_empty_media() { let _m = RowGuard::monitor(monitor.id); // Stored as ZoneMinder stores them: server-local wall-clock. - let base = chrono::NaiveDate::from_ymd_opt(2026, 10, 1) - .unwrap() - .and_hms_opt(10, 0, 0) - .unwrap() - .and_utc(); - let at = |s: i64| zm_api::util::utc_to_naive_local(base + chrono::Duration::seconds(s)); + let base: jiff::Timestamp = "2026-10-01T10:00:00Z".parse().unwrap(); + let at = |s: i64| zm_api::util::utc_to_datetime(base + jiff::SignedDuration::from_secs(s)); // (start, end, video bytes): 0 = empty file, None = no file. let specs = [(0, 60, Some(5)), (90, 120, Some(0)), (110, 200, None)]; let mut ids = Vec::new(); @@ -506,15 +502,14 @@ async fn time_filters_round_trip_an_events_reported_start() { let token = superuser_token(); let monitor = insert_monitor(&app.db, "TzRound").await.expect("monitor"); let _m = RowGuard::monitor(monitor.id); - let start_utc = - chrono::DateTime::from_timestamp(chrono::Utc::now().timestamp() - 600, 0).unwrap(); + let start_utc = jiff::Timestamp::from_second(zm_api::util::time::unix_now() - 600).unwrap(); let e = zm_api::entity::events::ActiveModel { monitor_id: Set(monitor.id), state_id: Set(1), name: Set(unique_name("TzRound")), - start_date_time: Set(Some(zm_api::util::utc_to_naive_local(start_utc))), - end_date_time: Set(Some(zm_api::util::utc_to_naive_local( - start_utc + chrono::Duration::seconds(30), + start_date_time: Set(Some(zm_api::util::utc_to_datetime(start_utc))), + end_date_time: Set(Some(zm_api::util::utc_to_datetime( + start_utc + jiff::SignedDuration::from_secs(30), ))), ..Default::default() } @@ -528,10 +523,10 @@ async fn time_filters_round_trip_an_events_reported_start() { .await .json(); let reported = reported["start_date_time"].as_str().unwrap().to_string(); - let at = chrono::DateTime::parse_from_rfc3339(&reported).unwrap(); + let at: jiff::Timestamp = reported.parse().unwrap(); assert_eq!( - at.timestamp(), - start_utc.timestamp(), + at.as_second(), + start_utc.as_second(), "reported as UTC: {reported}" ); @@ -558,7 +553,7 @@ async fn time_filters_round_trip_an_events_reported_start() { } }; assert_eq!(ids(reported.clone()).await, vec![e.id]); - let later = (at + chrono::Duration::seconds(1)).to_rfc3339(); + let later = zm_api::util::time::rfc3339_offset(at + jiff::SignedDuration::from_secs(1)); assert!(ids(later).await.is_empty()); } @@ -612,7 +607,7 @@ async fn counts_by_monitor_filters_archived_events() { monitor_id: Set(monitor.id), state_id: Set(1), name: Set(unique_name("EvCountArch")), - start_date_time: Set(Some(chrono::Utc::now().naive_utc())), + start_date_time: Set(Some(zm_api::util::time::db_utc_now())), length: Set(Decimal::new(1, 0)), archived: Set(archived), ..Default::default() diff --git a/tests/it_frame_images.rs b/tests/it_frame_images.rs index 6f7a04f2..1e3336dd 100644 --- a/tests/it_frame_images.rs +++ b/tests/it_frame_images.rs @@ -169,7 +169,7 @@ async fn is_white(f: &Fixture, fid: &str) -> bool { async fn set_event(f: &Fixture, closed: bool, max_score_frame_id: u32) { zm_api::entity::events::ActiveModel { id: Set(f.event_id), - end_date_time: Set(closed.then(|| chrono::Utc::now().naive_utc())), + end_date_time: Set(closed.then(zm_api::util::time::db_utc_now)), max_score_frame_id: Set(Some(max_score_frame_id)), ..Default::default() } diff --git a/tests/it_logs.rs b/tests/it_logs.rs index 9beb7ead..230b2914 100644 --- a/tests/it_logs.rs +++ b/tests/it_logs.rs @@ -24,7 +24,7 @@ async fn insert_log( message: &str, offset: i64, ) { - let t = chrono::Utc::now().timestamp() + offset; + let t = zm_api::util::time::unix_now() + offset; zm_api::entity::logs::ActiveModel { time_key: Set(Decimal::new(t, 0)), component: Set(component.to_string()), diff --git a/tests/it_media_links.rs b/tests/it_media_links.rs index 63b2ddcc..31580b08 100644 --- a/tests/it_media_links.rs +++ b/tests/it_media_links.rs @@ -47,7 +47,7 @@ async fn an_expired_signature_is_unauthorized() { let st = sign_until( MediaResource::Monitor(1), 7, - chrono::Utc::now().timestamp() - 1, + zm_api::util::time::unix_now() - 1, ); let path = format!( "/api/v3/live/1/hls/init.mp4?st={}", diff --git a/tests/it_monitor_status.rs b/tests/it_monitor_status.rs index c6896bec..25d6b7a5 100644 --- a/tests/it_monitor_status.rs +++ b/tests/it_monitor_status.rs @@ -24,7 +24,7 @@ async fn insert_status(db: &sea_orm::DatabaseConnection, monitor_id: u32) { analysis_fps: Set(Decimal::new(1480, 2)), capture_bandwidth: Set(1024), // Local wall-clock, as zmc's NOW() writes it in a SYSTEM-zone session. - updated_on: Set(zm_api::util::utc_to_timestamp(chrono::Utc::now())), + updated_on: Set(zm_api::util::utc_to_timestamp(jiff::Timestamp::now())), } .insert(db) .await @@ -88,10 +88,10 @@ async fn get_monitor_status_returns_the_row() { // A row written just now must read back as just now, not shifted by the // server's UTC offset: zm-web marks a monitor Offline when it is older // than 90 s. - let updated = chrono::DateTime::parse_from_rfc3339(&body.updated_on).expect("RFC 3339"); - let age = chrono::Utc::now() - .signed_duration_since(updated) - .num_seconds() + let updated: jiff::Timestamp = body.updated_on.parse().expect("RFC 3339"); + let age = jiff::Timestamp::now() + .duration_since(updated) + .as_secs() .abs(); assert!( age < 60, diff --git a/tests/it_real_users.rs b/tests/it_real_users.rs index 4cd6c9bf..c553fe68 100644 --- a/tests/it_real_users.rs +++ b/tests/it_real_users.rs @@ -65,7 +65,7 @@ async fn site(app: &TestApp) -> Site { capture_fps: Set(Decimal::new(1000, 2)), analysis_fps: Set(Decimal::new(1000, 2)), capture_bandwidth: Set(0), - updated_on: Set(zm_api::util::utc_to_timestamp(chrono::Utc::now())), + updated_on: Set(zm_api::util::utc_to_timestamp(jiff::Timestamp::now())), } .insert(&app.db) .await diff --git a/tests/it_retention.rs b/tests/it_retention.rs index dd1377ce..fefd151e 100644 --- a/tests/it_retention.rs +++ b/tests/it_retention.rs @@ -37,12 +37,13 @@ async fn insert_event( db: &DatabaseConnection, monitor_id: u32, storage_id: u16, - start: chrono::NaiveDateTime, + start: jiff::civil::DateTime, ended: bool, archived: u8, disk_space: u64, label: &str, ) -> u64 { + let start = zm_api::util::time::db_datetime(start); zm_api::entity::events::ActiveModel { monitor_id: Set(monitor_id), storage_id: Set(Some(storage_id)), @@ -123,13 +124,13 @@ async fn reap_deletes_oldest_over_quota_and_protects_newest() { let _mg = RowGuard::monitor(monitor.id); let (storage, _sg) = dedicated_storage(&db, &tmp, "ReapStore").await; - let base = chrono::Utc::now().naive_utc(); + let base = zm_api::util::time::utc_now(); // Oldest -> newest; 100 MiB each; total 300 MiB. let e1 = insert_event( &db, monitor.id, storage.id, - base - chrono::Duration::hours(3), + base - jiff::SignedDuration::from_hours(3), true, 0, 100 * MIB, @@ -140,7 +141,7 @@ async fn reap_deletes_oldest_over_quota_and_protects_newest() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(2), + base - jiff::SignedDuration::from_hours(2), true, 0, 100 * MIB, @@ -151,7 +152,7 @@ async fn reap_deletes_oldest_over_quota_and_protects_newest() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(1), + base - jiff::SignedDuration::from_hours(1), true, 0, 100 * MIB, @@ -202,13 +203,13 @@ async fn reap_never_touches_archived_or_in_progress_events() { // directory a real storage has. std::fs::create_dir_all(tmp.path().join(monitor.id.to_string())).unwrap(); - let base = chrono::Utc::now().naive_utc(); + let base = zm_api::util::time::utc_now(); // Archived + in-progress are old and large but must be immune to the reaper. let archived = insert_event( &db, monitor.id, storage.id, - base - chrono::Duration::hours(5), + base - jiff::SignedDuration::from_hours(5), true, 1, 100 * MIB, @@ -219,7 +220,7 @@ async fn reap_never_touches_archived_or_in_progress_events() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(4), + base - jiff::SignedDuration::from_hours(4), false, 0, 100 * MIB, @@ -231,7 +232,7 @@ async fn reap_never_touches_archived_or_in_progress_events() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(3), + base - jiff::SignedDuration::from_hours(3), true, 0, 100 * MIB, @@ -242,7 +243,7 @@ async fn reap_never_touches_archived_or_in_progress_events() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(1), + base - jiff::SignedDuration::from_hours(1), true, 0, 100 * MIB, @@ -294,12 +295,12 @@ async fn reap_dry_run_reports_but_deletes_nothing() { let _mg = RowGuard::monitor(monitor.id); let (storage, _sg) = dedicated_storage(&db, &tmp, "ReapDryStore").await; - let base = chrono::Utc::now().naive_utc(); + let base = zm_api::util::time::utc_now(); let e1 = insert_event( &db, monitor.id, storage.id, - base - chrono::Duration::hours(3), + base - jiff::SignedDuration::from_hours(3), true, 0, 100 * MIB, @@ -310,7 +311,7 @@ async fn reap_dry_run_reports_but_deletes_nothing() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(2), + base - jiff::SignedDuration::from_hours(2), true, 0, 100 * MIB, @@ -321,7 +322,7 @@ async fn reap_dry_run_reports_but_deletes_nothing() { &db, monitor.id, storage.id, - base - chrono::Duration::hours(1), + base - jiff::SignedDuration::from_hours(1), true, 0, 100 * MIB, diff --git a/tests/it_synopsis.rs b/tests/it_synopsis.rs index c621a214..2c37e562 100644 --- a/tests/it_synopsis.rs +++ b/tests/it_synopsis.rs @@ -19,9 +19,10 @@ mod common; use std::sync::Arc; use axum::http::{Method, StatusCode}; -use chrono::{Duration, Utc}; +use jiff::SignedDuration; use sea_orm::{ActiveModelTrait, EntityTrait, Set}; use tokio::sync::mpsc; +use zm_api::util::time::{db_datetime, utc_now}; use common::fixtures::{insert_monitor, unique_name, RowGuard}; use common::harness::{superuser_token, TestApp}; @@ -120,7 +121,7 @@ async fn insert_synopsis_row( tube_count: Set(1), source_w: Set(32), source_h: Set(24), - created_at: Set(Utc::now().naive_utc()), + created_at: Set(db_datetime(utc_now())), expires_at: Set(None), ..Default::default() } @@ -187,7 +188,7 @@ async fn synopsis_repo_round_trip() { assert_eq!(reloaded.rendered_path.as_deref(), Some("/tmp/out.mp4")); // not expired (expires_at is NULL), so find_expired in the far future is empty for it - let future = Utc::now().naive_utc() + Duration::days(3650); + let future = utc_now() + SignedDuration::from_hours(3650 * 24); let expired = repo::event_synopsis::find_expired(&db, future) .await .unwrap(); @@ -559,8 +560,8 @@ async fn overview_merges_events_in_window() { }, ); - let from = Utc::now().naive_utc() - Duration::hours(1); - let to = Utc::now().naive_utc() + Duration::hours(1); + let from = utc_now() - SignedDuration::from_hours(1); + let to = utc_now() + SignedDuration::from_hours(1); let jpeg = service .overview_still(monitor_id, from, to, vec![]) .await @@ -568,8 +569,8 @@ async fn overview_merges_events_in_window() { assert_eq!(&jpeg[0..2], &[0xFF, 0xD8], "overview is a JPEG"); // A window with no synopses → NotFound. - let empty_from = Utc::now().naive_utc() + Duration::days(3650); - let empty_to = empty_from + Duration::hours(1); + let empty_from = utc_now() + SignedDuration::from_hours(3650 * 24); + let empty_to = empty_from + SignedDuration::from_hours(1); let err = service .overview_still(monitor_id, empty_from, empty_to, vec![]) .await @@ -600,7 +601,7 @@ async fn retention_removes_expired_rows_and_cached_mp4() { let mp4_path = cache_dir.join("event-990808.mp4"); std::fs::write(&mp4_path, b"\x00\x00\x00\x18ftypmp42fake").expect("write fake mp4"); - let now = Utc::now().naive_utc(); + let now = utc_now(); let row = event_synopsis::ActiveModel { event_id: Set(Some(990_808)), monitor_id: Set(monitor_id), @@ -612,8 +613,8 @@ async fn retention_removes_expired_rows_and_cached_mp4() { tube_count: Set(1), source_w: Set(32), source_h: Set(24), - created_at: Set(now - Duration::days(8)), - expires_at: Set(Some(now - Duration::days(1))), // expired yesterday + created_at: Set(db_datetime(now - SignedDuration::from_hours(8 * 24))), + expires_at: Set(Some(db_datetime(now - SignedDuration::from_hours(24)))), // expired yesterday ..Default::default() } .insert(&fixture_db) diff --git a/tests/it_zmnext_secrets.rs b/tests/it_zmnext_secrets.rs index b1d4f263..32f71844 100644 --- a/tests/it_zmnext_secrets.rs +++ b/tests/it_zmnext_secrets.rs @@ -176,7 +176,7 @@ async fn a_legacy_graph_is_migrated_on_read_and_resolves_for_the_worker() { let db = get_test_db().await.unwrap(); let monitor = insert_monitor(&db, "zmnext_secrets_legacy").await.unwrap(); let _mon = RowGuard::monitor(monitor.id); - let now = chrono::Utc::now().naive_utc(); + let now = zm_api::util::time::utc_now(); zm_api::repo::monitor_pipeline::upsert( &db, monitor.id, diff --git a/tests/token_revocation.rs b/tests/token_revocation.rs index 7c8708d8..97190c92 100644 --- a/tests/token_revocation.rs +++ b/tests/token_revocation.rs @@ -23,7 +23,7 @@ async fn revoked_token_is_rejected_on_protected_routes() { let token = token_for(REVOKED_UID, UserPermissions::superuser()); state .revocations - .revoke(REVOKED_UID, chrono::Utc::now().timestamp() + 1); + .revoke(REVOKED_UID, zm_api::util::time::unix_now() + 1); let app = TestApp::from_state(state); let resp = app.get("/api/v3/monitors", &token).await; @@ -94,7 +94,7 @@ async fn revoked_token_is_rejected_on_every_documented_route() { let token = token_for(UID, UserPermissions::superuser()); state .revocations - .revoke(UID, chrono::Utc::now().timestamp() + 1); + .revoke(UID, zm_api::util::time::unix_now() + 1); let app = TestApp::from_state(state); let doc = serde_json::to_value(zm_api::routes::served_openapi()).expect("openapi as json");