Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
32 changes: 29 additions & 3 deletions src/daemon/ipc/socket.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -335,20 +336,31 @@ async fn execute_command(cmd: DaemonCommand, manager: &Arc<DaemonManager>) -> 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
/// `'<command>' 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)
)
}
Expand All @@ -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;

Expand Down
26 changes: 14 additions & 12 deletions src/daemon/onvif_event_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64, crate::error::AppError> {
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()
};
Expand All @@ -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(())
Expand Down Expand Up @@ -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<chrono::NaiveDateTime> {
fn parse_utc(s: Option<&str>) -> Option<jiff::civil::DateTime> {
let s = s?;
chrono::DateTime::parse_from_rfc3339(s)
s.parse::<jiff::Timestamp>()
.ok()
.map(|dt| dt.naive_utc())
.map(crate::util::time::utc_civil)
}

#[cfg(test)]
Expand Down Expand Up @@ -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);
Expand Down
12 changes: 6 additions & 6 deletions src/daemon/zmdc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProcessStatus> {
pub fn parse_status(reply: &str, now: jiff::civil::DateTime) -> Vec<ProcessStatus> {
reply
.lines()
.filter_map(|line| parse_line(line, now))
.collect()
}

fn parse_line(line: &str, now: chrono::NaiveDateTime) -> Option<ProcessStatus> {
fn parse_line(line: &str, now: jiff::civil::DateTime) -> Option<ProcessStatus> {
let rest = line.trim().strip_prefix('\'')?;
let (command, rest) = rest.split_once('\'')?;
let rest = rest.trim_start();
Expand All @@ -63,9 +63,9 @@ fn parse_line(line: &str, now: chrono::NaiveDateTime) -> Option<ProcessStatus> {
.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)
Expand Down Expand Up @@ -105,8 +105,8 @@ fn monitor_id(command: &str) -> Option<u32> {
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]
Expand Down
6 changes: 3 additions & 3 deletions src/dto/request/notifications.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -104,7 +104,7 @@ pub struct CreateNotificationRequest {
/// RFC 3339.
#[schema(value_type = Option<String>, format = DateTime)]
#[garde(skip)]
pub last_notified_at: Option<DateTime<Utc>>,
pub last_notified_at: Option<Timestamp>,
/// The owner. Only a System editor may set it; otherwise it is the caller.
#[garde(skip)]
pub user_id: Option<u32>,
Expand Down Expand Up @@ -138,7 +138,7 @@ pub struct UpdateNotificationRequest {
#[serde(default, deserialize_with = "crate::dto::serde_helpers::double_option")]
#[schema(value_type = Option<String>, format = DateTime)]
#[garde(skip)]
pub last_notified_at: Option<Option<DateTime<Utc>>>,
pub last_notified_at: Option<Option<Timestamp>>,
/// System editors only.
#[garde(skip)]
pub user_id: Option<u32>,
Expand Down
8 changes: 5 additions & 3 deletions src/dto/request/snapshots.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use chrono::NaiveDateTime;
use garde::Validate;
use jiff::civil::DateTime as Civil;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

Expand All @@ -13,7 +13,8 @@ pub struct CreateSnapshotRequest {
pub created_by: Option<i32>,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00")]
#[garde(skip)]
pub created_on: Option<NaiveDateTime>,
#[serde(default, with = "crate::util::datetime_format::optional")]
pub created_on: Option<Civil>,
}

#[derive(Debug, Clone, Deserialize, Serialize, ToSchema, Validate)]
Expand All @@ -26,5 +27,6 @@ pub struct UpdateSnapshotRequest {
pub created_by: Option<i32>,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00")]
#[garde(skip)]
pub created_on: Option<NaiveDateTime>,
#[serde(default, with = "crate::util::datetime_format::optional")]
pub created_on: Option<Civil>,
}
8 changes: 5 additions & 3 deletions src/dto/request/tags.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use garde::Validate;
use sea_orm::prelude::DateTimeUtc;
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};

Expand All @@ -9,7 +9,8 @@ pub struct CreateTagRequest {
pub name: String,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00Z")]
#[garde(skip)]
pub create_date: Option<DateTimeUtc>,
#[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")]
pub create_date: Option<Timestamp>,
}

#[derive(Debug, Clone, Deserialize, Serialize, ToSchema, Validate)]
Expand All @@ -18,7 +19,8 @@ pub struct UpdateTagRequest {
pub name: Option<String>,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00Z")]
#[garde(skip)]
pub create_date: Option<DateTimeUtc>,
#[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")]
pub create_date: Option<Timestamp>,
}

/// Query params for tag detail with paginated events
Expand Down
2 changes: 1 addition & 1 deletion src/dto/response/event_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/dto/response/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ impl From<EventModel> 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,
Expand Down
10 changes: 6 additions & 4 deletions src/dto/response/events_tags.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use sea_orm::prelude::DateTimeUtc;
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

Expand All @@ -15,7 +15,8 @@ pub struct EventTagResponse {
#[schema(example = 1)]
pub event_id: u64,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00Z")]
pub assigned_date: Option<DateTimeUtc>,
#[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")]
pub assigned_date: Option<Timestamp>,
#[schema(example = 1)]
pub assigned_by: Option<u32>,
}
Expand Down Expand Up @@ -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,
Expand All @@ -109,7 +110,8 @@ pub struct TagDetailResponse {
#[schema(example = "Important")]
pub name: String,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00Z")]
pub create_date: Option<DateTimeUtc>,
#[serde(serialize_with = "crate::util::time::serialize_option_rfc3339_z")]
pub create_date: Option<Timestamp>,
pub events: Vec<EventSummary>,
#[schema(example = 100)]
pub total_events: u64,
Expand Down
4 changes: 3 additions & 1 deletion src/dto/response/frames.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions src/dto/response/media_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ pub struct MediaJobResponse {
pub finished_at: Option<DateTimeWrapper>,
}

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 {
Expand Down
Loading
Loading