modem-mgmt 0.2.0

The management plane of zenoh-modem as a library: serve every device on a host over Zenoh, for any driver that links the contract
Documentation
//! What the plane knows about time, in one place.
//!
//! Three facts travel beside every wall-clock timestamp this producer
//! publishes (#121): seconds since the driver started, one id per start, and
//! whether the wall clock is believed synchronised. A field unit may have no
//! RTC, and `now_ms` answers 0 for any time before 1970 rather than guessing —
//! so a reader orders this node's events by `uptime_s` within a `boot_id`,
//! and trusts `at_ms` only when `clock_synced` says it may.

use std::sync::atomic::{AtomicU64, Ordering};

/// Milliseconds since the Unix epoch, or 0 if the clock is before it.
pub(crate) fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_millis() as u64)
}

/// Whether the kernel believes the wall clock is synchronised.
///
/// `adjtimex(2)` with no modes set is a read, and returns `TIME_ERROR` while
/// the clock is unsynchronised — which is what NTP, chrony and `systemd-
/// timesyncd` all leave it saying until they have a source. Not a claim of
/// accuracy, and not a network round trip: the one bit the kernel already
/// holds.
#[cfg(target_os = "linux")]
pub(crate) fn clock_synced() -> bool {
    // SAFETY: `timex` is plain data and a zeroed one has `modes == 0`, which
    // asks the kernel to read the clock state and change nothing; the
    // pointer is to a live local.
    let mut t: libc::timex = unsafe { std::mem::zeroed() };
    let state = unsafe { libc::adjtimex(&mut t) };
    state >= 0 && state != libc::TIME_ERROR
}

/// Whether the wall clock is believed synchronised: not on this platform.
#[cfg(not(target_os = "linux"))]
pub(crate) fn clock_synced() -> bool {
    false
}

/// A ULID, minted here rather than by a dependency.
///
/// RFC 04 §1.3 keys an event by one, and zenkey ships no minter — only an
/// example of the shape. Thirty lines against pulling `ulid` and `rand` into a
/// driver whose data path is deliberately dependency-light, and the properties
/// that matter are cheap: 48 bits of millisecond timestamp so ids sort by time,
/// then 80 bits that are monotonic within a millisecond so two events in the
/// same tick cannot collide. Crockford base32, lowercase, 26 characters.
///
/// Deliberately **not** random. A per-process counter is what makes collisions
/// impossible rather than unlikely for a single producer, and a single producer
/// is all this keyspace has: the origin chunk already separates hosts.
pub(crate) fn ulid(counter: &AtomicU64) -> String {
    const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
    let ms = now_ms() & ((1 << 48) - 1);
    let seq = counter.fetch_add(1, Ordering::Relaxed);
    // 128 bits: 48 of timestamp, 80 of sequence. The sequence wraps at 2^80,
    // which no process reaches.
    let value = (u128::from(ms) << 80) | u128::from(seq);
    let mut out = [b'0'; 26];
    // 26 base32 digits carry 130 bits; the top digit therefore holds only the
    // two high bits, which is the standard ULID layout.
    for (i, slot) in out.iter_mut().enumerate() {
        let shift = 125 - 5 * i;
        *slot = ALPHABET[((value >> shift) & 0x1f) as usize];
    }
    String::from_utf8(out.to_vec()).expect("base32 is ascii")
}

/// One id per driver start (#121): the `boot_id` every status document
/// carries, so two events a second apart on either side of a restart are
/// told apart. A ULID, because the shape is already here and it sorts.
pub(crate) fn boot_id() -> String {
    ulid(&AtomicU64::new(0))
}

/// Milliseconds since the Unix epoch as RFC 3339 UTC with milliseconds —
/// `2026-09-27T20:14:05.123Z` — for the deadlines a document carries (#127).
/// Written out rather than pulled in: the plane has no other use for a
/// calendar, and the civil-from-days arithmetic is twelve lines.
pub(crate) fn rfc3339(ms: u64) -> String {
    let secs = ms / 1000;
    let millis = ms % 1000;
    let days = i64::try_from(secs / 86_400).unwrap_or(i64::MAX);
    let sod = secs % 86_400;
    // Howard Hinnant's civil_from_days.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{millis:03}Z",
        sod / 3600,
        (sod % 3600) / 60,
        sod % 60
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_calendar_arithmetic_is_right_on_known_instants() {
        assert_eq!(rfc3339(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(rfc3339(1_700_000_000_000), "2023-11-14T22:13:20.000Z");
        assert_eq!(rfc3339(951_782_400_000), "2000-02-29T00:00:00.000Z");
        assert_eq!(rfc3339(1_790_543_149_204), "2026-09-27T21:05:49.204Z");
    }

    #[test]
    fn an_id_is_twenty_six_crockford_characters() {
        let c = AtomicU64::new(0);
        let id = ulid(&c);
        assert_eq!(id.len(), 26, "a ULID is 26 characters");
        assert!(
            id.bytes()
                .all(|b| b"0123456789abcdefghjkmnpqrstvwxyz".contains(&b)),
            "Crockford base32 excludes i, l, o and u: {id}"
        );
    }

    #[test]
    fn ids_are_distinct_and_ordered_within_a_millisecond() {
        let c = AtomicU64::new(0);
        let ids: Vec<String> = (0..1000).map(|_| ulid(&c)).collect();
        let mut sorted = ids.clone();
        sorted.sort();
        assert_eq!(ids, sorted, "ids minted in order must sort in order");
        sorted.dedup();
        assert_eq!(sorted.len(), 1000, "no two ids collide");
    }

    #[test]
    fn the_clock_question_has_an_answer() {
        // Whatever the answer is on this machine, asking must not fail or
        // block: it is called on every status refresh.
        let _ = clock_synced();
    }
}