Cotton code
462 lines · 19.3 KB · RustRaw
//! What each held database looked like when it was last closed — enough to//! speak for it in an exchange WITHOUT opening it.//!//! One exchange a cycle carries a section for every database this device//! holds. Most of them, most of the time, have nothing to hand over: the//! section is the file's cursors and no ops. Opening a file — a writer, a//! reader, a page cache, a ladder check — to read a map that has not changed//! since the last pass is what "an idle database costs nothing" forbids, so//! the map is kept here, beside the connection record, and the file stays//! closed until the answer has something to fold into it.//!//! **AND WHETHER IT OWES THIS DEVICE BYTES.** The media drain's tick (the//! uploads, the thumbnail sweep, the keep-fetches) opens a database for one//! of two reasons: it holds bytes on this device (its media folder), or rows//! have come into it whose bytes have not ([`HeldNote::owes_bytes`]). A pass//! that folds rows into a file counts it ([`HeldNote::pulls`]); a tick that//! leaves the file wanting nothing says how far it caught up//! ([`HeldNotes::note_bytes_level`]). So a database whose pictures were all//! added on another device gets its thumbnails as soon as its rows arrive —//! before, its file had no media folder here, no tick ever opened it, and its//! tiles stayed grey until a tap fetched one original — while a database that//! owes nothing still stays closed.//!//! NEVER SYNCED, by construction: it is a file in the client folder, not a//! table in a replica. It is also never the truth — the replica's own//! `_cursors` and `_outbox` are. A note that is missing, stale or written by//! another build answers "open the file", which is always correct and only//! costs the open this exists to save.use std::collections::BTreeMap;use std::path::{Path, PathBuf};use std::sync::Mutex;use cotton_store::cursors::read_cursors;use cotton_store::driver::Driver;use cotton_store::migrate::SCHEMA_VERSION;use cotton_store::outbox::pending_count;use cotton_store::protocol::types::{ExchangeRequest, ExchangeResponse, EXCHANGE_PAGE_ROWS};use serde::{Deserialize, Serialize};use super::{write_durably, ConnectionFileError};/// One held database, as its last pass left it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct HeldNote {    /// How far this file has seen each author — its `_cursors`, whole.    pub cursors: BTreeMap<String, String>,    /// How far the PEER had seen each author when the last pass ended. An    /// answer whose `seen` differs — a peer restored from a backup, another    /// Mac serving — is one this file may owe a handover, so it is opened.    #[serde(default)]    pub seen: BTreeMap<String, String>,    /// How many ops wait in its outbox. Anything over zero means the file    /// has something to hand over and must be opened.    pub outbox: i64,    /// How many writes it holds for the Mac's time (`held = 1`). They are in    /// no outbox, and only a pass that opens the file releases them, so a    /// file holding any is never idle. `None` from a note written before this    /// was counted, which is "open the file".    #[serde(default)]    pub held: Option<i64>,    /// Did the last pass end with nothing more to ask and nothing more to    /// hand over? A pass cut short by a page limit or a failure leaves this    /// false, and the next cycle opens the file to finish.    pub caught_up: bool,    /// The schema of the build that wrote this note. A newer build opens the    /// file — its ladder has to run before anything speaks for it.    pub schema_version: u32,    /// The file's `_meta.handed_over_epoch` (slice 12), which the idle    /// section says for it: a server at an epoch it names neither folds    /// nothing and starts a hand-over, and the file is opened for it.    #[serde(deserialize_with = "nullable_epoch")]    pub handed_over_epoch: Option<i64>,    /// The author of the file's latest serving fact: the night of an owner's    /// Dev copy the file is (`ExchangeRequest::serving_author`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub serving_author: Option<String>,    /// How many passes have folded rows into this file. COUNTED, not    /// flagged, so the media tick can say which of them it caught up with: a    /// pass that lands while a sweep is running moves this past the mark the    /// sweep writes, and the file stays owing.    #[serde(default)]    pub pulls: u64,    /// The [`Self::pulls`] at which a media tick last left this file owing    /// this device nothing — every thumbnail, face, screenshot and kept    /// original its rows want is on this device. `None` is "never", which a    /// note written before this was counted says too: the drain opens the    /// file once and finds out.    #[serde(default)]    pub bytes_level_at: Option<u64>,}// Required in a note, and `null` is a value.fn nullable_epoch<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>where    D: serde::Deserializer<'de>,{    Option::<i64>::deserialize(deserializer)}impl HeldNote {    /// Can this note speak for its file — nothing queued, nothing unfinished,    /// written by this build?    pub fn idle(&self) -> bool {        self.outbox == 0            && self.held == Some(0)            && self.caught_up            && self.schema_version == SCHEMA_VERSION    }    /// Have rows come into this file since a media tick last found it owing    /// this device nothing? Then the drain opens it, though it holds no bytes    /// here yet.    pub fn owes_bytes(&self) -> bool {        self.bytes_level_at != Some(self.pulls)    }    /// Does this answer to the note's own section change nothing — no ops, no    /// more to ask, no cursor moved and the peer where it was? Only    /// then is the file left closed; anything else is folded into it.    pub fn unchanged_by(&self, answer: &ExchangeResponse) -> bool {        answer.ops.is_empty()            && !answer.has_more            && answer.rejected.is_empty()            // An answer's cursors are only what that page MOVED: none, or            // none past where the note already stands.            && answer                .cursors                .iter()                .all(|(author, at)| self.cursors.get(author) == Some(at))            && answer.seen == self.seen            // A copy of another night is answered with nothing else, and            // must reach the fold that says so.            && answer.copy_night.is_none()    }}#[derive(Debug, Default, Serialize, Deserialize)]struct HeldNotesFile {    #[serde(default)]    files: BTreeMap<String, HeldNote>,}/// The notes file, `held.json` beside `connection.json`.#[derive(Debug, Clone)]pub struct HeldNotes {    path: PathBuf,}/// One writer at a time in this process: every change is read-modify-write/// of one small file, and a write minting in one database must not lose the/// note a pass is writing for another.static WRITING: Mutex<()> = Mutex::new(());impl HeldNotes {    /// The notes beside the connection record at `connection_json`.    pub fn beside(connection_json: &Path) -> HeldNotes {        HeldNotes {            path: connection_json.with_file_name("held.json"),        }    }    pub fn path(&self) -> &Path {        &self.path    }    /// The note for one database, or `None` — which reads as "open the file".    ///    /// A missing or unreadable notes file is `None` for every database, never    /// an error: nothing here is owed to anyone, and the files themselves    /// hold everything it says.    pub fn read(&self, database: &str) -> Option<HeldNote> {        self.load().files.remove(database)    }    /// The section an idle database sends: its cursors and no ops. `None`    /// when the file has to be opened instead.    pub fn idle_section(&self, database: &str) -> Option<ExchangeRequest> {        let note = self.read(database).filter(HeldNote::idle)?;        Some(ExchangeRequest {            takes_copy: false,            parks_waiting: false,            workspace_id: database.to_string(),            cursors: note.cursors,            ops: Vec::new(),            limit: Some(EXCHANGE_PAGE_ROWS),            schema_version: Some(SCHEMA_VERSION),            schema_floor: Some(cotton_store::schema::move_intents::floor()),            handed_over_epoch: note.handed_over_epoch,            // An idle file is in no pass: a pass is an open file's.            handing_over_to: None,            serving_author: note.serving_author,        })    }    /// Every note, read once — what a pass over many databases asks, rather    /// than reading the file once per database.    pub fn read_all(&self) -> BTreeMap<String, HeldNote> {        self.load().files    }    /// Does `database` owe this device bytes ([`HeldNote::owes_bytes`]), by    /// the notes [`Self::read_all`] answered? No note is "yes": the file is    /// opened and asked, which is always correct and costs only the open.    pub fn owes_bytes(notes: &BTreeMap<String, HeldNote>, database: &str) -> bool {        notes.get(database).is_none_or(HeldNote::owes_bytes)    }    /// Record how a pass left an OPEN file: its cursors and its outbox, read    /// from the file itself, whether the pass finished, and where the peer's    /// last answer said the peer is. `pulled` is whether the pass folded any    /// row into it — what makes the file owe this device bytes.    pub fn note_pass(        &self,        database: &str,        db: &Driver,        caught_up: bool,        seen: &BTreeMap<String, String>,        pulled: bool,    ) -> Result<(), ConnectionFileError> {        let mut note = HeldNote {            cursors: read_cursors(db).map_err(|error| self.unreadable(error))?,            seen: seen.clone(),            outbox: pending_count(db).map_err(|error| self.unreadable(error))?,            held: Some(cotton_store::mint::clock::held_count(db).map_err(|error| self.unreadable(error))?),            caught_up,            schema_version: SCHEMA_VERSION,            handed_over_epoch: cotton_store::exchange::handed_over_epoch(db)                .map_err(|error| self.unreadable(error))?,            serving_author: db                .get("SELECT workspace_id FROM _meta", &[])                .ok()                .flatten()                .and_then(|row| row.text("workspace_id").map(str::to_string))                .and_then(|workspace| cotton_store::serving::serving_fact(db, &workspace).ok().flatten())                .map(|fact| fact.author_id),            pulls: 0,            bytes_level_at: None,        };        // The media half is carried from the note this replaces, under the        // one writer, so a tick's mark written since the last pass is kept.        self.change(|files| {            let before = files.get(database);            note.pulls = before.map_or(0, |before| before.pulls) + u64::from(pulled);            note.bytes_level_at = before.and_then(|before| before.bytes_level_at);            files.insert(database.to_string(), note);        })    }    /// A media tick left this database owing this device nothing, as of    /// `pulls` — the count it read BEFORE it opened the file, so rows folded    /// during the tick still owe. No note: nothing to mark, and the file    /// stays "open and ask" until a pass writes one.    pub fn note_bytes_level(&self, database: &str, pulls: u64) -> Result<(), ConnectionFileError> {        self.change(|files| {            if let Some(note) = files.get_mut(database) {                note.bytes_level_at = Some(pulls);            }        })    }    /// A write was just queued in this database: it is no longer idle.    ///    /// Marked, not counted: the only thing a reader of the note asks is "zero    /// or not", so the first write after a pass costs one small file write    /// and every write after it costs none.    pub fn note_write(&self, database: &str) -> Result<(), ConnectionFileError> {        self.change(|files| {            if let Some(note) = files.get_mut(database) {                if note.outbox == 0 {                    note.outbox = 1;                }            }            // No note is already "open the file": nothing to add.        })    }    /// Drop every note — the device left its server, and every file with it.    pub fn forget_all(&self) {        let _writing = WRITING.lock().unwrap_or_else(|error| error.into_inner());        // not a copy: the connection's lock.        let _ = std::fs::remove_file(&self.path);    }    /// Drop a database's note — it was left, or its file was replaced.    pub fn forget(&self, database: &str) -> Result<(), ConnectionFileError> {        self.change(|files| {            files.remove(database);        })    }    fn load(&self) -> HeldNotesFile {        std::fs::read_to_string(&self.path)            .ok()            .and_then(|text| serde_json::from_str(&text).ok())            .unwrap_or_default()    }    fn change(        &self,        change: impl FnOnce(&mut BTreeMap<String, HeldNote>),    ) -> Result<(), ConnectionFileError> {        let _writing = WRITING.lock().unwrap_or_else(|error| error.into_inner());        let mut file = self.load();        let before = file.files.clone();        change(&mut file.files);        if file.files == before {            return Ok(());        }        let body =            serde_json::to_string_pretty(&file).map_err(|source| ConnectionFileError::Parse {                path: self.path.display().to_string(),                source,            })?;        let temp = self.path.with_extension("json.writing");        write_durably(&temp, &self.path, &format!("{body}\n")).map_err(|source| {            ConnectionFileError::Read {                path: self.path.display().to_string(),                source,            }        })    }    fn unreadable(&self, error: impl std::fmt::Display) -> ConnectionFileError {        ConnectionFileError::Read {            path: self.path.display().to_string(),            source: std::io::Error::other(error.to_string()),        }    }}#[cfg(test)]mod tests {    use super::*;    fn note(outbox: i64, caught_up: bool) -> HeldNote {        HeldNote {            cursors: BTreeMap::from([("author-a".to_string(), "0001".to_string())]),            seen: BTreeMap::new(),            outbox,            held: Some(0),            caught_up,            schema_version: SCHEMA_VERSION,            handed_over_epoch: None,            serving_author: None,            pulls: 0,            bytes_level_at: None,        }    }    /// RULE: A database holding a write for the Mac's time is never spoken for by its note — the next pass opens its file, where judge time releases the write; a note that cannot say what it holds opens the file too.    ///    /// 13 Oct 2026: the owner approved two lists on the phone; the writes were    /// held (no Mac time yet that launch), the note counted the outbox alone    /// and said idle, and every pass answered for the file unopened — so the    /// release never ran and the approvals never left the phone.    #[test]    fn a_file_holding_writes_is_never_idle() {        let mut holding = note(0, true);        holding.held = Some(1);        let (_dir, notes) = notes_with("db-a", holding);        assert!(notes.idle_section("db-a").is_none(), "a held write opens the file");        let mut unsaid = note(0, true);        unsaid.held = None;        let (_dir, notes) = notes_with("db-a", unsaid);        assert!(notes.idle_section("db-a").is_none(), "a note that does not say opens the file");    }    fn notes_with(database: &str, held: HeldNote) -> (tempfile::TempDir, HeldNotes) {        let dir = tempfile::tempdir().expect("a temp folder");        let notes = HeldNotes::beside(&dir.path().join("connection.json"));        notes            .change(|files| {                files.insert(database.to_string(), held);            })            .expect("the note is written");        (dir, notes)    }    #[test]    fn an_idle_database_is_spoken_for_by_its_note() {        let (_dir, notes) = notes_with("db-a", note(0, true));        let section = notes.idle_section("db-a").expect("an idle section");        assert_eq!(section.workspace_id, "db-a");        assert!(section.ops.is_empty());        assert_eq!(section.cursors["author-a"], "0001");        assert_eq!(section.schema_version, Some(SCHEMA_VERSION));    }    #[test]    fn a_queued_write_an_unfinished_pass_another_build_or_no_note_opens_the_file() {        let (_dir, notes) = notes_with("db-a", note(0, true));        assert!(notes.idle_section("db-unknown").is_none());        notes.note_write("db-a").expect("counted");        assert_eq!(notes.read("db-a").expect("kept").outbox, 1);        assert!(notes.idle_section("db-a").is_none());        let (_dir, unfinished) = notes_with("db-a", note(0, false));        assert!(unfinished.idle_section("db-a").is_none());        let mut older = note(0, true);        older.schema_version = SCHEMA_VERSION - 1;        let (_dir, other_build) = notes_with("db-a", older);        assert!(other_build.idle_section("db-a").is_none());        notes.forget("db-a").expect("forgotten");        assert!(notes.read("db-a").is_none());    }    #[test]    fn a_pass_records_the_open_files_own_cursors_and_outbox() {        // The note is only worth anything if it says what the file says: a        // cursor or a queued op the note missed would let an idle section        // speak for a file that has something to hand over.        use cotton_store::cursors::advance_cursor;        use cotton_store::meta::Meta;        use rusqlite::types::Value as SqlValue;        const AT: &str = "2026-09-16T09:00:00.000Z";        let dir = tempfile::tempdir().expect("a temp folder");        let db = Driver::open(dir.path().join("db-a.db")).expect("a file");        cotton_store::create::create_workspace(            &db,            &Meta {                workspace_id: "db-a".to_string(),                owner_id: "owner-1".to_string(),                device_id: "device:this-phone".to_string(),                last_server_seq: 0,                last_hlc: None,            },        )        .expect("the ladder runs");        advance_cursor(            &db,            "device:other-phone",            "0001787394600000:0001:device:other-phone",            AT,        )        .expect("a cursor");        let notes = HeldNotes::beside(&dir.path().join("connection.json"));        notes.note_pass("db-a", &db, true, &BTreeMap::new(), false).expect("noted");        let note = notes.read("db-a").expect("a note");        assert_eq!(note.outbox, pending_count(&db).expect("a count"));        assert_eq!(note.outbox, 0);        assert_eq!(note.cursors, read_cursors(&db).expect("the cursors"));        assert!(!note.cursors.is_empty());        assert!(notes.idle_section("db-a").is_some());        db.run(            "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes)\n             VALUES ('op-1', 'create', 'device:this-phone', 'cotton_todos', 'todo-0', 'h', 1, ?, X'7b7d')",            &[SqlValue::Text(AT.to_string())],        )        .expect("a queued write");        notes.note_pass("db-a", &db, true, &BTreeMap::new(), false).expect("noted");        assert_eq!(notes.read("db-a").expect("a note").outbox, 1);        assert!(notes.idle_section("db-a").is_none());    }}