Cotton code
173 lines · 7.8 KB · RustRaw
//! The sealing sweep (sealing plan §1, §7; L3): every open row of a sealed//! table that this copy holds, sealed and posted as the object's `seal` act//! with `expect_version`, so a row the object changed since is left for the//! next pass rather than overwritten.//!//! Open rows come from two places: the Worker's own writes outside a window//! (an MCP `create_record` on a note), and legacy rows from before the table//! was sealed. A row marked `keep_open` stays open (Q3).//!//! It resumes by construction: each row sealed is noted at once//! (`_seal.sealed = 1`), so a sweep cut short by a dropped line or a missing//! key leaves only the rows it did not reach, and the next one takes those.//! Generic over the poster, so the Mac importer runs the same sweep (Q21).use serde_json::{json, Map, Value};use super::{guard_act, Note, Sealer, KEEP_OPEN};use crate::transport::object::{ObjectRefusal, ObjectTables};/// What a sweep did.#[derive(Debug, Default, Clone, PartialEq)]pub struct Swept {    /// The rows sealed, as notes for the copy.    pub notes: Vec<Note>,    /// Rows left as they are, each with why: kept open, gone from the copy,    /// or changed on the object since (`version_mismatch`).    pub left: Vec<(String, String, String)>,    /// Why the sweep stopped before its last row: no key, or no line.    pub stopped: Option<String>,    /// Open rows left for the next pass: this pass's budget was spent.    pub more: bool,}/// The open rows of sealed tables this copy holds: `(table, id, version)`.pub fn open_rows(file: &rusqlite::Connection, map: &ObjectTables) -> Result<Vec<(String, String, i64)>, String> {    let exists: i64 = file        .query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = '_seal'", [], |row| row.get(0))        .map_err(|error| format!("this copy's seal state could not be read ({error})"))?;    if exists == 0 {        return Ok(Vec::new());    }    let unread = |error: rusqlite::Error| format!("this copy's open sealed rows could not be read ({error})");    let mut statement = file.prepare("SELECT tbl, row_id, version FROM _seal WHERE sealed = 0 ORDER BY tbl, row_id").map_err(unread)?;    let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, i64>(2)?))).map_err(unread)?;    let mut out = Vec::new();    for row in rows {        let row = row.map_err(unread)?;        if map.object(&row.0).is_some_and(|table| table.seal.is_some()) {            out.push(row);        }    }    Ok(out)}/// Rows one pass's sweep seals at most (SYNC STUCK, 25 Nov 2026: an unbounded sweep, one round trip a row, held his/// phones' passes past their 120 s for hours, so nothing was pulled). The rest wait for the next pass, after its pull.pub const PASS_ROWS: usize = 2000;/// Seconds one pass's sweep runs at most, whatever is left.pub const PASS_SECONDS: u64 = 20;/// Rows sealed per round trip (the object's `seal_many` takes 200).pub const BATCH: usize = 100;/// How much one sweep may do: rows, and a time it stops by.#[derive(Debug, Clone, Copy)]pub struct Budget {    pub rows: usize,    pub until: Option<std::time::Instant>,}impl Budget {    /// One pass's share: [`PASS_ROWS`] rows, [`PASS_SECONDS`] seconds from now.    pub fn pass() -> Budget {        Budget { rows: PASS_ROWS, until: Some(std::time::Instant::now() + std::time::Duration::from_secs(PASS_SECONDS)) }    }    /// No bound (the Mac importer's migration, run on its own).    pub fn whole() -> Budget {        Budget { rows: usize::MAX, until: None }    }    fn spent(&self, done: usize) -> bool {        done >= self.rows || self.until.is_some_and(|until| std::time::Instant::now() >= until)    }}/// Seal and post the open rows, at most `budget`, [`BATCH`] to a round trip, each batch's marks kept (`keep`) as soon/// as the object answers it. `row_of` reads the row as the copy holds it/// (the object's columns, plaintext); `post` posts one batch of `seal` args and answers each row's outcome in order,/// or the whole call's refusal. A sweep cut short by its budget leaves the rest for the next pass (`more`).pub fn sweep(    sealer: &Sealer,    map: &ObjectTables,    open: &[(String, String, i64)],    budget: Budget,    mut row_of: impl FnMut(&str, &str) -> Result<Option<Map<String, Value>>, String>,    mut post: impl FnMut(&[Value]) -> Result<Vec<Result<(), ObjectRefusal>>, ObjectRefusal>,    mut keep: impl FnMut(&[Note]) -> Result<(), String>,) -> Result<Swept, String> {    let mut swept = Swept::default();    let mut batch: Vec<(Value, Note)> = Vec::new();    let mut done = 0usize;    let mut flush = |batch: &mut Vec<(Value, Note)>, swept: &mut Swept| -> bool {        if batch.is_empty() {            return true;        }        let args: Vec<Value> = batch.iter().map(|(args, _)| args.clone()).collect();        let taken = std::mem::take(batch);        match post(&args) {            Ok(outcomes) => {                let before = swept.notes.len();                for ((_, note), outcome) in taken.into_iter().zip(outcomes.into_iter().chain(std::iter::repeat_with(|| Err(ObjectRefusal { status: 502, code: "no_answer".into(), message: "the object answered fewer rows than were sent".into() })))) {                    match outcome {                        Ok(()) => swept.notes.push(note),                        // Changed on the object since, gone, or refused: the next pull says what it holds now, and the                        // next sweep looks again.                        Err(refusal) => {                            let (table, id) = match &note {                                Note::Sealed { table, id, .. } => (table.clone(), id.clone()),                                _ => (String::new(), String::new()),                            };                            swept.left.push((table, id, refusal.code));                        }                    }                }                // Kept as it goes: a pass cut short after this keeps what this batch sealed.                if let Err(why) = keep(&swept.notes[before..]) {                    swept.stopped = Some(why);                    return false;                }                true            }            Err(refusal) => {                swept.stopped = Some(refusal.message);                false            }        }    };    for (table, id, version) in open {        if budget.spent(done) {            swept.more = true;            break;        }        let Some(spec) = map.object(table).and_then(|stored| stored.seal.clone()) else { continue };        let Some(row) = row_of(table, id)? else {            swept.left.push((table.clone(), id.clone(), "gone from this copy".into()));            continue;        };        if row.get(KEEP_OPEN) == Some(&Value::Bool(true)) {            swept.left.push((table.clone(), id.clone(), KEEP_OPEN.into()));            continue;        }        // An open row has no DEK yet: a fresh one.        let mut plain = row;        plain.remove(KEEP_OPEN);        let sealed = match sealer.seal(table, id, &spec, &plain, None) {            Ok(sealed) => sealed,            Err(error) => {                swept.stopped = Some(error.to_string());                break;            }        };        let args = json!({"table": table, "id": id, "data": sealed.data, "blind": sealed.blind, "expect_version": version});        let spec_of = |name: &str| map.object(name).and_then(|stored| stored.seal.clone());        guard_act(spec_of, "seal", &args)?;        batch.push((args, Note::Sealed { table: table.clone(), id: id.clone(), dek_enc: sealed.dek_enc, seal_v: sealed.seal_v, version: *version }));        done += 1;        if batch.len() >= BATCH && !flush(&mut batch, &mut swept) {            return Ok(swept);        }    }    flush(&mut batch, &mut swept);    Ok(swept)}