Cotton code
202 lines · 6.3 KB · RustRaw
//! The three things this crate may not read for itself: the clock, a random//! source, and where an op id comes from.//!//! The store crate holds none of them at all (spec R7) and the server injects//! its own (`cotton_server::clock`, `::random`); the client does the same, for//! the same reason and with the same shapes. A sync loop's backoff, a `_media`//! row's `next_attempt_at` and a call's `updated_at` are all stamps a suite has//! to be able to name, and a `Utc::now()` inside the library is a test that can//! only assert a range.//!//! They are DECLARED here rather than taken from `cotton-server` because a//! client is not a server: this crate depends on the store and the domain, and//! on nothing that binds a port.use std::sync::{Arc, Mutex};use chrono::{DateTime, Utc};use cotton_store::protocol::ulid::Monotonic;/// What time it is, as far as this client is concerned.pub trait Clock: Send + Sync + std::fmt::Debug {    fn now(&self) -> DateTime<Utc>;    /// The instant as the ISO-8601 UTC string every stamped column holds.    fn now_iso(&self) -> String {        iso(self.now())    }}/// The wall clock. The one implementation a running app uses.#[derive(Debug, Clone, Copy, Default)]pub struct SystemClock;impl Clock for SystemClock {    fn now(&self) -> DateTime<Utc> {        Utc::now()    }}/// A clock a test sets and moves.#[derive(Debug, Clone)]pub struct FixedClock {    at: Arc<Mutex<DateTime<Utc>>>,}impl FixedClock {    pub fn new(at: DateTime<Utc>) -> FixedClock {        FixedClock {            at: Arc::new(Mutex::new(at)),        }    }    /// The instant most suites start from — the server's own `default_start`,    /// so a stamp compared across the two crates agrees.    pub fn default_start() -> FixedClock {        FixedClock::new(            DateTime::parse_from_rfc3339("2026-09-08T10:00:00Z")                .expect("a literal instant")                .with_timezone(&Utc),        )    }    pub fn set(&self, at: DateTime<Utc>) {        *self.at.lock().unwrap_or_else(|error| error.into_inner()) = at;    }    pub fn advance(&self, by: chrono::Duration) {        let mut at = self.at.lock().unwrap_or_else(|error| error.into_inner());        *at += by;    }}impl Clock for FixedClock {    fn now(&self) -> DateTime<Utc> {        *self.at.lock().unwrap_or_else(|error| error.into_inner())    }}/// The ISO-8601 UTC spelling every column in the file holds — the same three/// decimals and trailing `Z` JavaScript's `toISOString` writes, because a/// string comparison is what orders these rows.pub fn iso(at: DateTime<Utc>) -> String {    at.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()}/// Fill a buffer with unpredictable bytes.pub trait Random: Send + Sync + std::fmt::Debug {    fn fill(&self, out: &mut [u8]);}/// The operating system's generator — what a real app runs on.#[derive(Debug, Default, Clone, Copy)]pub struct SystemRandom;impl Random for SystemRandom {    fn fill(&self, out: &mut [u8]) {        use rand::RngCore;        rand::rngs::OsRng.fill_bytes(out);    }}/// A generator a test can predict. Never reached by a running app.#[derive(Debug, Clone)]pub struct SeededRandom {    next: Arc<Mutex<u64>>,}impl SeededRandom {    pub fn new(seed: u64) -> SeededRandom {        SeededRandom {            next: Arc::new(Mutex::new(seed | 1)),        }    }}impl Default for SeededRandom {    fn default() -> Self {        SeededRandom::new(0x2026_0908)    }}impl Random for SeededRandom {    fn fill(&self, out: &mut [u8]) {        // xorshift64*. Not cryptography, and it is never asked to be: the one        // caller is a suite that wants the SAME op ids on the next run.        let mut state = self.next.lock().unwrap_or_else(|error| error.into_inner());        for byte in out.iter_mut() {            *state ^= *state << 13;            *state ^= *state >> 7;            *state ^= *state << 17;            *byte = (*state >> 24) as u8;        }    }}/// A v4 UUID from this source — the id a minted row carries.pub fn uuid_v4(random: &dyn Random) -> String {    let mut bytes = [0u8; 16];    random.fill(&mut bytes);    bytes[6] = (bytes[6] & 0x0f) | 0x40;    bytes[8] = (bytes[8] & 0x3f) | 0x80;    cotton_store::protocol::uuid::format_uuid_v4(&bytes)}/// Where op ids come from, bound to this client's clock and random source.////// `Monotonic` is the store's own ULID generator: two ops minted in the same/// millisecond still sort in the order they were written, which is what makes/// `ORDER BY op_id` the outbox's queue order.pub fn op_ids(random: Arc<dyn Random>) -> Monotonic<impl FnMut(&mut [u8])> {    Monotonic::new(move |out: &mut [u8]| random.fill(out))}#[cfg(test)]mod tests {    use super::*;    #[test]    fn the_iso_spelling_is_the_one_the_file_holds() {        let clock = FixedClock::default_start();        assert_eq!(clock.now_iso(), "2026-09-08T10:00:00.000Z");    }    #[test]    fn a_fixed_clock_moves_only_when_a_test_moves_it() {        let clock = FixedClock::default_start();        assert_eq!(clock.now_iso(), clock.now_iso());        clock.advance(chrono::Duration::seconds(90));        assert_eq!(clock.now_iso(), "2026-09-08T10:01:30.000Z");    }    #[test]    fn a_seeded_source_answers_the_same_bytes_twice_and_a_uuid_says_it_is_a_v4() {        let a = uuid_v4(&SeededRandom::new(7));        let b = uuid_v4(&SeededRandom::new(7));        assert_eq!(a, b);        assert_eq!(a.len(), 36);        assert_eq!(a.as_bytes()[14], b'4');    }    #[test]    fn op_ids_climb_within_one_millisecond_so_the_outbox_keeps_its_order() {        let mut ids = op_ids(Arc::new(SeededRandom::default()));        let first = ids.next(1_760_000_000_000).expect("an id");        let second = ids.next(1_760_000_000_000).expect("an id");        assert!(second > first, "{second} should sort after {first}");    }}/// How loud a line of the Mac's own log is.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]#[serde(rename_all = "lowercase")]pub enum LogLevel {    Info,    Warn,    Error,}/// Where a line of the Mac's own log goes: the two-variant logger the CI/// runner and the backup write through, so a person reading the Activity page/// sees every helper's lines in one place and one shape.pub type Log = Arc<dyn Fn(&str, LogLevel) + Send + Sync>;