Cotton code
164 lines · 6.8 KB · RustRaw
//! The TAKE-BACK: Undo of an add removes the record, as if it was never made.//!//! A take-back IS an erase ([`crate::erase`]) whose reason is [`REASON`]: one//! erase path, no second conflict rule. It is signed, travels as any erase//! travels, and every device that folds it takes the record and its owned//! descendants out for good; a peer's concurrent edit parks `gone`.//!//! What makes it a take-back is WHEN it may be minted, judged once, on the//! device that asks ([`refusal`]) — a receiver cannot judge "nothing changed//! since" as the asker saw it, so it folds the erase as it folds any other://!//! 1. the same person, at the same device, made the record and asks now;//! 2. nothing has changed it since: every receipt that writes at the record,//!    or names it (an edit, a link, a child record, a change-log row), was//!    minted by the add's own act;//! 3. the caller is the add's own receipt asking Undo — the store sees this//!    as the act's own bound (`through`), which only that receipt holds.//!//! `mint`'s kinds hook runs the same judgement on every//! [`crate::mint::Delete::TakeBack`], and refuses an erase that borrows the//! reason, so no call site can take back what the rule would keep. When it//! refuses, the caller falls back to the table's own put-away state.use rusqlite::types::Value as SqlValue;use crate::actor::Actor;use crate::driver::Driver;use crate::error::Result;use crate::fact_hooks::author_device;use crate::receipts::pages::{Pages, Side};pub(crate) const RELATED: &str =    "hlc >= ? AND NOT (tbl = ? AND row_id = ?) AND instr(CAST(bytes AS TEXT), ?) > 0";/// The stamp RELATED's first argument names: the add's own.fn args_born(args: &[SqlValue]) -> &str {    match args.first() {        Some(SqlValue::Text(born)) => born.as_str(),        _ => "",    }}/// The erase reason a take-back's receipt carries, and `_gone.reason` keeps.pub const REASON: &str = "taken_back";/// Why an add may not be taken back.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Refusal {    /// The one asking is not a person at a device's screen.    NotAPerson,    /// The record was made by another person or at another device.    MadeElsewhere,    /// Something wrote at the record, or named it, after the add's own act.    ChangedSince { table: String, row_id: String },    /// The record is not here to take back.    NotHere,}impl std::fmt::Display for Refusal {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        match self {            Refusal::NotAPerson => {                write!(f, "only the person who added a record takes the add back")            }            Refusal::MadeElsewhere => write!(                f,                "the record was added by someone else or on another device"            ),            Refusal::ChangedSince { table, row_id } => {                write!(                    f,                    "the record has changed since it was added ({table} {row_id})"                )            }            Refusal::NotHere => write!(f, "the record is not here"),        }    }}/// Why `asker` may not take back the add of `table`'s `row_id`, or `None`/// when all the conditions hold. `through` is the stamp of the last receipt/// of the add's own act: every receipt at the record, or naming it, must be/// the adding author's, under the adding actor, no later than it.pub fn refusal(    db: &Driver,    asker: &Actor,    table: &str,    row_id: &str,    through: &str,) -> Result<Option<Refusal>> {    if !matches!(asker, Actor::Owner(_) | Actor::Member(_)) {        return Ok(Some(Refusal::NotAPerson));    }    let own = db.get(        "SELECT hlc, author, actor, kind FROM _writes WHERE tbl = ? AND row_id = ? ORDER BY hlc LIMIT 1",        &[SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())],    )?;    let Some(create) = own        .as_ref()        .filter(|row| row.text("kind") == Some("create"))    else {        return Ok(Some(Refusal::NotHere));    };    let born = create.text("hlc").unwrap_or_default().to_string();    let author = create.text("author").unwrap_or_default().to_string();    let actor = create.text("actor").unwrap_or_default().to_string();    // 1. The same person and device: the add was minted here, by this file's    // own device, under the very actor that asks now.    let here = author_device(db, &crate::mint::file_author(db)?)?;    if actor != asker.to_wire() || here.is_none() || author_device(db, &author)? != here {        return Ok(Some(Refusal::MadeElsewhere));    }    if through < born.as_str() || crate::fold::author_of(through) != Some(author.as_str()) {        return Ok(Some(Refusal::MadeElsewhere));    }    // 2. Nothing changed since: a receipt at the record, or naming it, that    // is not the add's own act is an edit, a link or a child record.    let changed = |row: &crate::driver::Row| {        let of_the_add = row.text("author") == Some(author.as_str())            && row.text("actor") == Some(actor.as_str())            && row.text("hlc").is_some_and(|hlc| hlc <= through);        (!of_the_add).then(|| Refusal::ChangedSince {            table: row.text("tbl").unwrap_or(table).to_string(),            row_id: row.text("row_id").unwrap_or(row_id).to_string(),        })    };    // Preserve the judgement's priority: edits at this record are reported    // before a receipt elsewhere that names it (such as its history row).    let mut own = Pages::of_row(table, row_id);    while let Some(rows) = own.next(db, "1", &[])? {        if let Some(refusal) = rows.iter().find_map(&changed) {            return Ok(Some(refusal));        }    }    let mut pages = Pages::new(Side::Writes);    let args = [        SqlValue::Text(born),        SqlValue::Text(table.to_string()),        SqlValue::Text(row_id.to_string()),        SqlValue::Text(row_id.to_string()),    ];    while let Some(rows) = pages.next(db, RELATED, &args)? {        // An implied receipt (receipts/implied.rs) keeps no bytes for RELATED to search: its bytes are made        // again from its row, and searched as RELATED searches the bytes it held.        let mut related = Vec::new();        for row in &rows {            let named = row.int("matches") == Some(1)                || (row.int("implied").is_some()                    && row.text("hlc").is_some_and(|hlc| hlc >= args_born(&args))                    && !(row.text("tbl") == Some(table) && row.text("row_id") == Some(row_id))                    && crate::receipts::implied::bytes_of(db, row)?                        .is_some_and(|bytes| String::from_utf8_lossy(&bytes).contains(row_id)));            if named {                related.push(row);            }        }        if let Some(refusal) = related.into_iter().find_map(&changed) {            return Ok(Some(refusal));        }    }    Ok(None)}