use std::time::{SystemTime, UNIX_EPOCH};
pub const SENTINEL_PREFIX: &str = "atproto-devtool conformance test";
pub fn build(run_id: &str, now: SystemTime) -> String {
let rfc3339 = format_rfc3339_utc(now);
format!("{SENTINEL_PREFIX} {rfc3339} {run_id}")
}
pub fn format_rfc3339_utc(ts: SystemTime) -> String {
let secs = ts
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let (year, month, day, hour, min, sec) = unix_to_civil(secs);
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z")
}
pub fn unix_to_civil(secs: i64) -> (i32, u32, u32, u32, u32, u32) {
let days = secs.div_euclid(86_400);
let sod = secs.rem_euclid(86_400);
let hour = (sod / 3600) as u32;
let min = ((sod % 3600) / 60) as u32;
let sec = (sod % 60) as u32;
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u32; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; let y = yoe as i32 + era as i32 * 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 year = if m <= 2 { y + 1 } else { y };
(year, m, d, hour, min, sec)
}
pub fn new_run_id() -> String {
let mut bytes = [0u8; 8];
getrandom::getrandom(&mut bytes).expect("OS CSPRNG is always available on supported platforms");
#[expect(clippy::format_collect)]
{
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_rfc3339_utc_pins_known_points() {
let before_epoch = UNIX_EPOCH.checked_sub(std::time::Duration::from_secs(1));
if let Some(t) = before_epoch {
assert_eq!(format_rfc3339_utc(t), "1970-01-01T00:00:00Z");
}
assert_eq!(format_rfc3339_utc(UNIX_EPOCH), "1970-01-01T00:00:00Z");
let t = UNIX_EPOCH + std::time::Duration::from_secs(1_709_164_800);
assert_eq!(format_rfc3339_utc(t), "2024-02-29T00:00:00Z");
let t = UNIX_EPOCH + std::time::Duration::from_secs(1_709_210_096);
assert_eq!(format_rfc3339_utc(t), "2024-02-29T12:34:56Z");
let t = UNIX_EPOCH + std::time::Duration::from_secs(951_782_400);
assert_eq!(format_rfc3339_utc(t), "2000-02-29T00:00:00Z");
let t = UNIX_EPOCH + std::time::Duration::from_secs(68_169_600);
assert_eq!(format_rfc3339_utc(t), "1972-02-29T00:00:00Z");
let t = UNIX_EPOCH + std::time::Duration::from_secs(253_402_300_799);
assert_eq!(format_rfc3339_utc(t), "9999-12-31T23:59:59Z");
}
#[test]
fn build_contains_prefix_and_run_id() {
let s = build("abcdef1234567890", UNIX_EPOCH);
assert!(s.starts_with(SENTINEL_PREFIX));
assert!(s.ends_with("abcdef1234567890"));
assert!(s.contains("1970-01-01T00:00:00Z"));
}
#[test]
fn new_run_id_is_16_hex_chars() {
let id = new_run_id();
assert_eq!(id.len(), 16);
assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn new_run_id_is_unique_between_calls() {
let a = new_run_id();
let b = new_run_id();
assert_ne!(a, b);
}
}