Cotton code
306 lines · 11.4 KB · RustRaw
//! Judge time, as the shell holds it: the relay's `HELLO.server_time` read at//! each greeting against the continuous clock, in memory only (slice 1).//!//! The rules for which readings are taken are pure and live in//! [`cotton_store::judge`]; this module reads the two things that crate never//! reads — the continuous clock and the boot session — and holds the running//! [`Judge`] for the process.//!//! The continuous clock counts sleep and no NTP step moves it: on Apple//! `CLOCK_MONOTONIC_RAW` (which is `mach_continuous_time`), on Linux and//! Android `CLOCK_BOOTTIME` (Linux's `CLOCK_MONOTONIC_RAW` stops in suspend). Never//! `std::time::Instant`, which stops while the machine sleeps on macOS. The//! boot session is `kern.bootsessionuuid`, never `kern.boottime`, which moves//! when the wall clock is set; on Linux it is `/proc/sys/kernel/random/boot_id`,//! and on Android too (an app may read it: Books on Android, 5 Nov 2026 —//! `target_os` there is "android", never "linux", so every write was refused).//! On iOS — device and simulator alike — the sandbox refuses that sysctl, so//! the boot session is an id the app mints and keeps ([`minted_boot`]).#[path = "judge_minted_boot.rs"]pub mod minted_boot;use std::sync::{Arc, Mutex};use chrono::DateTime;use cotton_store::judge::{clock_state, ClockState, Judge, Offered, Reading};/// The continuous clock and the boot it counts in. A trait so a test supplies/// both.pub trait Continuous: Send + Sync {    /// Milliseconds on the continuous clock.    fn now_ms(&self) -> Result<i64, String>;    /// The boot session id. Unreadable is an error, never a made-up id.    fn boot(&self) -> Result<String, String>;}/// The running machine's continuous clock and boot session.pub struct SystemContinuous;impl Continuous for SystemContinuous {    fn now_ms(&self) -> Result<i64, String> {        continuous_ms()    }    fn boot(&self) -> Result<String, String> {        boot_session()    }}#[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))]fn continuous_ms() -> Result<i64, String> {    #[cfg(target_vendor = "apple")]    const CONTINUOUS: libc::clockid_t = libc::CLOCK_MONOTONIC_RAW;    #[cfg(any(target_os = "linux", target_os = "android"))]    const CONTINUOUS: libc::clockid_t = libc::CLOCK_BOOTTIME;    let mut spec = libc::timespec {        tv_sec: 0,        tv_nsec: 0,    };    // SAFETY: `spec` is a valid, writable timespec for the call's duration.    if unsafe { libc::clock_gettime(CONTINUOUS, &mut spec) } != 0 {        return Err(format!(            "the continuous clock is unreadable: {}",            std::io::Error::last_os_error()        ));    }    // `time_t` and `c_long` are i64 on every 64-bit target this builds for,    // but not by definition; the conversion is the type-checked spelling.    #[allow(clippy::useless_conversion)]    Ok(i64::from(spec.tv_sec) * 1_000 + i64::from(spec.tv_nsec) / 1_000_000)}#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android")))]fn continuous_ms() -> Result<i64, String> {    Err("this platform has no continuous clock CottonDB reads".to_string())}/// The data folder a minted boot session is kept in.static BOOT_FOLDER: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();/// Name the app's data folder, where iOS keeps the boot session it mints/// ([`minted_boot`]). The shell calls this before its judge clock is read;/// the first folder named is the one kept to. Platforms that read the/// kernel's own boot session never look at it.pub fn keep_boot_session_in(folder: &std::path::Path) {    let _ = BOOT_FOLDER.set(folder.to_path_buf());}/// The boot session id: one the app minted and keeps in its data folder,/// because the iOS sandbox refuses `kern.bootsessionuuid` on a real device/// (the simulator takes this path too, so it exercises what the phone runs).#[cfg(target_os = "ios")]pub fn boot_session() -> Result<String, String> {    kept_boot_session()}/// The minted boot session of this process ([`minted_boot`]), kept in the/// folder [`keep_boot_session_in`] named. Read once per process: a process/// never outlives its boot, so the id it found holds however the wall clock/// is set afterwards. Compiled on every platform so the path iOS runs is/// type-checked and tested wherever the crate builds.pub fn kept_boot_session() -> Result<String, String> {    static SESSION: Mutex<Option<String>> = Mutex::new(None);    let mut session = SESSION        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner());    if let Some(id) = session.as_ref() {        return Ok(id.clone());    }    let folder = BOOT_FOLDER.get().ok_or_else(|| {        "the boot session has no data folder to be kept in (keep_boot_session_in was not called)"            .to_string()    })?;    let since_1970 = std::time::SystemTime::now()        .duration_since(std::time::UNIX_EPOCH)        .map_err(|error| format!("the wall clock is before 1970: {error}"))?;    let wall_ms = i64::try_from(since_1970.as_millis())        .map_err(|error| format!("the wall clock is unreadable: {error}"))?;    let id = minted_boot::session(        &folder.join(minted_boot::FILE),        continuous_ms()?,        wall_ms,        minted_boot::fresh_id,    )?;    *session = Some(id.clone());    Ok(id)}/// The boot session id: `kern.bootsessionuuid` through `sysctlbyname`.#[cfg(all(target_vendor = "apple", not(target_os = "ios")))]pub fn boot_session() -> Result<String, String> {    let name = c"kern.bootsessionuuid";    let mut buffer = [0u8; 64];    let mut length = buffer.len();    // SAFETY: `name` is NUL-terminated; `buffer` and `length` describe a    // writable region the call fills no further than `length`.    let status = unsafe {        libc::sysctlbyname(            name.as_ptr(),            buffer.as_mut_ptr().cast(),            &mut length,            std::ptr::null_mut(),            0,        )    };    if status != 0 {        return Err(format!(            "kern.bootsessionuuid is unreadable: {}",            std::io::Error::last_os_error()        ));    }    let bytes = &buffer[..length.min(buffer.len())];    let id = String::from_utf8_lossy(bytes)        .trim_end_matches('\0')        .trim()        .to_string();    if id.is_empty() {        return Err("kern.bootsessionuuid is empty".to_string());    }    Ok(id)}/// The boot session id: the kernel's `boot_id`.#[cfg(any(target_os = "linux", target_os = "android"))]pub fn boot_session() -> Result<String, String> {    let id = std::fs::read_to_string(LINUX_BOOT_ID)        .map_err(|error| format!("{LINUX_BOOT_ID} is unreadable: {error}"))?        .trim()        .to_string();    if id.is_empty() {        return Err(format!("{LINUX_BOOT_ID} is empty"));    }    Ok(id)}#[cfg(any(target_os = "linux", target_os = "android"))]pub const LINUX_BOOT_ID: &str = "/proc/sys/kernel/random/boot_id";#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android")))]pub fn boot_session() -> Result<String, String> {    Err("this platform has no boot session CottonDB reads".to_string())}/// The process's judge time: one [`Judge`] behind a lock, fed by the line.pub struct JudgeClock {    continuous: Arc<dyn Continuous>,    judge: Mutex<Judge>,}impl std::fmt::Debug for JudgeClock {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("JudgeClock")            .field("judge", &self.lock())            .finish()    }}impl JudgeClock {    pub fn new(continuous: Arc<dyn Continuous>) -> JudgeClock {        JudgeClock {            continuous,            judge: Mutex::new(Judge::new()),        }    }    /// The running machine's clocks.    pub fn system() -> JudgeClock {        JudgeClock::new(Arc::new(SystemContinuous))    }    fn lock(&self) -> std::sync::MutexGuard<'_, Judge> {        self.judge            .lock()            .unwrap_or_else(|poisoned| poisoned.into_inner())    }    fn here(&self) -> Result<(i64, String), String> {        Ok((self.continuous.now_ms()?, self.continuous.boot()?))    }    /// Offer `HELLO.server_time` — or an exchange answer's, snapshot's or    /// `future` refusal's `serverTime` (ISO-8601) — as a reading; `wall_ms` is    /// this device's wall clock, read for the 1-hour rule only.    pub fn offer_server_time(&self, server_time: &str, wall_ms: i64) -> Result<Offered, String> {        let relay_ms = DateTime::parse_from_rfc3339(server_time)            .map_err(|error| format!("the relay's time {server_time:?} is unreadable: {error}"))?            .timestamp_millis();        let (cont_ms, boot) = self.here()?;        Ok(self.lock().offer(            Reading {                relay_ms,                cont_ms,                boot,            },            wall_ms,        ))    }    /// A live device's signed `ts` (ms): confirms an unconfirmed first    /// reading when they agree within 2 minutes.    pub fn confirm(&self, device_ts_ms: i64) -> Result<bool, String> {        let (cont_ms, boot) = self.here()?;        Ok(self.lock().confirm(device_ts_ms, cont_ms, &boot))    }    /// Judge time now. `None` when there is none this boot — or when the    /// continuous clock or boot session cannot be read, which is Unchecked,    /// never a guess.    pub fn now(&self) -> Option<i64> {        let (cont_ms, boot) = self.here().ok()?;        self.lock().now(cont_ms, &boot)    }    /// The four readings a mint takes, at wall clock `wall_ms`: judge time    /// if there is one this boot (`None` is Unchecked, and the mint holds).    /// An unreadable continuous clock or boot session is an error — a held    /// receipt is dated by them, so neither is ever made up.    pub fn mint_clock(&self, wall_ms: i64) -> Result<cotton_store::mint::Clock, String> {        let (cont_ms, boot) = self.here()?;        let judge = self.lock().now(cont_ms, &boot);        Ok(cotton_store::mint::Clock::judged(judge, wall_ms, cont_ms, boot))    }    /// The mint state of a wall clock reading `wall_ms` against judge time.    pub fn state(&self, wall_ms: i64) -> ClockState {        clock_state(self.now(), wall_ms)    }    /// The relay's time of the first reading waiting for a device to    /// confirm it — the other clock the Unchecked line names.    pub fn unconfirmed_relay_ms(&self) -> Option<i64> {        self.lock().unconfirmed().map(|reading| reading.relay_ms)    }    /// The reading is a day old: re-dial at a moment with no open stream.    pub fn needs_redial(&self) -> bool {        self.continuous            .now_ms()            .is_ok_and(|cont_ms| self.lock().needs_redial(cont_ms))    }}/// The serving Mac's file store, routes and chokepoint read judge time through/// this, so the one clock the relay line feeds is the one they judge by — and a/// replica's handle, whose server's answers feed the same process clock.impl cotton_store::judge::JudgeSource for JudgeClock {    fn now(&self) -> Option<i64> {        JudgeClock::now(self)    }    fn mint_clock(&self, wall_ms: i64) -> Result<cotton_store::mint::Clock, String> {        JudgeClock::mint_clock(self, wall_ms)    }    fn confirm(&self, device_ts_ms: i64) -> Result<bool, String> {        JudgeClock::confirm(self, device_ts_ms)    }    fn offer(&self, server_time: &str, wall_ms: i64) -> Result<Offered, String> {        JudgeClock::offer_server_time(self, server_time, wall_ms)    }}#[cfg(test)]#[path = "judge_tests.rs"]mod tests;