scryer-db 0.2.1

Database models and Turso/SQLite storage layer for Scryer code intelligence
//! UTC timestamps stored as RFC 3339 strings, e.g. `2026-10-06T21:04:20.123Z`.
//!
//! The fixed width keeps lexicographic order equal to chronological order.

use std::time::{SystemTime, UNIX_EPOCH};

/// The current time as an RFC 3339 UTC string with millisecond precision.
pub fn now_rfc3339() -> String {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64;
    format_unix_millis(millis)
}

/// Format milliseconds since the Unix epoch as an RFC 3339 UTC string.
pub fn format_unix_millis(millis: u64) -> String {
    let secs = millis / 1000;
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let (year, month, day) = civil_from_days(days);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
        rem / 3600,
        rem % 3600 / 60,
        rem % 60,
        millis % 1000
    )
}

/// Parse the legacy `"<secs>.<millis>Z"` format written by earlier versions.
pub(crate) fn parse_legacy(value: &str) -> Option<u64> {
    let (secs, millis) = value.strip_suffix('Z')?.split_once('.')?;
    if millis.len() != 3 {
        return None;
    }
    Some(secs.parse::<u64>().ok()? * 1000 + millis.parse::<u64>().ok()?)
}

/// Convert days since 1970-01-01 to a proleptic Gregorian `(year, month, day)`.
///
/// Howard Hinnant's `civil_from_days` algorithm.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    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 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
    let year = yoe + era * 400 + i64::from(month <= 2);
    (year, month, day)
}

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

    #[test]
    fn formats_known_instants() {
        assert_eq!(format_unix_millis(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(
            format_unix_millis(951_782_400_000),
            "2000-02-29T00:00:00.000Z"
        );
        assert_eq!(
            format_unix_millis(1_791_334_794_678),
            "2026-10-07T00:59:54.678Z"
        );
    }

    #[test]
    fn parses_only_the_legacy_format() {
        assert_eq!(parse_legacy("1791334794.678Z"), Some(1_791_334_794_678));
        assert_eq!(parse_legacy("2026-10-06T00:00:00Z"), None);
        assert_eq!(parse_legacy("2026-10-06T00:00:00.000Z"), None);
    }
}