Cotton code
409 lines · 18.0 KB · RustRaw
//! **What a copy another build stamped holds that its server does not** —//! listed from the receipts alone, and dropped only when the person says so.//!//! Every change this device has not sent is kept as its SIGNED RECEIPT — the//! canonical bytes and signature that travel on the wire as they are//! (`cotton_store::wire`), written in the same transaction as the write//! itself. So the list reads only `op_id`, `bytes` and `sig` from the receipt//! tables (`_outbox`; a parked push; a held write or delete) and decodes//! everything else — table, row, kind, stamp — from the bytes. Nothing here//! opens the file as a store, runs a migration, or reads any other column: a//! build at schema N+1 lists what a build at N queued. `unsent_tests.rs`//! stamps the file with another schema and changes its other tables to prove//! it.//!//! A copy dropped with changes in it writes every change down first//! ([`record_discarded`]), for the Feedback row filed once a copy is open again//! ([`discarded`]).use std::collections::BTreeMap;use std::collections::BTreeSet;use std::path::{Path, PathBuf};use cotton_store::migrate::SCHEMA_VERSION;use cotton_store::protocol::types::CottonOp;use cotton_store::Driver;use crate::layout::Layout;/// Where an unsent change was waiting in the old copy.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase")]pub enum Waiting {    /// Queued to send (`_outbox`).    Queued,    /// Sent once and parked for another try (`_parked`, a push).    Parked,    /// Made before this device had the Mac's time (`held = 1`).    Held,}/// One change this device made and the Mac does not hold yet — what the screen/// lists and what a discard names.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase")]pub struct UnsentChange {    pub op_id: String,    /// The table, as the receipt names it (`cotton_todos`).    pub table: String,    pub row_id: String,    /// `upsert` or `delete` — the receipt's own word.    pub kind: String,    /// When it was made: the receipt's stamp.    pub made_at: String,    pub waiting: Waiting,}impl UnsentChange {    /// The fact naming this device as an author, queued beside its first    /// write: sent like any change, never listed to a person as one.    pub fn is_bookkeeping(&self) -> bool {        self.table == "cotton_authors"    }    pub(crate) fn of(op: &CottonOp, waiting: Waiting) -> UnsentChange {        UnsentChange {            op_id: op.op_id.clone(),            table: op.table.clone(),            row_id: op.row_id.clone(),            kind: op.kind.as_str().to_string(),            made_at: op.hlc.clone(),            waiting,        }    }}/// The receipts this copy has not sent, read from `op_id`, `bytes` and `sig`/// alone, oldest stamp first. A table the file does not have holds nothing.pub(crate) fn receipts(db: &Driver) -> Result<Vec<(CottonOp, Waiting)>, String> {    let has = |table: &str| -> Result<bool, String> {        db.get(            "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",            &[rusqlite::types::Value::Text(table.to_string())],        )        .map(|row| row.is_some())        .map_err(|error| error.to_string())    };    let mut found: Vec<(CottonOp, Waiting)> = Vec::new();    let mut seen: BTreeSet<String> = BTreeSet::new();    let mut read = |from: &str, waiting: Waiting| -> Result<(), String> {        // Counted first: an empty store holds nothing to send, whatever        // columns another build gave it.        let rows = db            .get(&format!("SELECT COUNT(*) AS n FROM {from}"), &[])            .map_err(|error| error.to_string())?            .and_then(|row| row.int("n"))            .unwrap_or(0);        if rows == 0 {            return Ok(());        }        for row in db.all(&format!("SELECT op_id, bytes, sig FROM {from}"), &[]).map_err(|error| error.to_string())? {            let op_id = row.text("op_id").unwrap_or_default().to_string();            if seen.contains(&op_id) {                continue;            }            // A parked push with no receipt has nothing anyone can send            // again; it was lost when it was parked.            if waiting == Waiting::Parked                && !matches!(row.get("bytes"), Some(rusqlite::types::Value::Blob(_) | rusqlite::types::Value::Text(_)))            {                continue;            }            // One that does not read is set aside and said by the stuck list (QUEUE BAD OP); nothing here can send            // it or name what it changes, so it is left out rather than stopping whoever asked.            let op = match cotton_store::stored::outbox_row(&row) {                Ok(op) => op,                Err(error) => {                    eprintln!("[cotton-sync] unsent change {op_id} does not read, left out ({error})");                    continue;                }            };            seen.insert(op_id);            found.push((op, waiting));        }        Ok(())    };    if has("_outbox")? {        read("_outbox", Waiting::Queued)?;    }    if has("_parked")? {        read("_parked WHERE direction = 'push'", Waiting::Parked)?;    }    for table in ["_writes", "_tombstones"] {        if has(table)? {            read(&format!("{table} WHERE held = 1"), Waiting::Held)?;        }    }    // WRITE ORDER, as `exchange_request` sends it: the fold applies a batch in    // the order given, and a row's amendment ahead of its create is refused.    found.sort_by(|left, right| left.0.hlc.cmp(&right.0.hlc));    Ok(found)}/// How many changes this copy has not sent write something its move to this/// build loses ([`cotton_store::signed::touches_a_loss`]) — the ones that hold/// the copy where it is (`crate::dev_heal`). An `Err` when they cannot be/// read: whether they do cannot be told.pub(crate) fn touching_a_loss(db: &Driver) -> Result<usize, String> {    Ok(receipts(db)?        .iter()        .filter(|(op, _)| cotton_store::signed::touches_a_loss(op))        .count())}/// The changes the copy at `path` holds that the Mac does not, oldest first.pub fn unsent_changes(path: &Path) -> Result<Vec<UnsentChange>, String> {    let db = Driver::open(path).map_err(|error| error.to_string())?;    Ok(receipts(&db)?        .iter()        .map(|(op, waiting)| UnsentChange::of(op, *waiting))        .collect())}/// The schema the copy at `path` is stamped with, when it is another build's:/// `None` for no file, a file that will not answer, an unstamped file, or one/// at this build's schema.////// Read from the file's header on a read-only connection, never a writer's/// open: a launch asks this of the copy its own core already holds open, and/// a writer's open sets `journal_mode`, which waits for an exclusive lock in/// SQLite's busy back-off (rust-main and verify-main 16282: Notes' signed-in/// connect at 2.2 s of a 1.5 s launch budget, 0.2 s of it here at rest).pub fn stamped_by_another_build(path: &Path) -> Option<u32> {    if !path.exists() {        return None;    }    let file = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX).ok()?;    let stamped: i64 = file.query_row("PRAGMA user_version", [], |row| row.get(0)).ok()?;    let stamped = u32::try_from(stamped).ok()?;    (stamped != 0 && stamped != SCHEMA_VERSION).then_some(stamped)}/// MOVE A COPY IN PLACE WHEN ITS BUILD ONLY ADDED (owner, 21 Nov 2026: every/// update that raised the schema threw the owner's copy away and pulled it/// all again, 25 minutes of an empty Chat several times a day). A copy an/// earlier build wrote whose move to this build only adds/// ([`cotton_store::shape_move::only_adds`]: new tables, columns, indexes, a/// search index that fills in the background) is moved now, in one/// transaction, every row kept, and stays this phone's copy: its cursor goes/// on, so its next pass pulls only what changed. `Ok(true)` when it moved;/// `Ok(false)` when it is not such a copy (another shape, a newer build's, a/// move under way), and it is made again from the object as before. A move/// that fails rolls back whole and says why; the copy is then made again.pub fn move_copy_if_it_only_adds(path: &Path) -> Result<bool, String> {    let Some(stamped) = stamped_by_another_build(path) else { return Ok(false) };    if stamped > SCHEMA_VERSION {        return Ok(false);    }    let db = Driver::open(path).map_err(|error| error.to_string())?;    if !cotton_store::shape_move::only_adds(&db).map_err(|error| error.to_string())? {        return Ok(false);    }    let report = cotton_store::shape_move::move_to_current(&db).map_err(|error| error.to_string())?;    eprintln!("cotton-client: the copy moved in place from schema {stamped} to {SCHEMA_VERSION}, every row kept, in {} ms ({} made)", report.took_ms, report.created.len());    Ok(true)}/// Changes this phone threw away with a copy, kept beside the copy's folder/// until the Feedback row naming them is filed (the discard happens before any/// copy is open to file it in).#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase")]pub struct Discarded {    pub workspace_id: String,    /// When the copy went, ISO 8601.    pub at: String,    /// Why: the person chose "Discard them", or the Mac refused them for good.    pub why: String,    pub changes: Vec<UnsentChange>,    /// The Mac's reason per refused change, by op id.    #[serde(default)]    pub reasons: BTreeMap<String, String>,}/// What this device is, as a Feedback row names it: a Mac discards a copy/// too, and "This phone" on a Mac's row was wrong (11 Oct 2026).pub(crate) const THIS_DEVICE: &str = if cfg!(target_os = "macos") {    "This Mac"} else if cfg!(any(target_os = "ios", target_os = "android")) {    "This phone"} else {    "This device"};impl Discarded {    /// The Feedback row's words: what table, what record, when.    pub fn note(&self) -> String {        let shown: Vec<&UnsentChange> = self.changes.iter().filter(|change| !change.is_bookkeeping()).collect();        let mut note = format!(            "{} discarded {} unsent {} to database {} at {} ({}).",            THIS_DEVICE,            shown.len(),            if shown.len() == 1 { "change" } else { "changes" },            self.workspace_id,            self.at,            self.why,        );        for change in shown {            note.push_str(&format!(                "\n- {} {} in {}, made {}",                change.kind, change.row_id, change.table, change.made_at            ));            if let Some(reason) = self.reasons.get(&change.op_id) {                note.push_str(&format!(" — the Mac said: {reason}"));            }        }        note    }    /// The key a Feedback row is filed once under.    pub fn key(&self) -> String {        format!("discarded-unsent:{}:{}", self.workspace_id, self.at)    }}fn discarded_path(layout: &Layout, workspace_id: &str) -> PathBuf {    layout.replica(workspace_id).with_file_name("discarded-unsent.json")}/// What was discarded from `workspace_id`'s copies and not yet filed.pub fn discarded(layout: &Layout, workspace_id: &str) -> Vec<Discarded> {    std::fs::read(discarded_path(layout, workspace_id))        .ok()        .and_then(|bytes| serde_json::from_slice(&bytes).ok())        .unwrap_or_default()}/// Forget the discards whose Feedback rows are filed.pub fn forget_discarded(layout: &Layout, workspace_id: &str, filed: &[Discarded]) {    let left: Vec<Discarded> = discarded(layout, workspace_id)        .into_iter()        .filter(|entry| !filed.contains(entry))        .collect();    let path = discarded_path(layout, workspace_id);    if left.is_empty() {        // not a copy: the discards list beside it.        let _ = std::fs::remove_file(path);    } else if let Ok(bytes) = serde_json::to_vec_pretty(&left) {        // not a copy: a record beside the copy (the discarded changes, the rows the server refused), never the copy.        let _ = std::fs::write(path, bytes);    }}pub(crate) fn record_discarded(    layout: &Layout,    workspace_id: &str,    changes: Vec<UnsentChange>,    reasons: BTreeMap<String, String>,    why: &str,    at: &str,) -> Result<(), String> {    if !changes.is_empty() {        let mut entries = discarded(layout, workspace_id);        entries.push(Discarded {            workspace_id: workspace_id.to_string(),            at: at.to_string(),            why: why.to_string(),            changes,            reasons,        });        let path = discarded_path(layout, workspace_id);        if let Some(parent) = path.parent() {            std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;        }        // Written BEFORE the copy goes: a discard nobody can name afterwards        // is the loss this record exists to prevent.        // not a copy: a record beside the copy (the discarded changes, the rows the server refused), never the copy.        std::fs::write(&path, serde_json::to_vec_pretty(&entries).map_err(|error| error.to_string())?)            .map_err(|error| format!("the discarded changes could not be written down, so the copy stays: {error}"))?;    }    Ok(())}/// A row the object refused for good at a backup, kept on this phone as it stood (`kept-rows.json` beside the/// object's copy): the written-down discard names only its op (what Feedback is told), so without this a scene and/// its lines written before sign-in were gone with the phone's own database (launch-story walk, 22 Nov 2026). Never/// filed anywhere. `table` and `row_id` are the object's, and `data` the row as the object would take it (the/// database's ids made the object's), in the clear: a later sync pass posts it again/// (`ObjectTransport::post_kept_rows`) and it leaves the file once the object takes it.#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]pub struct KeptRow {    pub table: String,    #[serde(rename = "rowId")]    pub row_id: String,    pub data: serde_json::Value,    pub why: String,    pub at: String,}fn kept_path(layout: &Layout, workspace_id: &str) -> PathBuf {    layout.replica(workspace_id).with_file_name("kept-rows.json")}/// The rows kept on this phone after the object refused them (see [`KeptRow`]). A file that does not read is set/// aside first (QUEUE BAD OP 6, M1), so what it held is never replaced.pub fn kept_rows(layout: &Layout, workspace_id: &str) -> Vec<KeptRow> {    load_kept_rows(&kept_path(layout, workspace_id)).unwrap_or_default()}/// The kept rows at `path`: none when there is no file; a file that does not read, or does not parse, is renamed/// beside under a numbered name (`kept-rows.unreadable.<n>.json`, never one that exists) and none answered; one that/// cannot be set aside is an error, and nothing writes over it.fn load_kept_rows(path: &Path) -> Result<Vec<KeptRow>, String> {    let bytes = match std::fs::read(path) {        Ok(bytes) => bytes,        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),        Err(error) => return Err(format!("the kept rows do not read ({error}), so they stay as they are")),    };    if let Ok(rows) = serde_json::from_slice(&bytes) {        return Ok(rows);    }    let aside = (1..).map(|n| path.with_file_name(format!("kept-rows.unreadable.{n}.json"))).find(|aside| std::fs::symlink_metadata(aside).is_err()).unwrap_or_default();    // not a copy: the kept rows list beside it, set aside whole under a name of its own.    std::fs::rename(path, &aside).map_err(|error| format!("the kept rows do not parse and could not be set aside ({error}), so they stay as they are"))?;    eprintln!("[unsent] the kept rows did not parse; they are kept beside as {}", aside.display());    Ok(Vec::new())}/// The kept rows written whole or not at all: to a file of its own, then renamed over the list in one step, so a/// stop part way leaves the list as it was (QUEUE BAD OP 6, M1).fn write_kept_rows(path: &Path, rows: &[KeptRow]) -> Result<(), String> {    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;    }    let next = path.with_file_name("kept-rows.json.next");    let bytes = serde_json::to_vec_pretty(rows).map_err(|error| error.to_string())?;    // not a copy: the kept rows list beside it, written whole to a file of its own first.    std::fs::write(&next, bytes).map_err(|error| error.to_string())?;    std::fs::File::open(&next).and_then(|file| file.sync_all()).map_err(|error| error.to_string())?;    // not a copy: the kept rows list beside it, put in place in one step.    std::fs::rename(&next, path).map_err(|error| error.to_string())}/// Write the kept rows as they now stand; none left removes the file. A list that does not read is set aside/// first, never written over.pub(crate) fn set_kept_rows(layout: &Layout, workspace_id: &str, rows: &[KeptRow]) -> Result<(), String> {    let path = kept_path(layout, workspace_id);    load_kept_rows(&path)?;    if rows.is_empty() {        // not a copy: the kept rows list beside it.        return match std::fs::remove_file(&path) {            Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),            _ => Ok(()),        };    }    write_kept_rows(&path, rows)}/// Keep `row` on this phone (see [`KeptRow`]); a later keep of the same row replaces it.pub(crate) fn keep_row(layout: &Layout, workspace_id: &str, row: KeptRow) -> Result<(), String> {    let path = kept_path(layout, workspace_id);    let mut rows = load_kept_rows(&path).map_err(|error| format!("a refused row could not be kept on this phone, so the copy stays: {error}"))?;    rows.retain(|kept| !(kept.table == row.table && kept.row_id == row.row_id));    rows.push(row);    write_kept_rows(&path, &rows).map_err(|error| format!("a refused row could not be kept on this phone, so the copy stays: {error}"))}#[cfg(test)]#[path = "unsent_tests.rs"]mod tests;