Cotton code
181 lines · 8.3 KB · RustRaw
//! The corrections a downloaded file needs before anything reads it.//!//! A snapshot is a copy of SOMEBODY ELSE'S file — the server's — and some of//! what is in it describes the server rather than this device.//!//! 1. **`device_id`** — the author stamped on every op this device writes and//!    the name its writes are found under in its own stream. Inheriting the//!    server's means writing under the server's name.//! 2. **The cursors** — how far this file has seen each AUTHOR. A device//!    holding a copy has, by definition, seen every write IN IT, so each//!    author's cursor goes to that author's own top stamp in the arrived file//!    (`cursors::seen_ceiling`). The cut records its full ceiling before//!    filtering rows and receipts, so claiming the cut never rewinds sync.//!    Without this the first exchange would ask every author for//!    everything and fold a whole file's worth of ops back over itself.//! 3. **`_media` emptied** — a media row is an upload of bytes this device does//!    not have.//!//! 4. **The author** — `_meta.author_id` is the stream every write of a FILE is//!    minted under, one author per device per file. `_meta` travels in the//!    copy (the snapshot is `VACUUM INTO` of the whole file), so a claim that//!    left it alone would leave this device minting under the SERVING MAC's//!    author: two machines, one stream, and a stamp either of them could//!    issue twice. The claim mints this device's own, and its fact is the//!    first row of this device's outbox.//! 5. **The local marks** — `rotation_check_due` is the serving Mac's own//!    reminder and is cleared; `handed_over_epoch` is set to the copy's OWN//!    serving epoch, because a device that holds nothing its server lacks owes//!    no hand-over, and the erase guard reads this device's mark, never the//!    server's copied one. `heard_serving_epoch` is set to that same epoch://!    the copy's value is what the server heard, and this device has heard of//!    the epoch it was handed and nothing newer. `origin` and `carry_complete`//!    describe the file and are kept.//!//! All of them in one transaction: a file with some of them applied is a file//! nobody wrote a rule for.//!//! ## What the claim does NOT do any more//!//! **It does not empty `_outbox`.** It used to, and that made the claim a//! function that could destroy writes — the re-hydrate's doc still had to warn//! its callers to drain first. The server's own queued ops are emptied by the//! STRIP instead (`cotton_store::snapshot::NOT_ON_A_PHONE`), on the server's//! copy, where the only rows in reach belong to the file being copied. A//! device's own queued writes are its own and survive everything.//!//! **It does not read a server sequence.** `last_server_seq` was the pull//! cursor, and there is no pull: `_snapshot_head`, `X-Cotton-Last-Seq` and the//! `header_disagreed` report are all gone with it.//!//! ## And it REFUSES a device that already has data//!//! A whole-file copy is never put beside a STRAY — a replica holding rows that//! is neither Mine nor a listed place: two lives on one device are joined only//! when the owner asks.use std::collections::BTreeMap;use cotton_store::cursors::seen_ceiling;use cotton_store::driver::Driver;use cotton_store::mint::clock::writer_clock;use cotton_store::mint::{first_author, AuthorReason, Held, IdSource};use cotton_store::serving::serving_fact;use cotton_store::StoreError;use rusqlite::types::Value as SqlValue;/// What claiming a snapshot changed.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Claimed {    /// Where each author's cursor was set — the arrived file's own ceiling.    pub cursors: BTreeMap<String, String>,    pub dropped_from_media: usize,    /// The author this device now mints under in this file. A reader has none:    /// its snapshot corrections are local and it never mints a receipt.    pub author: Option<String>,    /// The copy's own serving epoch, now this device's hand-over mark. `None`    /// when the copy holds no serving fact.    pub handed_over_epoch: Option<i64>,}/// Make the downloaded file this device's own.////// `held_elsewhere` is how many records this DEVICE is already holding in a/// STRAY file — one that is neither Mine nor a listed place, as the caller/// counts them. Zero on the ordinary first run, and the reason this call can/// refuse./// `now_ms` is the instant the cursor rows record and the author is minted at/// — this crate reads no clock of its own — and `ids` names the author and its/// fact.pub fn claim_snapshot(    db: &Driver,    device_id: &str,    held_elsewhere: usize,    now_ms: i64,    ids: &mut dyn IdSource,) -> cotton_store::Result<Claimed> {    if held_elsewhere > 0 {        return Err(StoreError::refused(format!(            "this device already holds {held_elsewhere} records in a database nothing has an \             address for, and a copy beside them would mix two databases — erase this device \             first"        )));    }    let now = cotton_store::protocol::js::to_iso_string(now_ms)        .ok_or_else(|| StoreError::encode(format!("timestamp out of range: {now_ms}")))?;    db.transaction(|db| {        // The copy's own epoch, read before anything of this device's is        // written: what this device holds is exactly what that epoch's server        // handed it.        let workspace_id = db            .get("SELECT workspace_id FROM _meta", &[])?            .and_then(|row| row.text("workspace_id").map(str::to_string))            .unwrap_or_default();        let handed_over_epoch = serving_fact(db, &workspace_id)?.map(|fact| fact.epoch);        db.run(            // No `WHERE`: `_meta` is single-row by construction. The author is            // emptied here and minted below, once the cursors are this file's.            "UPDATE _meta SET device_id = ?, author_id = NULL, rotation_check_due = NULL, \             handed_over_epoch = ?, heard_serving_epoch = ?",            &[                SqlValue::Text(device_id.to_string()),                handed_over_epoch.map_or(SqlValue::Null, SqlValue::Integer),                // Heard of exactly the copy's own epoch: the server's copied                // value is what IT heard, not what this device was told.                handed_over_epoch.map_or(SqlValue::Null, SqlValue::Integer),            ],        )?;        // The cut records the full Mac's ceiling before removing rows and        // their receipts. Read it BEFORE replacing the copied cursor map.        let cursors = seen_ceiling(db)?;        db.run("DELETE FROM _cursors", &[])?;        for (author, hlc_seen) in &cursors {            db.run(                "INSERT INTO _cursors (author_device_id, hlc_seen, updated_at) VALUES (?, ?, ?)",                &[                    SqlValue::Text(author.clone()),                    SqlValue::Text(hlc_seen.clone()),                    SqlValue::Text(now.clone()),                ],            )?;        }        // not a copy: a snapshot just downloaded and being claimed: its _media rows are the serving Mac's ledger, never this phone's uploads.        let dropped_from_media = db.run("DELETE FROM _media", &[])?;        // THIS DEVICE'S OWN AUTHOR, after the cursors: the mint advances its        // own author's cursor, and the reset above would have taken it away.        // `Held::Replica` queues the fact, so the serving Mac hears of the        // author before it hears anything the author wrote.        let reader = db.device_scope() == Some(cotton_store::device_scope::DeviceScope::Reader)            || db.signer()                .map(|signer| cotton_store::device_scope::scope_of(db, &signer.device_key()))                .transpose()?                == Some(cotton_store::device_scope::DeviceScope::Reader);        let author = if reader {            None        } else {            Some(first_author(                db,                device_id,                None,                AuthorReason::First,                &writer_clock(db, now_ms, ids)?,                ids,                Held::Replica,            )?.id)        };        Ok(Claimed {            cursors,            dropped_from_media,            author,            handed_over_epoch,        })    })}#[cfg(test)]#[path = "claim_tests.rs"]mod tests;