Skip to content

refactor(time): move zm-api's own date and time code from chrono to jiff - #280

Merged
SteveGilvarry merged 2 commits into
masterfrom
refactor/chrono-to-jiff
Nov 18, 2026
Merged

SteveGilvarry merged 2 commits into
masterfrom
refactor/chrono-to-jiff

Conversation

@SteveGilvarry

Copy link
Copy Markdown
Member

Why

chrono's maintainer has wound the crate down and recommends jiff (RUSTSEC-2026-0543, chrono #1768). This moves the date and time code zm-api controls.

What changes

  • chrono is no longer a direct dependency. jiff replaces it in Cargo.toml, and async_zip and fake no longer enable their chrono features.
  • One boundary module. SeaORM's DateTime and DateTimeUtc are still chrono types. src/util/time.rs converts them as a value leaves an entity or enters a query, and no other file calls chrono's API. Since the crate can no longer be named, the compiler enforces most of that.
  • Repos take jiff values and bind SeaORM's types inside. A few functions that work on entity rows throughout, such as the media job store, keep SeaORM's type in their signatures.

What does not change

Date strings in API responses. jiff prints several values differently from chrono, so this keeps the old spellings and pins each with a unit test:

  • the +00:00 form on monitor status, server stats, event data, reports and pipelines
  • the 2026-10-23 21:30:15 UTC form of a frame's time_stamp
  • chrono's 3, 6 or 9 digit fractions, where jiff trims trailing zeros

DST handling in naive_local_to_utc is also the same: a repeated local time takes the earlier instant, and a skipped one is read as UTC digits.

Small side changes

  • Deleted src/util/datetime_format.rs. It was never compiled, because an inline module of the same name in util/mod.rs shadowed it.
  • The two event-count queries saturate on a huge hours_back where they used to panic.
  • One line in CLAUDE.md records the convention.

Worth a reviewer's eye

  • Input parsing is slightly more lenient. jiff accepts a few RFC 3339 variants chrono rejected, such as a space in place of the T.
  • One test changed meaning. parse_utc_handles_rfc3339_and_garbage asserted chrono's Display text. It now compares the parsed value.
  • The advisory still fires. SeaORM, sea-query, sqlx and rustls-acme keep chrono in the lockfile, so the ignore in deny.toml stays. Entities move when SeaORM releases jiff support that covers MySQL.

Checked locally

  • cargo fmt --all -- --check and cargo clippy --locked --all-targets --all-features -- -D warnings are clean
  • cargo test --all-features: 1393 passed, 0 failed
  • APP_PROFILE=test-db cargo test --test '*' -- --include-ignored against local MySQL: 535 passed, 0 failed
  • cargo deny check passes

The two full test runs were on the same source before I rebased onto current master. The rebase only brought in #279's Cargo.lock and deny.toml changes, and after it I re-ran fmt, clippy, cargo deny and the 1313 library tests.

🤖 Generated with Claude Code

chrono's maintainer has wound the crate down and recommends jiff
(RUSTSEC-2026-0543). This moves the code we control.

chrono is no longer a direct dependency, and async_zip and fake no longer
enable their chrono features. SeaORM, sqlx and rustls-acme still pull it
in, so the advisory ignore in deny.toml stays for now.

SeaORM's DateTime and DateTimeUtc are chrono types. src/util/time.rs is
the one module that converts them, as a value leaves an entity or enters
a query. Nothing else calls chrono's API.

Date strings in API responses are unchanged. jiff prints several values
differently from chrono, so the old spellings are kept and pinned by unit
tests: the "+00:00" form on monitor status, server stats, event data,
reports and pipelines, the "2026-10-23 21:30:15 UTC" form of a frame's
time_stamp, and chrono's 3, 6 or 9 digit fractions.

Also:
- delete src/util/datetime_format.rs, which was never compiled because an
  inline module of the same name shadowed it
- the two event-count queries saturate on a huge hours_back where they
  used to panic
- note the convention in CLAUDE.md

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved regressions miscalculate process start times across DST transitions, alter valid year-9999 database dates, and change fractional-second response strings contrary to the compatibility contract.

4 open issues
What changed in this PR

Migrates zm-api’s application-owned date and time code from chrono to jiff, while retaining SeaORM’s chrono-based database types behind a conversion module. Chrono remains a transitive dependency, so the existing advisory exception still applies.

Changes:

  • Replaces direct chrono usage across services, handlers, repositories, streaming, and tests.
  • Adds database-boundary conversions and compatibility formatters to preserve existing API date strings.
  • Removes unused formatting code, adds saturating event-count calculations, and documents the time-handling convention.
File Description
tests/​token_revocation.rs Uses the shared Unix clock helper.
tests/​it_zmnext_secrets.rs Uses jiff timestamps for pipeline fixtures.
tests/​it_synopsis.rs Migrates synopsis fixtures and time arithmetic.
tests/​it_retention.rs Migrates retention fixtures and database conversions.
tests/​it_real_users.rs Uses jiff for monitor-status timestamps.
tests/​it_monitor_status.rs Checks timestamp freshness with jiff.
tests/​it_media_links.rs Uses the shared clock for expired signatures.
tests/​it_logs.rs Uses the shared clock for log fixtures.
tests/​it_frame_images.rs Uses the database UTC clock helper.
tests/​it_events_list_filters.rs Migrates filter fixtures and timestamp assertions.
tests/​it_event_stream.rs Migrates event-stream fixture timestamps.
tests/​it_event_media.rs Migrates recorded-event time arithmetic.
tests/​it_event_filters.rs Uses the database UTC clock helper.
tests/​it_event_delete.rs Migrates event-deletion fixture timestamps.
tests/​handlers_monitors_events_frames_integration.rs Migrates event creation timestamps.
src/​util/​time.rs Adds clocks, database conversions, compatibility formatting, and tests.
src/​util/​mod.rs Migrates timezone conversion and civil-date serialization.
src/​util/​media_url.rs Migrates signed-URL issue and expiry clocks.
src/​util/​datetime_format.rs Deletes the uncompiled formatting module.
src/​util/​claim.rs Uses the shared clock for token claims.
src/​util/​assertion.rs Migrates timestamp comparison helpers and tests.
src/​streaming/​source/​worker_status.rs Uses jiff epoch milliseconds.
src/​streaming/​rtsp/​session.rs Migrates credential-expiry checks.
src/​streaming/​rtsp/​session_tests.rs Migrates test credential timestamps.
src/​streaming/​live/​whep.rs Migrates session-start timestamps.
src/​streaming/​live/​webrtc.rs Migrates session timestamps with compatibility serialization.
src/​service/​zmnext/​secrets.rs Migrates secret and pipeline update timestamps.
src/​service/​zmnext/​ingest.rs Migrates ingest timestamps, durations, and database bindings.
src/​service/​users.rs Migrates token-revocation clocks and tests.
src/​service/​token.rs Uses the shared token-issuance clock.
src/​service/​synopsis/​mod.rs Migrates synopsis windows, expiry, and serialization.
src/​service/​server.rs Uses jiff for local UTC offsets.
src/​service/​roles.rs Migrates role-change revocation clocks.
src/​service/​retention/​mod.rs Migrates age cutoffs and retention fixtures.
src/​service/​notifications.rs Converts notification dates at database boundaries.
src/​service/​monitor.rs Migrates audio-level request expiry.
src/​service/​monitor_pipeline.rs Migrates pipeline update timestamps.
src/​service/​media_jobs.rs Uses the database UTC clock helper.
src/​service/​media_job_store.rs Migrates stored-job millisecond conversions.
src/​service/​media_grant.rs Migrates media-grant expiry calculations.
src/​service/​maintenance/​telemetry.rs Migrates telemetry clocks and timestamp formatting.
src/​service/​maintenance/​stats.rs Migrates session-pruning cutoff clocks.
src/​service/​maintenance/​audit/​mod.rs Migrates quarantine clocks and batch names.
src/​service/​maintenance/​audit/​filesystem.rs Migrates quarantine parsing and retention arithmetic.
src/​service/​filter_build.rs Parses filter timestamps with jiff.
src/​service/​events.rs Migrates event timestamps and database conversions.
src/​service/​event_stream.rs Uses boundary conversions for streamed event dates.
src/​service/​event_storage.rs Converts database dates before building storage paths.
src/​service/​event_export.rs Builds ZIP timestamps without chrono integration.
src/​service/​event_audit.rs Migrates audit windows, gaps, and formatting.
src/​service/​daemon.rs Supplies jiff local time to status parsing.
src/​service/​auth.rs Migrates authentication and revocation clocks.
src/​repo/​zmnext_secret.rs Converts jiff timestamps when binding secret updates.
src/​repo/​snapshots.rs Converts snapshot dates for database writes.
src/​repo/​server_stats.rs Uses jiff for server-stat timestamps.
src/​repo/​reports.rs Centralizes report-date parsing with jiff.
src/​repo/​monitor_pipeline.rs Converts pipeline timestamps at the database boundary.
src/​repo/​frames.rs Parses frame timestamps with jiff.
src/​repo/​events.rs Migrates hourly dates and saturates lookback arithmetic.
src/​repo/​events_tags.rs Uses jiff for tag-assignment timestamps.
src/​repo/​event_synopsis.rs Converts jiff query bounds for SeaORM.
src/​repo/​event_data.rs Parses event-data timestamps with jiff.
src/​onvif/​security.rs Migrates security timestamp generation and tests.
src/​migration/​stamp.rs Uses the shared migration-stamping clock.
src/​handlers/​synopsis.rs Converts epoch query bounds to jiff civil dates.
src/​handlers/​media_links.rs Migrates media-link expiry clocks.
src/​handlers/​live.rs Migrates viewer timestamps and revocation tests.
src/​handlers/​events.rs Removes an obsolete commented-out chrono import.
src/​handlers/​event_stream.rs Migrates token-expiry timeout calculation.
src/​handlers/​event_export.rs Formats export filenames with jiff local time.
src/​dto/​wrappers.rs Migrates date wrappers while preserving serialization formats.
src/​dto/​response/​tags.rs Changes tag dates to jiff timestamps.
src/​dto/​response/​snapshots.rs Converts snapshot dates to jiff civil values.
src/​dto/​response/​server_stats.rs Uses numeric-offset compatibility formatting.
src/​dto/​response/​reports.rs Centralizes compatible report-date formatting.
src/​dto/​response/​notifications.rs Uses database-boundary date conversions.
src/​dto/​response/​monitor_status.rs Preserves numeric-offset output and tests its spelling.
src/​dto/​response/​monitor_pipeline.rs Preserves pipeline timestamp formatting.
src/​dto/​response/​media_jobs.rs Converts database dates to wrapped jiff timestamps.
src/​dto/​response/​frames.rs Preserves the legacy frame timestamp spelling.
src/​dto/​response/​events.rs Uses the new database-to-UTC conversion.
src/​dto/​response/​events_tags.rs Migrates tag dates and event date conversions.
src/​dto/​response/​event_data.rs Preserves numeric-offset timestamp formatting.
src/​dto/​request/​tags.rs Accepts tag dates as jiff timestamps.
src/​dto/​request/​snapshots.rs Accepts snapshot dates as jiff civil values.
src/​dto/​request/​notifications.rs Migrates notification timestamp request fields.
src/​daemon/​zmdc_client.rs Migrates status-date parsing and uptime arithmetic.
src/​daemon/​onvif_event_listener.rs Migrates event timestamps, durations, and parsing tests.
src/​daemon/​ipc/​socket.rs Migrates legacy daemon-status time formatting.
CLAUDE.md Documents jiff usage and the database boundary.
Cargo.toml Adds jiff and removes direct chrono integrations.
Cargo.lock Updates dependency edges for the migration.

Review effort: Balanced

Comment thread src/daemon/ipc/socket.rs Outdated
ProcessState::Running | ProcessState::Starting => {
let since = now - chrono::Duration::seconds(d.uptime_seconds.unwrap_or(0) as i64);
let uptime = jiff::SignedDuration::from_secs(d.uptime_seconds.unwrap_or(0) as i64);
let since = now.saturating_sub(uptime);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6162680. This was a regression: the chrono code subtracted from an instant and mine subtracted from wall-clock time. started_at now subtracts the uptime from the instant and converts the result to local time. A test covers 03:30 in New York after the spring-forward change with a two-hour uptime, which gives 00:30.

pub created_by: Option<i32>,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00")]
pub created_on: Option<NaiveDateTime>,
pub created_on: Option<Civil>,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6162680. created_on on the snapshot response and both snapshot requests now uses datetime_format::optional, so a fraction keeps chrono's width. A test checks .500, a whole second, and that a body without the field still parses.

Comment thread src/dto/response/tags.rs
pub name: String,
#[schema(value_type = Option<String>, example = "2025-01-15T10:30:00Z")]
pub create_date: Option<DateTimeUtc>,
pub create_date: Option<Timestamp>,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6162680. create_date and assigned_date in tags.rs and events_tags.rs, plus the tag request DTOs, now serialize through rfc3339_z. A test checks .500Z and the null case.

Comment thread src/util/time.rs
Comment on lines +53 to +67
pub fn civil(column: DbDateTime) -> Civil {
utc_civil(instant(column.and_utc()))
}

/// 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 {
db_instant(civil_utc(c)).naive_utc()
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6162680. civil and db_datetime now convert the digits by civil arithmetic from the epoch and no longer go through Timestamp. A test round-trips 9999-12-31T12:00:00, 9999-12-31T23:59:59.999999, 1000-01-01T00:00:00 and a value just before the epoch.

Four findings from review of #280, each with a test.

- A daemon's start time in the legacy status text was an hour off for up
  to a day after a DST change. The uptime is now subtracted from the
  instant, then converted to local time, as the chrono code did.
- A DATETIME value on 9999-12-31 moved by a day on read and on write,
  because the conversion went through jiff's Timestamp, whose range ends
  earlier. The digits now convert by civil arithmetic from the epoch.
- Snapshot created_on, and tag create_date and assigned_date, printed a
  fraction as ".5" where chrono printed ".500". They now use the same
  serializers as the other date fields.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@SteveGilvarry
SteveGilvarry merged commit 9c52577 into master Nov 18, 2026
21 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 18, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants