Cotton code
214 lines · 9.6 KB · RustRaw
//! `_cursors` — how far this file has seen each AUTHOR's writes.//!//! One row per WRITER, never per peer. Under table-as-log there is no server//! sequence to tail: a device asks each author's own stream//! ([`crate::changes::changes_since`]) for what it has not seen, so the cursor//! that matters is "the last stamp of A's I have folded", and it means the same//! thing whichever peer handed the writes over. Two devices can therefore hand//! each other the same person's writes without a server in the middle, and a//! device that has been offline for a month is caught up by the cursor that//! names IT, not by a log that may have been pruned past it.//!//! A cursor of `""` is "this author's writes have never been seen", which is//! the right answer for an author nobody has heard of — every stamp sorts after//! it. The one exception is [`crate::changes::ORIGIN_AUTHOR`], whose writes all//! sit at the empty stamp; its cursor is the `(table, row)` token//! `changes::origin_ceiling` answers with.//!//! Nothing here reads the clock (spec R7): `updated_at` arrives as the ISO//! string the caller decided on.use std::collections::BTreeMap;use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::Result;pub const FIRST_CURSORS_PAGE: &str = "SELECT author_device_id, hlc_seen FROM _cursors WHERE author_device_id >= ?1 ORDER BY author_device_id LIMIT 64";pub const CURSORS_PAGE: &str = "SELECT author_device_id, hlc_seen FROM _cursors WHERE author_device_id > ?1 ORDER BY author_device_id LIMIT 64";/// Count writers through bounded primary-key pages, including an empty author./// Works on offline backups as well as live files without assuming WAL mode.pub fn count_cursors(connection: &rusqlite::Connection) -> rusqlite::Result<i64> {    let mut after: Option<String> = None;    let mut count = 0;    loop {        let comparison = if after.is_some() { ">" } else { ">=" };        let mut statement = connection.prepare(&format!(            "SELECT author_device_id FROM _cursors WHERE author_device_id {comparison} ?1 ORDER BY author_device_id LIMIT 64"))?;        let rows = statement.query_map([after.as_deref().unwrap_or("")], |row| row.get::<_, String>(0))?            .collect::<rusqlite::Result<Vec<_>>>()?;        let Some(last) = rows.last() else { break; };        after = Some(last.clone());        count += rows.len() as i64;    }    Ok(count)}/// Every cursor this file holds, by author, read through bounded index seeks.pub fn read_cursors(db: &Driver) -> Result<BTreeMap<String, String>> {    let mut out = BTreeMap::new();    let mut after: Option<String> = None;    loop {        let rows = db.all(if after.is_some() { CURSORS_PAGE } else { FIRST_CURSORS_PAGE }, &[SqlValue::Text(after.clone().unwrap_or_default())])?;        let Some(last) = rows.last() else { break; };        after = last.text("author_device_id").map(str::to_string);        for row in rows {            out.insert(row.text("author_device_id").unwrap_or_default().to_string(),                row.text("hlc_seen").unwrap_or_default().to_string());        }    }    Ok(out)}/// Move an author's cursor to `hlc_seen`, FORWARDS ONLY. Answers whether it/// moved.////// The guard is in the statement rather than in a read-then-write, because two/// pages of the same author's stream can be folded in either order — a retry/// that arrives after a later page must not rewind the cursor and re-ask for/// writes this file has already folded. Backwards is not an error, it is a/// no-op: the caller asking for it has simply told us something we already/// knew.pub fn advance_cursor(db: &Driver, author: &str, hlc_seen: &str, at: &str) -> Result<bool> {    let moved = db.run(        "INSERT INTO _cursors (author_device_id, hlc_seen, updated_at) VALUES (?, ?, ?)\n         ON CONFLICT(author_device_id) DO UPDATE SET hlc_seen = excluded.hlc_seen, updated_at = excluded.updated_at\n           WHERE excluded.hlc_seen > _cursors.hlc_seen",        &[            SqlValue::Text(author.to_string()),            SqlValue::Text(hlc_seen.to_string()),            SqlValue::Text(at.to_string()),        ],    )?;    Ok(moved > 0)}/// Every author whose receipts this file currently HOLDS, at that author's/// maximum stamp over `_writes` and `_tombstones`, excluding held receipts/// and tables this build does not hand over.////// A snapshot records [`seen_ceiling`] before filtering; claim and replacement/// checks use those recorded cursors as well as the receipts still present./// Recomputing this map alone after a cut would lose positions for rows the/// copy intentionally omitted.pub fn cursor_ceiling(db: &Driver) -> Result<BTreeMap<String, String>> {    let mut ceiling: BTreeMap<String, String> = BTreeMap::new();    let mut raise = |author: &str, stamp: &str| {        if author.is_empty() || stamp.is_empty() {            return;        }        let entry = ceiling            .entry(author.to_string())            .or_insert_with(|| stamp.to_string());        if stamp > entry.as_str() {            *entry = stamp.to_string();        }    };    // The two places a write can be: `_writes` and `_tombstones` (a held    // receipt left out of both — it never travels, so it never counts as held    // by this file either, 3.8). Through the stream's own clause, so a receipt for a    // table this build never had raises nobody's ceiling.    for side in [WRITES, TOMBSTONES] {        for (author, top) in tops(db, side)? {            raise(&author, &top);        }    }    Ok(ceiling)}/// Each author's newest receipt in `table` that travels (not held) and is of a/// table this build hands over — BY WALKING THE AUTHOR INDEX, never by a pass/// over the table.////// This is asked on every exchange of every device (`seen_ceiling`), and as/// one `GROUP BY author` over the table it read EVERY receipt: the clause that/// keeps to known tables names `tbl`, which is in no author index, so each/// index entry cost a fetch of its row. On the owner's personal database that/// was 679,687 receipts and five to nine seconds inside the file to answer/// sixteen rows, once a minute, with every route and the roster read waiting/// behind it (11 Oct 2026: 7.88 M steps; this walk reads 1,426).////// So the authors are stepped through the index one at a time — the next/// author is the smallest one greater than the last — and each author's top is/// the first receipt met walking its stamps downward that is not held and is/// of a known table: one seek per author and, almost always, one row.////// [`Side`] says how the table's author index is spelled.fn tops(db: &Driver, side: Side) -> Result<Vec<(String, String)>> {    let known = crate::changes::known_tables_clause(db)?;    let Side { table, author, author_of_t, index_holds } = side;    let (only, and_only) = match index_holds {        Some(clause) => (format!(" WHERE {clause}"), format!(" AND {clause}")),        None => (String::new(), String::new()),    };    let sql = format!(        "WITH RECURSIVE authors(author) AS ( \           SELECT MIN({author}) FROM {table}{only} \           UNION ALL \           SELECT (SELECT MIN({author}) FROM {table} WHERE {author} > authors.author{and_only}) \           FROM authors WHERE authors.author IS NOT NULL) \         SELECT author, \                (SELECT t.hlc FROM {table} t WHERE {author_of_t} = authors.author AND t.held = 0 AND {known} \                 ORDER BY t.hlc DESC LIMIT 1) AS top \         FROM authors WHERE author IS NOT NULL"    );    let mut tops = Vec::new();    for row in db.all(&sql, &[])? {        if let (Some(author), Some(top)) = (row.text("author"), row.text("top")) {            tops.push((author.to_string(), top.to_string()));        }    }    Ok(tops)}/// One of the two places a receipt can be, and its author index: the/// expression the index leads with, the same expression of the row `t`, and/// the condition a partial index holds only rows of.#[derive(Clone, Copy)]struct Side {    table: &'static str,    author: &'static str,    author_of_t: &'static str,    index_holds: Option<&'static str>,}/// `_writes`, by `idx_writes_author (author, hlc) WHERE held = 0`.const WRITES: Side = Side { table: "_writes", author: "author", author_of_t: "t.author", index_holds: Some("held = 0") };/// `_tombstones`, by `idx_tombstones_author (substr(hlc, 20), hlc)` — the/// stamp's own author, `<13 ms>:<4 counter>:<author>`.const TOMBSTONES: Side =    Side { table: "_tombstones", author: "substr(hlc, 20)", author_of_t: "substr(t.hlc, 20)", index_holds: None };/// How far this file has SEEN each author — what a peer hands over from.////// [`cursor_ceiling`] is what this file HOLDS; `_cursors` is what it has/// FOLDED, and the two are not the same map. A write of A's that lost to a/// newer write of B's leaves no row, no tombstone and no shadow entry — it is/// gone from the ceiling — while `_cursors` still remembers folding it. A peer/// told only the ceiling would hand that write over again on every pass for/// ever, and the fold would discard it again every time.////// So the honest answer is the maximum of the two, per author, and it is what/// [`crate::exchange::answer`] puts on the wire.pub fn seen_ceiling(db: &Driver) -> Result<BTreeMap<String, String>> {    Ok(raised_by(cursor_ceiling(db)?, read_cursors(db)?))}pub(crate) fn raised_by(    mut held: BTreeMap<String, String>,    folded: BTreeMap<String, String>,) -> BTreeMap<String, String> {    for (author, hlc) in folded {        let entry = held.entry(author).or_default();        if hlc > *entry {            *entry = hlc;        }    }    held}#[cfg(test)]#[path = "cursors_tests.rs"]mod tests;