Cotton code
491 lines · 19.7 KB · RustRaw
//! The generic verbs over the BIN — the built-in table `bin`, whose engine//! (`bin`) keeps no table of its own. It is a VIEW: every row of every//! [`BinKind`] whose `trashed_at` is set, read off that kind's own table//! (`cotton_core::rules::bin::bin_source`), and written only through the//! bin's own verbs — `restore_from_bin`, and `empty_bin`'s eraser.//!//! - **A record** is `{title, kind, trashed_at, state}`: the title `list_bin`//!   shows (`bin::BinItems::title`), the kind, when it went in, and `"binned"`. A row of//!   a binnable kind that is out of the bin reads as `"restored"` with no//!   `trashed_at` — what a restore leaves, so the restore's change reads it.//! - **Its id is the binned row's own id, bare.** Every binnable row's id is a//!   UUID — a random one, or derived under its own table's name//!   (`derived_id("cotton_emails", …)`) — so two kinds never share one; a read//!   that ever finds the same id in two kinds refuses rather than guesses.//! - **list** answers every binned row, newest first (then by kind, then id),//!   with no cap of its own; the generic offset pages it. It takes `query`//!   and a `where` on its own columns, matched in memory (`table: "note"` is//!   a table's "Deleted · n" link), never one table's SQL narrowing.//! - **update** takes `{state: "restored"}` and nothing else: it is//!   `restore_from_bin {kind, id}`.//! - **delete** erases that one row for good, as `empty_bin` erases each//!   (`bin::erase`). Only a binned row can be erased. An event Google still//!   holds is asked gone: out of the bin at once, erased once the push has//!   cancelled it there. A conversation takes its//!   binned messages with it — the store would cascade them away with no//!   tombstone — and is refused while any of its messages is out of the bin.//!   Every change row naming an erased row goes with it (`bin::erase`, so//!   `empty_bin` does the same), and the erase's own change says only its//!   kind and state: the change log syncs, and nothing an erased row said may//!   outlive it there.//! - **undo**: a restore is undone by binning the record again//!   (`undo_restore`) — so a restore's receipt offers Undo — and an erase is//!   gone for good. Create, reorder and link are refused.//!//! A deleted record of a table a person defined, and a deleted group, wait//! here too — one rule for everything a person removes. They are rows of//! their own table (a made table's, or `cotton_groups`) with `deleted_at` set//! (`tables::binned`), listed as kind//! `record` and kind `group`; both are `list_bin`'s kind `record` to//! `restore_from_bin`, and a group comes back with its members. The//! definition's `kind` choices are `BinKind::ALL` and then those two (the//! guard `the_bin_view_names_every_kind_the_engine_bins`).use cotton_core::constants::BinKind;use cotton_core::definitions::TableDefinition;use cotton_core::rules::bin::bin_source;use cotton_core::records::{holds, matches_query, Condition, Data, Verb, WhereClause};use serde_json::{json, Value};use super::builtin::{self, Op};use super::{Page, Stored};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::bin;use crate::mcp::handlers::common::{rows, text, Valid};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Query};/// The bin table's id.pub const TABLE: &str = "bin";const BINNED: &str = "binned";const RESTORED: &str = "restored";/// Is this the bin table?pub fn is_bin(definition: &TableDefinition) -> bool {    definition.has_engine() && definition.id == TABLE}/// What a bin row is: a kind the bin engine keeps, or a soft-deleted row — a/// group, or a record of a table a person defined.#[derive(Clone, Copy, PartialEq, Eq)]enum Kind {    Engine(BinKind),    Group,    Record,}/// The kinds a soft-deleted group or record is listed as, after `BinKind::ALL`.pub const RECORD_KINDS: [&str; 2] = ["group", "record"];impl Kind {    fn as_str(self) -> &'static str {        match self {            Kind::Engine(kind) => kind.as_str(),            Kind::Group => RECORD_KINDS[0],            Kind::Record => RECORD_KINDS[1],        }    }}/// One row of a binnable kind, binned or not.struct Row {    kind: Kind,    /// The table the record is a row of, so the Bin opens the record's own    /// page — everything it held, read only, with Restore — never this row's.    table: String,    id: String,    title: String,    trashed_at: Option<String>,    /// A made table's own name, and a date its record is titled by (`Binned`).    table_name: Option<String>,    title_at: Option<String>,}impl Row {    fn stored(&self) -> Stored {        let mut data = Data::new();        data.insert("title".into(), Value::from(self.title.clone()));        if let Some(name) = &self.table_name {            data.insert("table_name".into(), Value::from(name.clone()));        }        if let Some(at) = &self.title_at {            data.insert("title_at".into(), Value::from(at.clone()));        }        data.insert("kind".into(), Value::from(self.kind.as_str()));        data.insert("table".into(), Value::from(self.table.clone()));        if let Some(at) = &self.trashed_at {            data.insert("trashed_at".into(), Value::from(at.clone()));        }        let state = if self.trashed_at.is_some() {            BINNED        } else {            RESTORED        };        data.insert("state".into(), Value::from(state));        Stored {            id: self.id.clone(),            data,            created_at: None,            updated_at: None,            deleted_at: None,            byline: None,        }    }}fn kind_rank(kind: Kind) -> usize {    match kind {        Kind::Engine(kind) => BinKind::ALL            .iter()            .position(|known| *known == kind)            .unwrap_or(usize::MAX),        Kind::Group => BinKind::ALL.len(),        Kind::Record => BinKind::ALL.len() + 1,    }}/// A soft-deleted group or record as a bin row.fn record_row(binned: super::Binned) -> Row {    Row {        kind: if binned.table == super::groups::TABLE {            Kind::Group        } else {            Kind::Record        },        table: binned.table,        id: binned.id,        title: binned.title,        trashed_at: Some(binned.deleted_at).filter(|at| !at.is_empty()),        table_name: binned.table_name,        title_at: binned.title_at,    }}/// Every row of `kind` the query narrows to, each named as the bin names it —/// only the bin's own items of them when `only_items` (`bin::BinItems`).fn rows_of(    ctx: &Ctx<'_>,    kind: BinKind,    items: &bin::BinItems,    only_items: bool,    narrow: impl Fn(Query) -> Query,) -> Valid<Vec<Row>> {    let source = bin_source(kind);    let query = narrow(Query::on(source.table).columns(&bin::BinItems::columns(kind)));    Ok(rows(ctx, &query)?        .iter()        // One whose erase is asked is gone, from the bin and from a read alike.        .filter(|row| !bin::BinItems::asked_gone(kind, row))        .filter(|row| !only_items || items.lists(kind, row))        .map(|row| Row {            kind: Kind::Engine(kind),            table: kind.as_str().to_string(),            id: text(row, "id").unwrap_or_default(),            title: items.title(kind, row),            trashed_at: text(row, "trashed_at"),            table_name: None,            title_at: None,        })        .collect())}/// The one row of a binnable kind with this id, binned or not.fn find(ctx: &Ctx<'_>, id: &str) -> Valid<Option<Row>> {    let mut found = Vec::new();    let items = bin::BinItems::read(ctx, &BinKind::ALL)?;    for kind in BinKind::ALL {        found.extend(rows_of(ctx, kind, &items, false, |query| query.eq("id", id.to_string()))?);    }    found.extend(super::bin_record(ctx, id)?.map(record_row));    if found.len() > 1 {        let kinds: Vec<&str> = found.iter().map(|row| row.kind.as_str()).collect();        return Err(ToolFailure::new(format!(            "That record is a row of {} at once, so the bin cannot say which one is meant",            kinds.join(" and ")        )));    }    Ok(found.pop())}pub(super) fn read_one(ctx: &Ctx<'_>, id: &str) -> Valid<Option<Stored>> {    Ok(find(ctx, id)?.map(|row| row.stored()))}pub(super) fn list(    ctx: &Ctx<'_>,    definition: &TableDefinition,    project: Option<&str>,    query_text: Option<&str>,    clauses: &[WhereClause],    offset: i64,    limit: i64,) -> Valid<Page> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    if project.is_some() {        return Err(ToolFailure::new(format!(            "{} do not belong to projects",            definition.plural        )));    }    let mut binned = Vec::new();    // A table's "Deleted · n" link (`{table: "meeting"}`) reads that kind's    // binned rows alone: it drew after the list's first page by reading the    // binned rows of every kind in the file, page after page (295 F row 81).    let named = clauses.iter().find_map(|clause| match (clause.column.as_str(), &clause.condition) {        ("table", Condition::Is(Value::String(table))) => Some(table.as_str()),        _ => None,    });    let kinds: Vec<BinKind> = BinKind::ALL.into_iter().filter(|kind| named.is_none_or(|table| kind.as_str() == table)).collect();    let items = bin::BinItems::read(ctx, &kinds)?;    for kind in kinds {        binned.extend(rows_of(ctx, kind, &items, true, |query| {            query.filter(Filter::NotNull("trashed_at".to_string()))        })?);    }    // A binned conversation is listed once, not again as each of its    // messages (`list_bin` counts the same way).    if binned.iter().any(|row| row.kind == Kind::Engine(BinKind::Email)) {        let inside = bin::messages_of_binned_conversations(ctx)?;        binned.retain(|row| row.kind != Kind::Engine(BinKind::Email) || !inside.contains(&row.id));    }    // Groups and made tables' records, unless the link names a built-in kind:    // none of them is filed under one (a made table's id is its own), and    // reading them all was most of Todos' "Deleted · n" after every write.    if named.is_none_or(|table| table == super::groups::TABLE || !BinKind::ALL.iter().any(|kind| kind.as_str() == table)) {        binned.extend(super::binned(ctx, i64::MAX)?.into_iter().map(record_row));    }    // The store writes ISO UTC, so a string comparison IS chronological.    binned.sort_by(|a, b| {        b.trashed_at            .cmp(&a.trashed_at)            .then(kind_rank(a.kind).cmp(&kind_rank(b.kind)))            .then(a.id.cmp(&b.id))    });    let listed: Vec<Stored> = binned        .iter()        .map(Row::stored)        .filter(|stored| query_text.is_none_or(|words| matches_query(definition, &stored.data, words)))        // The whole list is in memory, so a `where` narrows it here, on the        // bin's own columns: `{table: "note"}` is what a table's        // "Deleted · n" link reads — the way back where the record was.        .filter(|stored| clauses.iter().all(|clause| holds(&stored.data, clause, &zone)))        .collect();    // The whole list is in memory, so its count is its length.    let total = listed.len() as i64;    let mut records: Vec<Stored> = listed        .into_iter()        .skip(usize::try_from(offset).unwrap_or(usize::MAX))        .take(usize::try_from(limit + 1).unwrap_or(usize::MAX))        .collect();    let more = records.len() as i64 > limit;    records.truncate(limit as usize);    Ok(Page {        records,        more,        total,    })}/// Every existing tool a generic verb over the bin stands in for.pub(super) fn tools(tool: &str) -> Vec<&'static str> {    match tool {        "list_records" | "get_record_by_table" => vec!["list_bin"],        _ => Vec::new(),    }}/// The tools a write's plan calls — what `builtin::plan` answers for the bin.pub(super) fn plan(op: Op<'_>) -> Vec<&'static str> {    match op {        Op::Update(_) => vec!["restore_from_bin"],        Op::Delete => vec!["empty_bin"],        Op::Create(_) | Op::Restore | Op::Reorder => Vec::new(),    }}/// Why a change of `verb` to the bin cannot be undone, or `None` when it can:/// a restore is undone by binning the record again ([`undo_restore`]); an/// erase is gone for good.pub(super) fn undo_refusal(verb: Verb) -> Option<String> {    match verb {        Verb::Update => None,        Verb::Link => Some("the bin links nothing".to_string()),        Verb::Delete => Some("an erased record is gone for good".to_string()),        Verb::Create | Verb::Restore => {            Some("a record goes into the bin from its own table, never through the bin".to_string())        }        Verb::Reorder => Some("the bin has no order of its own".to_string()),        Verb::Move | Verb::MoveIn => {            Some("undoing a move needs the cross-database coordinator".to_string())        }    }}/// The Undo of a restore through the bin: the record goes back into the bin/// as it went in the first time — its kind's own write, when it went in/// (`patch`'s `trashed_at`), and its edited time untouched, so the bin's list/// and the record's own list both read as they did before the restore.pub(super) fn undo_restore(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, patch: &Data) -> Valid<()> {    if patch.get("state").and_then(Value::as_str) != Some(BINNED) {        return Err(ToolFailure::new(format!(            "this change cannot be undone: the {} only undoes a restore",            definition.plural.to_lowercase()        )));    }    let row = find(ctx, id)?.ok_or_else(|| super::not_found(definition, id))?;    if row.trashed_at.is_some() {        return Err(ToolFailure::new(            "That record is already back in the bin, so there is nothing to undo",        ));    }    let went_in = patch        .get("trashed_at")        .and_then(Value::as_str)        .map(str::to_string)        .unwrap_or_else(|| crate::mcp::handlers::common::now_iso(ctx));    match row.kind {        Kind::Group | Kind::Record => super::bin_again(ctx, id)?,        // Mail goes back in through the mailbox's own writer, which queues        // Gmail's trash as the restore queued its untrash.        Kind::Engine(kind @ (BinKind::Email | BinKind::EmailThread)) => {            bin::bin_mail_again(ctx, kind, id)?;        }        Kind::Engine(kind) => {            let mut back = serde_json::Map::new();            back.insert("trashed_at".to_string(), Value::from(went_in));            crate::mcp::handlers::common::update_row(ctx, bin_source(kind).table, id, back)?;            ctx.commit()?;        }    }    ctx.audit("undo", &format!("bin: {} {id} binned again", row.kind.as_str()));    Ok(())}pub(super) fn create(definition: &TableDefinition) -> ToolFailure {    ToolFailure::new(format!(        "Nothing is created in the {}: a record goes in when it is binned from its own table",        definition.plural.to_lowercase()    ))}/// `update_record` on the bin: `{state: "restored"}` is `restore_from_bin`.pub(super) fn update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let restore = patch.len() == 1 && patch.get("state").and_then(Value::as_str) == Some(RESTORED);    if !restore {        return Err(ToolFailure::new(format!(            "The {} takes one change, state {RESTORED:?}, which puts the record back where it \             was; everything else about it is changed in its own table",            definition.plural.to_lowercase()        )));    }    let row = find(ctx, id)?.ok_or_else(|| super::not_found(definition, id))?;    // A group and a made table's record are both `restore_from_bin`'s    // `record`: it knows a group by its row and brings its members back.    let kind = match row.kind {        Kind::Engine(kind) => kind.as_str(),        Kind::Group | Kind::Record => super::BIN_KIND,    };    builtin::call(        ctx,        definition,        "restore_from_bin",        bin::restore_from_bin,        json!({ "kind": kind, "id": id }),    )    .map(|_| ())}/// What a restore through the bin says when it brought a moved occurrence/// back as an event of its own (`bin::restore_from_bin`): the row's bin title/// lost its day, because it left its series — "Restored Swimming, Thu 8 Oct,/// as its own event", never a bare "Changed Swimming".pub(super) fn restored_said(ctx: &Ctx<'_>, definition: &TableDefinition, verb: Verb, before: &Value, record: Option<&Value>) -> Option<String> {    if !is_bin(definition) || verb != Verb::Update {        return None;    }    let record = record?;    if record.get("kind")?.as_str()? != BinKind::Event.as_str() || record.get("state")?.as_str()? != RESTORED {        return None;    }    let title = record.get("title")?.as_str()?;    // The bin title was listed in the database's `bin.occurrence`, so its day    // is read back out of the same words, and said in its own.    let lines = crate::presentation::line_rows(ctx.db(), ctx.workspace_id);    let day = bin::occurrence_day(before.get("title")?.as_str()?, title, &lines)?;    Some(bin::restored_as_own_event(title, day, &lines))}/// `delete_record` on the bin: erase that one row for good.pub(super) fn delete(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    // Unconditional, and asked of the context alone: erasing from the bin is    // the owner's own app's, whatever the catalogue says of any tool.    if !ctx.is_owner_app() {        return Err(ToolFailure::new(            "only the owner's own app can erase what is in the bin",        ));    }    let row = find(ctx, id)?.ok_or_else(|| super::not_found(definition, id))?;    if row.trashed_at.is_none() {        return Err(ToolFailure::new(            "That record is not in the bin, so there is nothing to erase; bin it from its own table first",        ));    }    let Kind::Engine(kind) = row.kind else {        super::erase_one_binned(ctx, id)?;        ctx.audit(            "delete_record",            &format!("bin: {} {id} erased", row.kind.as_str()),        );        return Ok(());    };    if kind == BinKind::EmailThread {        // A message cannot outlive its conversation: the store cascades it        // away with no tombstone, so its binned messages are erased first, each        // with its own, and one still out of the bin keeps the conversation.        let messages = Query::on(bin_source(BinKind::Email).table)            .columns(&["id", "trashed_at"])            .eq("thread_id", id.to_string());        let mut binned = Vec::new();        let mut kept = 0;        for message in rows(ctx, &messages)? {            match (text(&message, "id"), text(&message, "trashed_at")) {                (Some(message_id), Some(_)) => binned.push(message_id),                _ => kept += 1,            }        }        if kept > 0 {            return Err(ToolFailure::new(format!(                "this conversation still has {kept} message(s) out of the bin; erasing it would \                 erase them too, so bin them first"            )));        }        bin::erase(ctx, BinKind::Email, &binned)?;    }    bin::erase(ctx, kind, &[id.to_string()])?;    ctx.audit(        "delete_record",        &format!("bin: {} {id} erased", row.kind.as_str()),    );    Ok(())}/// What an erase's change says the row was: its kind and state, never its/// title or when it went in — the change log syncs, and an erased password's/// name must not outlive the password.pub(super) fn erased_values(data: &Data) -> Data {    data.iter()        .filter(|(key, _)| matches!(key.as_str(), "kind" | "state"))        .map(|(key, value)| (key.clone(), value.clone()))        .collect()}/// An erase is never undone.pub(super) fn restore() -> ToolFailure {    ToolFailure::new(undo_refusal(Verb::Delete).unwrap_or_default())}