Cotton code
216 lines · 9.3 KB · RustRaw
//! `mint`'s HISTORY hook — slice 6's one history rule (store-history).//!//! History is `cotton_changes`, one row per act per record, written by `mint`//! as receipts of the act that made the change, so it travels with the act and//! every device holds the same rows. Folding a peer's write writes none: the//! fold never calls this. A row holds the act's verb and actor, the stamp of//! the record's write, the record's kind, and before and after of the MOVED//! fields only — a secret column as `has_<column>`, never its value.//!//! Which records keep history: the kinds on//! [`crate::schema::versioned::VERSIONED_TABLES`] — every record kind a person//! sees. Every other table is machine bookkeeping or a supporting row and says//! why in `cotton-core`'s registry (`SUPPORTING_TABLES`, or the kind's//! `versioned: No(reason)`). An act that says [`super::History::None`] (a job//! touching rows every hour, a bulk ingest) keeps none, and an act that brings//! its own history row (the generic verbs, until they hand theirs to `mint`)//! gets no second one.use std::collections::BTreeSet;use serde_json::{Map, Value as JsonValue};use super::{Act, Change, History, Kind};use crate::driver::Driver;use crate::error::Result;use crate::fact_hooks::HISTORY_TABLE;use crate::fold;use crate::protocol::types::CottonOp;use crate::schema::versioned::{VersionedTable, VERSIONED_TABLES};/// The records an act will write history for, each as it stood before the act.pub(crate) struct Before {    rows: Vec<(&'static VersionedTable, String, Option<Map<String, JsonValue>>)>,}/// Read, before the act folds, every record it will write history for. `None`/// when the act keeps no history.pub(crate) fn before(db: &Driver, act: &Act) -> Result<Option<Before>> {    if act.history == History::None || act.changes.iter().any(|change| change.table == HISTORY_TABLE) {        return Ok(None);    }    let erased: BTreeSet<(&str, &str)> = act        .changes        .iter()        .filter(|change| change.delete.as_ref().is_some_and(|delete| delete.erase_reason().is_some()))        .map(|change| (change.table.as_str(), change.row_id.as_str()))        .collect();    let mut seen = BTreeSet::new();    let mut rows = Vec::new();    for change in &act.changes {        let Some(versioned) = VERSIONED_TABLES.iter().find(|v| v.table == change.table) else {            continue;        };        let key = (change.table.as_str(), change.row_id.as_str());        if erased.contains(&key) || !seen.insert(key) {            continue;        }        rows.push((versioned, change.row_id.clone(), read_versioned(db, versioned, &change.row_id)?));    }    Ok(Some(Before { rows }))}/// The history rows of an act that has folded: one create of `cotton_changes`/// per record that moved, after the act's own receipts `ops`.pub(crate) fn rows(    db: &Driver,    act: &Act,    before: Before,    ops: &[CottonOp],    workspace_id: &str,    at: &str,) -> Result<Vec<Change>> {    let actor = act.actor.to_wire();    let mut out = Vec::new();    for (versioned, row_id, was) in before.rows {        let now = read_versioned(db, versioned, &row_id)?;        let Some((before, after)) = moved(versioned, was.as_ref(), now.as_ref()) else {            continue;        };        let Some(write) = ops.iter().rev().find(|op| op.table == versioned.table && op.row_id == row_id) else {            continue;        };        let id = format!("h:{}", write.hlc);        let mut patch = Map::new();        patch.insert("id".into(), JsonValue::String(id.clone()));        patch.insert("workspace_id".into(), JsonValue::String(workspace_id.to_string()));        patch.insert("table_id".into(), JsonValue::String(versioned.table.to_string()));        patch.insert("kind".into(), JsonValue::String(versioned.kind.to_string()));        patch.insert("record_id".into(), JsonValue::String(row_id));        patch.insert("verb".into(), JsonValue::String(act.verb.clone()));        patch.insert("actor".into(), JsonValue::String(actor.clone()));        patch.insert("byline".into(), JsonValue::String(actor.clone()));        patch.insert("write_hlc".into(), JsonValue::String(write.hlc.clone()));        patch.insert("before".into(), before);        patch.insert("after".into(), after);        patch.insert("created_at".into(), JsonValue::String(at.to_string()));        out.push(Change::create(HISTORY_TABLE, &id, patch));    }    Ok(out)}/// Why a history row may not apply: it is the history of a record this file/// erased (`erase_of` answers the erase's `(stamp, author)`), so it parks/// `gone` as the record's own write does — history never outlives an erase./// The one row that stands is the erase's own note: a generic verb's row (no/// `write_hlc`) by the erase's author, stamped after it, in the erase's act.pub(crate) fn of_gone(    op: &CottonOp,    receipt: &crate::canonical::Receipt,    erase_of: impl Fn(&str) -> Result<Option<(String, String)>>,) -> Result<Option<String>> {    if op.table != HISTORY_TABLE || receipt.kind != crate::canonical::Kind::Create {        return Ok(None);    }    let field = |name: &str| receipt.fields.get(name).and_then(|v| v.as_str()).unwrap_or_default();    let (table, record) = (field("table_id"), field("record_id"));    if record.is_empty() {        return Ok(None);    }    let Some((erased_at, eraser)) = erase_of(record)? else {        return Ok(None);    };    let the_erases_own_note =        field("write_hlc").is_empty() && receipt.author == eraser && receipt.stamp.as_str() > erased_at.as_str();    if the_erases_own_note {        return Ok(None);    }    Ok(Some(format!(        "{} {HISTORY_TABLE} {} is the history of {table} {record}, which was erased, so it is never applied",        crate::erase::GONE_REFUSAL,        op.row_id    )))}/// A generic verb's own history row, with the act's actor written in.pub(crate) fn with_actor(change: &Change, actor: &str) -> Change {    let mut change = change.clone();    if change.table == HISTORY_TABLE && change.kind == Kind::Create {        if let Some(patch) = change.patch.as_mut() {            patch.entry("actor").or_insert_with(|| JsonValue::String(actor.to_string()));        }    }    change}/// Fields that live beside a record's own row and must be retained in its/// history. Money keeps its account and amount on the transaction itself.const BESIDE: &[(&str, &str, &str)] = &[];/// A versioned record as its history reads it: the row, and what it holds/// beside it ([`BESIDE`]).fn read_versioned(db: &Driver, versioned: &VersionedTable, row_id: &str) -> Result<Option<Map<String, JsonValue>>> {    let Some(mut row) = fold::read_row(db, versioned.table, row_id)? else {        return Ok(None);    };    for (_, field, sql) in BESIDE.iter().filter(|(table, _, _)| *table == versioned.table) {        let found = db.get(sql, &[rusqlite::types::Value::Text(row_id.to_string())])?;        let value = found            .as_ref()            .and_then(|found| found.text("v"))            .and_then(|text| serde_json::from_str::<JsonValue>(text).ok())            .unwrap_or(JsonValue::Null);        row.insert((*field).to_string(), value);    }    Ok(Some(row))}/// Before and after of the moved fields, or `None` when nothing moved.fn moved(    versioned: &VersionedTable,    was: Option<&Map<String, JsonValue>>,    now: Option<&Map<String, JsonValue>>,) -> Option<(JsonValue, JsonValue)> {    let fields = |row: &Map<String, JsonValue>| -> Map<String, JsonValue> {        row.iter()            .filter(|(column, value)| told(column) && !value.is_null() && !versioned.omit.contains(&column.as_str()))            .map(|(column, value)| (column.clone(), value.clone()))            .collect()    };    let (before, after) = match (was, now) {        (None, None) => return None,        (None, Some(now)) => (None, Some(fields(now))),        (Some(was), None) => (Some(fields(was)), None),        (Some(was), Some(now)) => {            let (was, now) = (fields(was), fields(now));            let columns: BTreeSet<&String> = was.keys().chain(now.keys()).collect();            let changed: Vec<&String> = columns.into_iter().filter(|c| was.get(*c) != now.get(*c)).collect();            if changed.is_empty() {                return None;            }            let pick = |row: &Map<String, JsonValue>| -> Map<String, JsonValue> {                changed.iter().map(|c| ((*c).clone(), row.get(*c).cloned().unwrap_or(JsonValue::Null))).collect()            };            (Some(pick(&was)), Some(pick(&now)))        }    };    let redacted = |fields: Option<Map<String, JsonValue>>| -> JsonValue {        let Some(mut fields) = fields else {            return JsonValue::Null;        };        for column in versioned.redact {            if let Some(value) = fields.remove(*column) {                let set = !value.is_null() && value.as_str() != Some("");                fields.insert(format!("has_{column}"), JsonValue::Bool(set));            }        }        JsonValue::Object(fields)    };    Some((redacted(before), redacted(after)))}/// Whether a column is something a person changed — not the row's identity,/// its database, its own timestamps or a sync stamp.fn told(column: &str) -> bool {    !column.starts_with('_') && !matches!(column, "id" | "workspace_id" | "created_at" | "updated_at")}