Cotton code
806 lines · 34.9 KB · RustRaw
//! The bin's three verbs — `list_bin`, `restore_from_bin`, `empty_bin`.//!//! KIND-GENERIC from day one and driven off core's [`bin_source`], which is//! TOTAL over [`BinKind`] by the `match` rather than by a load-time assertion://! a kind missing from a read registry reads as "there is none of that" to//! every caller, and in a bin that means the owner's mail is gone with no//! trace of where it went.//!//! A deleted record of a table a person defined waits here too, as kind//! `record` (`tables::binned`): it is soft-deleted in `cotton_records`, not a//! `BinKind` row, because every such table shares the one generic storage.//!//! `empty_bin` alone erases. One delete per row, deliberately: a delete is a//! tombstone every other device has to fold, and a bulk statement would write//! none of them.use std::collections::HashSet;use cotton_core::constants::BinKind;use cotton_core::rules::bin::{bin_source, bin_title, title_column, RestoreValue, LINES};use cotton_core::rules::shell_lines::LineRow;use cotton_core::rules::email_state::EmailStatePatch;use cotton_core::records::page::weekday_date_of as weekday_date;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::tables;use crate::mcp::handlers::common::{    bounded_limit, fail, iso_of_ms, now_ms, MODDATETIME_TABLES, optional_string, put, require_uuid, rows, text,    update_row, Valid,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};/// Whether the Bin's tile is on Home in this database — a delete's receipt is/// worded by it (`receipt::binned_said`): "in the Bin" names a tile the/// person can see.pub fn bin_shown(ctx: &Ctx<'_>) -> Valid<bool> {    use cotton_store::link_rule::FileKind;    let personal = !matches!(ctx.file_kind()?, FileKind::Shared);    let workspace_id = ctx.workspace_id.to_string();    let manual = crate::home_arrangement::stored(ctx.db(), &workspace_id).map_err(ToolFailure::new)?;    let home = crate::home_arrangement::home(ctx.db(), &workspace_id, manual.as_ref(), personal).map_err(ToolFailure::new)?;    Ok(home.shows(&cotton_core::rules::home_arrangement::tool_view("bin")))}pub fn handlers() -> HandlerGroup {    &[        ("list_bin", list_bin),        ("restore_from_bin", restore_from_bin),        ("empty_bin", empty_bin),    ]}/// The shared put-away for a person-made record. Only its Bin marker changes:/// the row, its owned records and the receipts that made it wait together.pub(crate) fn put_away(ctx: &mut Ctx<'_>, kind: BinKind, id: &str) -> Valid<()> {    let source = bin_source(kind);    let query = Query::on(source.table).columns(&["id", "trashed_at"]).eq("id", id.to_owned());    let row = rows(ctx, &query)?.into_iter().next()        .ok_or_else(|| ToolFailure::new(format!("no such {kind} in this workspace")))?;    if text(&row, "trashed_at").is_some() {        return Ok(());    }    let mut patch = Map::new();    patch.insert("trashed_at".into(), Value::from(super::common::now_iso(ctx)));    // Going away is not an edit of the person's words. Restore must put    // every stored column back, including its original edited time.    if let Some(edited) = edited_at(ctx, source.table, id)? {        patch.insert("updated_at".into(), Value::from(edited));    }    update_row(ctx, source.table, id, patch)?;    ctx.commit()}const DAY_MS: i64 = 24 * 60 * 60 * 1000;/// The binned messages a binned conversation stands in for: binning a/// conversation bins every message in it and restoring it brings them back,/// so the bin lists and counts the conversation once, never each message/// again. A message binned on its own, in a conversation still out, is not/// one of these. The one answer `list_bin` and the bin table both read.pub(crate) fn messages_of_binned_conversations(ctx: &Ctx<'_>) -> Valid<HashSet<String>> {    let threads = Query::on(bin_source(BinKind::EmailThread).table)        .columns(&["id"])        .filter(Filter::NotNull("trashed_at".to_string()));    let conversations: HashSet<String> = rows(ctx, &threads)?.iter().filter_map(|row| text(row, "id")).collect();    if conversations.is_empty() {        return Ok(HashSet::new());    }    let messages = Query::on(bin_source(BinKind::Email).table)        .columns(&["id", "thread_id"])        .filter(Filter::NotNull("trashed_at".to_string()));    Ok(rows(ctx, &messages)?        .iter()        .filter(|row| text(row, "thread_id").is_some_and(|thread| conversations.contains(&thread)))        .filter_map(|row| text(row, "id"))        .collect())}/// Which binned rows wait in the bin as items of their own, and what each is/// called there — the one answer `list_bin`, `empty_bin` and the bin table/// read.////// A moved occurrence of a series deleted on its own IS one: it is trashed,/// not dropped, and still claims its instant of the series, so it is the/// record of that cancellation — listed as "<title> on <day>", brought back by/// Restore, and erased with its instant left cancelled on the series/// (`events::keep_occurrence_cancelled`). One whose series is binned too is/// not: the binned series stands for it, and its erase takes it.////// An event whose erase was asked while Google still held it/// (`erase_requested_at`, [`erase`]) is not one either: the person asked it/// gone, so it is gone from the bin at once, and the push erases it for good/// once it has cancelled it at Google.pub(crate) struct BinItems {    binned_series: HashSet<String>,    zone: String,    lines: Vec<LineRow>,    dates: cotton_core::records::page::DateWords,}impl BinItems {    pub(crate) fn read(ctx: &Ctx<'_>, kinds: &[BinKind]) -> Valid<Self> {        let mut binned_series = HashSet::new();        if kinds.contains(&BinKind::Event) {            let query = Query::on(bin_source(BinKind::Event).table)                .columns(&["id"])                .filter(Filter::NotNull("trashed_at".to_string()));            binned_series = rows(ctx, &query)?.iter().filter_map(|row| text(row, "id")).collect();        }        let zone = super::common::workspace_timezone_or_null(ctx)?.unwrap_or_else(|| "UTC".to_string());        let lines = crate::presentation::line_rows(ctx.db(), ctx.workspace_id);        let dates = cotton_core::records::page::DateWords::of_rows(&lines);        Ok(BinItems { binned_series, zone, lines, dates })    }    /// The columns a row of `kind` is read with to be listed.    pub(crate) fn columns(kind: BinKind) -> Vec<&'static str> {        let mut columns = vec!["id", title_column(kind), "trashed_at"];        if kind == BinKind::Event {            columns.extend(["series_id", "starts_at", "erase_requested_at"]);        }        if kind == BinKind::Message {            columns.push("meta");        }        columns    }    /// A message the disappearing timer put in the Bin, or a timer line: never an item of this Bin, so never emptied    /// from it. It leaves only by his own act on the chat's line (`chat.timer.erase`); a timer line never leaves while    /// its chat stands (ABSENCE 7, item 1).    pub(crate) fn timer_held(kind: BinKind, row: &Map<String, Value>) -> bool {        if kind != BinKind::Message {            return false;        }        let meta = match row.get("meta") {            Some(Value::String(text)) => serde_json::from_str::<Value>(text).unwrap_or(Value::Null),            Some(value) => value.clone(),            None => Value::Null,        };        meta.pointer("/cotton/timer_binned").is_some_and(|v| !v.is_null()) || meta.pointer("/cotton/timer").is_some_and(|v| !v.is_null())    }    /// Was this row's erase asked already? Then it is not in the bin, nor    /// anywhere else a person reads, whatever the push has yet to do.    pub(crate) fn asked_gone(kind: BinKind, row: &Map<String, Value>) -> bool {        kind == BinKind::Event && text(row, "erase_requested_at").is_some()    }    /// Is this binned row of `kind` an item of its own?    pub(crate) fn lists(&self, kind: BinKind, row: &Map<String, Value>) -> bool {        if Self::asked_gone(kind, row) || Self::timer_held(kind, row) {            return false;        }        kind != BinKind::Event || !text(row, "series_id").is_some_and(|series| self.binned_series.contains(&series))    }    /// What the bin calls this row: a moved occurrence by its day too.    pub(crate) fn title(&self, kind: BinKind, row: &Map<String, Value>) -> String {        let title = bin_title(kind, text(row, title_column(kind)).as_deref(), &self.lines);        let day = (kind == BinKind::Event && text(row, "series_id").is_some())            .then(|| text(row, "starts_at"))            .flatten()            .and_then(|at| weekday_date(&at, &self.zone, &self.dates));        match day {            Some(day) => occurrence_title(&title, &day, &self.lines),            None => title,        }    }}/// What the bin calls a moved occurrence: its title, on its day — line/// `occurrence` of set `bin`, the database's row first.fn occurrence_title(title: &str, day: &str, lines: &[LineRow]) -> String {    cotton_core::rules::shell_lines::resolve(LINES, OCCURRENCE, lines, &[("title", title), ("day", day)])        .expect("the bin line set ships occurrence")}/// The line a moved occurrence's bin title is.const OCCURRENCE: &str = "occurrence";/// The day a bin title of [`occurrence_title`] names, given the title alone:/// the same line with only the title filled, read around its `{day}`.pub(crate) fn occurrence_day<'a>(listed: &'a str, title: &str, lines: &[LineRow]) -> Option<&'a str> {    let template = cotton_core::rules::shell_lines::resolve(LINES, OCCURRENCE, lines, &[("title", title)])?;    let (before, after) = template.split_once("{day}")?;    listed.strip_prefix(before)?.strip_suffix(after).filter(|day| !day.is_empty())}/// What a restore of a moved occurrence Google has already let go says: it/// came back as an event of its own on its day ([`restore_from_bin`]) — line/// `restored_own_event` of set `bin`, the database's row first.pub(crate) fn restored_as_own_event(title: &str, day: &str, lines: &[LineRow]) -> String {    cotton_core::rules::shell_lines::resolve(LINES, RESTORED_OWN_EVENT, lines, &[("title", title), ("day", day)])        .expect("the bin line set ships restored_own_event")}/// The line a restore that made a moved occurrence its own event says.const RESTORED_OWN_EVENT: &str = "restored_own_event";/// Does Google Calendar still hold this binned event — deleted here, its/// cancel not yet pushed? Its erase is then ASKED, not refused ([`erase`]):/// erasing it now would leave it at Google with nothing here to name it, so/// the push erases it for good the moment its cancel has reached Google.fn still_at_google(ctx: &Ctx<'_>, id: &str) -> Valid<bool> {    let query = Query::on(bin_source(BinKind::Event).table)        .columns(&["id", "gcal_id"])        .eq("id", id.to_string());    Ok(rows(ctx, &query)?.iter().any(|row| text(row, "gcal_id").is_some()))}/// The binned moved occurrence a restore makes an event of its own: one the/// push has cancelled at Google, so its series skips its instant there and/// here (the instant is in the series' `exdates`) and its Google link is/// gone. Brought back as an occurrence of that series it would stand for an/// instance Google no longer has; it comes back on its day as itself, and the/// push makes it at Google as a new event. `None` for any other row — a/// moved occurrence Google still holds, or one it never had, is restored as/// it was.fn let_go_occurrence(ctx: &Ctx<'_>, id: &str) -> Valid<Option<(String, String)>> {    let table = bin_source(BinKind::Event).table;    let query = Query::on(table)        .columns(&["id", "title", "starts_at", "series_id", "original_starts_at", "gcal_id"])        .eq("id", id.to_string());    let Some(row) = rows(ctx, &query)?.into_iter().next() else {        return Ok(None);    };    let (Some(series), Some(claims), None) =        (text(&row, "series_id"), text(&row, "original_starts_at"), text(&row, "gcal_id"))    else {        return Ok(None);    };    let series = Query::on(table).columns(&["id", "exdates"]).eq("id", series);    let skipped = rows(ctx, &series)?.into_iter().next().is_some_and(|series| {        let exdates = match series.get("exdates") {            Some(Value::String(raw)) => serde_json::from_str::<Value>(raw).unwrap_or(Value::Null),            Some(value) => value.clone(),            None => Value::Null,        };        exdates.as_array().is_some_and(|list| list.iter().any(|at| at.as_str() == Some(claims.as_str())))    });    if !skipped {        return Ok(None);    }    let zone = super::common::workspace_timezone_or_null(ctx)?.unwrap_or_else(|| "UTC".to_string());    let lines = crate::presentation::line_rows(ctx.db(), ctx.workspace_id);    let title = bin_title(BinKind::Event, text(&row, title_column(BinKind::Event)).as_deref(), &lines);    let dates = cotton_core::records::page::DateWords::of_rows(&lines);    let day = text(&row, "starts_at").and_then(|at| weekday_date(&at, &zone, &dates)).unwrap_or_default();    Ok(Some((title, day)))}/// Every kind, or the one the call named — `kindsFor`.fn kinds_for(kind: Option<BinKind>) -> Vec<BinKind> {    match kind {        Some(kind) => vec![kind],        None => BinKind::ALL.to_vec(),    }}fn bin_kinds_sentence() -> String {    BinKind::ALL        .iter()        .map(|kind| kind.as_str())        .chain([tables::BIN_KIND])        .collect::<Vec<_>>()        .join(", ")}/// Did the call name kind `record` — a user table's deleted records?fn names_records(args: &Map<String, Value>) -> bool {    optional_string(args, "kind").as_deref() == Some(tables::BIN_KIND)}/// `binKindArg` — the one reader both the required and the optional form use.fn bin_kind_arg(args: &Map<String, Value>, required: bool) -> Valid<Option<BinKind>> {    let Some(raw) = optional_string(args, "kind") else {        if required {            return fail(format!("kind must be one of {}", bin_kinds_sentence()));        }        return Ok(None);    };    match BinKind::parse(&raw) {        Some(kind) => Ok(Some(kind)),        None => fail(format!(            "kind must be one of {} — every other kind has a different answer than a bin",            bin_kinds_sentence()        )),    }}pub struct ListBinArgs {    pub kind: Option<BinKind>,    pub limit: i64,}pub fn validate_list_bin(args: &Map<String, Value>) -> Valid<ListBinArgs> {    Ok(ListBinArgs {        kind: bin_kind_arg(args, false)?,        limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST),    })}pub struct RestoreFromBinArgs {    pub kind: BinKind,    pub id: String,}pub fn validate_restore_from_bin(args: &Map<String, Value>) -> Valid<RestoreFromBinArgs> {    let kind = bin_kind_arg(args, true)?        .ok_or_else(|| ToolFailure::new(format!("kind must be one of {}", bin_kinds_sentence())))?;    // A picture is addressed by its bytes ("photo:" and its hash), never a uuid.    let id = match kind {        BinKind::Photo | BinKind::Video => {            crate::mcp::handlers::media_tools::require_media_id(args, kind.as_str())?        }        _ => require_uuid(args, "id")?,    };    Ok(RestoreFromBinArgs { kind, id })}pub struct EmptyBinArgs {    pub kind: Option<BinKind>,    pub older_than_days: Option<i64>,}pub fn validate_empty_bin(args: &Map<String, Value>) -> Valid<EmptyBinArgs> {    let kind = bin_kind_arg(args, false)?;    let older_than_days = match args.get("olderThanDays") {        None => None,        Some(raw) => {            let whole = raw                .as_f64()                .filter(|value| value.fract() == 0.0)                .map(|value| value as i64)                .filter(|value| (1..=3650).contains(value));            match whole {                Some(days) => Some(days),                None => {                    return fail("olderThanDays must be a whole number of days, 1 to 3650");                }            }        }    };    Ok(EmptyBinArgs {        kind,        older_than_days,    })}pub fn list_bin(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let records_only = names_records(args);    let args = if records_only {        ListBinArgs {            kind: None,            limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST),        }    } else {        validate_list_bin(args)?    };    let mut entries: Vec<(String, Value)> = Vec::new();    let mut counts = Map::new();    let mut capped = false;    let kinds = if records_only {        Vec::new()    } else {        kinds_for(args.kind)    };    // Listed with its conversation, a binned message is not listed (or    // counted) again — the bin table's list leaves out the same ones.    let inside = if kinds.contains(&BinKind::Email) && kinds.contains(&BinKind::EmailThread) {        messages_of_binned_conversations(ctx)?    } else {        HashSet::new()    };    if records_only || args.kind.is_none() {        let found = tables::binned(ctx, args.limit)?;        capped |= found.len() as i64 == args.limit;        counts.insert(            tables::BIN_KIND.to_string(),            Value::from(found.len() as i64),        );        for record in found {            let mut entry = Map::new();            entry.insert("kind".to_string(), Value::from(tables::BIN_KIND));            entry.insert("table".to_string(), Value::from(record.table));            entry.insert("id".to_string(), Value::from(record.id));            entry.insert("title".to_string(), Value::from(record.title));            entry.insert(                "trashedAt".to_string(),                Value::from(record.deleted_at.clone()),            );            entries.push((record.deleted_at, Value::Object(entry)));        }    }    let items = BinItems::read(ctx, &kinds)?;    for kind in kinds {        let source = bin_source(kind);        let query = Query::on(source.table)            .columns(&BinItems::columns(kind))            .filter(Filter::NotNull("trashed_at".to_string()))            .order_by("trashed_at", Order::Desc)            .limit(args.limit);        let found = rows(ctx, &query)?;        // A page that came back full is a page, whatever the filter leaves.        capped |= found.len() as i64 == args.limit;        let found: Vec<_> = found            .into_iter()            .filter(|row| kind != BinKind::Email || !text(row, "id").is_some_and(|id| inside.contains(&id)))            .filter(|row| items.lists(kind, row))            .collect();        counts.insert(kind.as_str().to_string(), Value::from(found.len() as i64));        for row in found {            let trashed_at = text(&row, "trashed_at").unwrap_or_default();            let mut entry = Map::new();            entry.insert("kind".to_string(), Value::from(kind.as_str()));            entry.insert("id".to_string(), Value::from(text(&row, "id")));            entry.insert("title".to_string(), Value::from(items.title(kind, &row)));            entry.insert("trashedAt".to_string(), Value::from(trashed_at.clone()));            entries.push((trashed_at, Value::Object(entry)));        }    }    // `localeCompare` descending on the instant — the store writes ISO UTC, so    // a string comparison IS chronological.    entries.sort_by(|a, b| b.0.cmp(&a.0));    let mut out = Map::new();    out.insert(        "entries".to_string(),        Value::Array(entries.into_iter().map(|(_, entry)| entry).collect()),    );    out.insert("counts".to_string(), Value::Object(counts));    if capped {        // Said out loud rather than left to be discovered: a count that is        // exactly the page size is a page, not a total.        out.insert(            "note".to_string(),            Value::from(format!(                "counts are capped at the {} rows this page read per kind",                args.limit            )),        );    }    Ok(Value::Object(out))}pub fn restore_from_bin(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if names_records(args) {        let id = require_uuid(args, "id")?;        let restored = tables::restore_binned(ctx, &id)?            .ok_or_else(|| ToolFailure::new("no such record in this workspace"))?;        let mut out = Map::new();        out.insert("kind".to_string(), Value::from(tables::BIN_KIND));        out.insert("id".to_string(), Value::from(id.clone()));        out.insert("restored".to_string(), Value::Bool(restored));        if restored {            ctx.audit("restore_from_bin", &format!("{} {id}", tables::BIN_KIND));        } else {            out.insert("note".to_string(), Value::from("it was not in the bin"));        }        return Ok(Value::Object(out));    }    let args = validate_restore_from_bin(args)?;    let source = bin_source(args.kind);    let query = Query::on(source.table)        .columns(&["id", "trashed_at"])        .eq("id", args.id.clone());    // One answer for "absent" and "not this workspace" — the probe-resistance    // rule every record read here follows.    let row = rows(ctx, &query)?        .into_iter()        .next()        .ok_or_else(|| ToolFailure::new(format!("no such {} in this workspace", args.kind)))?;    if text(&row, "trashed_at").is_none() {        let mut out = Map::new();        out.insert("kind".to_string(), Value::from(args.kind.as_str()));        out.insert("id".to_string(), Value::from(args.id));        out.insert("restored".to_string(), Value::Bool(false));        out.insert("note".to_string(), Value::from("it was not in the bin"));        return Ok(Value::Object(out));    }    // A conversation is its messages: the Email list and search read the    // messages, so a restore that cleared the conversation's row alone left it    // out of both, and its messages in the bin under Email (walk 3c SEV 1).    // Each message comes out through the mailbox's own writer, which queues    // Gmail's untrash and folds the conversation's row back out of the bin.    if args.kind == BinKind::EmailThread {        let messages = super::emails::shared::target_rows(ctx, &[], std::slice::from_ref(&args.id))?;        let out_of_bin = EmailStatePatch { bin: Some(false), ..EmailStatePatch::default() };        super::emails::shared::apply_email_state(ctx, &messages, out_of_bin)?;    }    let mut patch = Map::new();    patch.insert("trashed_at".to_string(), Value::Null);    let own_event = match args.kind {        BinKind::Event => let_go_occurrence(ctx, &args.id)?,        _ => None,    };    if own_event.is_some() {        // No longer an exception of its series, which keeps that day        // cancelled so it is not drawn twice. Not marked pending: nothing        // writes to Google (Cotton Days, 20 Nov 2026).        patch.insert("series_id".to_string(), Value::Null);        patch.insert("original_starts_at".to_string(), Value::Null);    }    if args.kind == BinKind::Event {        patch.insert("erase_requested_at".to_string(), Value::Null);    }    // A restored record returns as it was, edited time and all (architect    // 1115): a restore stamped now lifted a note to the top of its list.    if let Some(edited) = edited_at(ctx, source.table, &args.id)? {        patch.insert("updated_at".to_string(), Value::from(edited));    }    for (column, value) in source.restore_also {        patch.insert(            (*column).to_string(),            match value {                RestoreValue::Text(text) => Value::from(*text),                RestoreValue::Number(number) => Value::from(*number),                RestoreValue::Null => Value::Null,            },        );    }    update_row(ctx, source.table, &args.id, patch)?;    ctx.commit()?;    ctx.audit("restore_from_bin", &format!("{} {}", args.kind, args.id));    let mut out = Map::new();    out.insert("kind".to_string(), Value::from(args.kind.as_str()));    out.insert("id".to_string(), Value::from(args.id));    out.insert("restored".to_string(), Value::Bool(true));    if let Some((title, day)) = own_event {        out.insert("asOwnEvent".to_string(), Value::Bool(true));        let lines = crate::presentation::line_rows(ctx.db(), ctx.workspace_id);        out.insert("said".to_string(), Value::from(restored_as_own_event(&title, &day, &lines)));    }    Ok(Value::Object(out))}/// Put a restored message, or a restored conversation's messages, back in the/// bin through the mailbox's own writer — the Undo of `restore_from_bin` for/// mail, which queues Gmail's trash as the restore queued its untrash, and/// folds the conversation's row back into the bin with them.pub(crate) fn bin_mail_again(ctx: &mut Ctx<'_>, kind: BinKind, id: &str) -> Valid<()> {    let one = [id.to_string()];    let messages = match kind {        BinKind::EmailThread => super::emails::shared::target_rows(ctx, &[], &one)?,        _ => super::emails::shared::target_rows(ctx, &one, &[])?,    };    let into_bin = EmailStatePatch { bin: Some(true), ..EmailStatePatch::default() };    super::emails::shared::apply_email_state(ctx, &messages, into_bin)?;    Ok(())}/// The row's edited time as it stands, for a table that keeps one.fn edited_at(ctx: &Ctx<'_>, table: &'static str, id: &str) -> Valid<Option<String>> {    if !MODDATETIME_TABLES.contains(&table) {        return Ok(None);    }    let query = Query::on(table).columns(&["id", "updated_at"]).eq("id", id.to_string());    Ok(rows(ctx, &query)?.first().and_then(|row| text(row, "updated_at")))}/// Erase these rows of `kind` for good — the one eraser, for `empty_bin` and/// for the bin table's `delete_record` (`tables::bin_table`). The caller has/// already decided they are in the bin.////// Every change row naming an erased row goes first (`tables::forget_changes`)/// — a restore through the bin table, or an edit through the row's own table,/// wrote its title there, and the change log syncs. An erased conversation's/// messages are named too: the erase takes them with it. The row's HISTORY/// (`cotton_changes`) and everything it owns go in the fold of the/// erase, on this file and every peer alike (`cotton_store::erase`).////// An event Google Calendar still holds is not erased yet but ASKED gone/// (`erase_requested_at`): out of the bin at once, and erased for good by the/// Google push right after its cancel has reached Google (`gcal_sync`'s/// `push_trashed`), which calls this again then. Answers how many were asked/// rather than erased.////// A document is erased in the documents slot, and never one whose statement/// Cotton has read: that refusal, or a busy slot, is this call's error, and/// nothing is erased (`empty_bin` leaves such a document in the bin instead).pub fn erase(ctx: &mut Ctx<'_>, kind: BinKind, ids: &[String]) -> Valid<usize> {    if kind == BinKind::Document {        return match erase_documents(ctx, ids)? {            Some(()) => Ok(0),            None => Err(ToolFailure::new(super::documents::tools::SLOT_BUSY_NOTE)),        };    }    let table = bin_source(kind).table;    let mut asked = 0;    // One delete per row, deliberately: a delete is a tombstone every other    // device has to fold, and a bulk statement would write none of them.    for id in ids {        if kind == BinKind::Event && still_at_google(ctx, id)? {            let mut patch = Map::new();            patch.insert("erase_requested_at".to_string(), Value::from(super::common::now_iso(ctx)));            update_row(ctx, table, id, patch)?;            asked += 1;            continue;        }        // A series goes with its moved occurrences: left behind, each would        // draw as an ordinary event of its own.        if kind == BinKind::Event {            let exceptions = Query::on(table).columns(&["id"]).eq("series_id", id.clone());            for exception in rows(ctx, &exceptions)? {                if let Some(exception) = text(&exception, "id") {                    tables::forget_changes(ctx, &exception)?;                    ctx.writer()?.erase(table, &exception, "bin");                }            }        }        if kind == BinKind::EmailThread {            let messages = Query::on(bin_source(BinKind::Email).table)                .columns(&["id"])                .eq("thread_id", id.clone());            for message in rows(ctx, &messages)? {                if let Some(message) = text(&message, "id") {                    tables::forget_changes(ctx, &message)?;                }            }        }        // A moved occurrence erased on its own stays cancelled: its row was        // what claimed its instant, and with it gone the series would draw        // that day again.        if kind == BinKind::Event {            super::records_1::events::keep_occurrence_cancelled(ctx, id)?;        }        tables::forget_changes(ctx, id)?;        ctx.writer()?.erase(table, id, "bin");    }    ctx.commit()?;    Ok(asked)}/// Erase binned documents through the documents engine: `None` when its slot/// is busy and nothing went.fn erase_documents(ctx: &mut Ctx<'_>, ids: &[String]) -> Valid<Option<()>> {    let table = bin_source(BinKind::Document).table;    super::documents::tools::erase_documents(ctx, ids, |ctx, id| {        tables::forget_changes(ctx, id)?;        ctx.writer()?.erase(table, id, "bin");        Ok(())    })}pub fn empty_bin(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let records_only = names_records(args);    let args = if records_only {        let mut rest = args.clone();        rest.remove("kind");        validate_empty_bin(&rest)?    } else {        validate_empty_bin(args)?    };    let before = args        .older_than_days        .map(|days| iso_of_ms(now_ms(ctx) - days * DAY_MS));    let mut erased = Map::new();    let mut total = 0_i64;    let mut at_google = 0_i64;    let mut kept_documents = 0_i64;    let mut slot_busy = false;    if records_only || args.kind.is_none() {        let count = tables::erase_binned(ctx, before.as_deref())?;        total += count;        erased.insert(tables::BIN_KIND.to_string(), Value::from(count));    }    let kinds = if records_only {        Vec::new()    } else {        kinds_for(args.kind)    };    let items = BinItems::read(ctx, &kinds)?;    for kind in kinds {        let source = bin_source(kind);        let mut query = Query::on(source.table)            .columns(&BinItems::columns(kind))            .filter(Filter::NotNull("trashed_at".to_string()));        if let Some(before) = &before {            query = query.filter(Filter::Lt("trashed_at".to_string(), before.clone().into()));        }        let listed = rows(ctx, &query)?.into_iter().filter(|row| items.lists(kind, row));        let mut doomed: Vec<String> = listed.filter_map(|row| text(&row, "id")).collect();        if kind == BinKind::Document {            // A read statement's paper stays in the bin rather than failing            // the whole empty; so does every document while a pass is reading.            let mut erasable = Vec::new();            for id in doomed {                match super::documents::tools::kept_for_its_statement(ctx, &id)? {                    Some(_) => kept_documents += 1,                    None => erasable.push(id),                }            }            doomed = erasable;            if !doomed.is_empty() && erase_documents(ctx, &doomed)?.is_none() {                kept_documents += doomed.len() as i64;                slot_busy = true;                doomed.clear();            }            total += doomed.len() as i64;            erased.insert(kind.as_str().to_string(), Value::from(doomed.len() as i64));            continue;        }        // An event Google still holds goes from the bin now and from the file        // once the sync has cancelled it there.        at_google += erase(ctx, kind, &doomed)? as i64;        total += doomed.len() as i64;        erased.insert(kind.as_str().to_string(), Value::from(doomed.len() as i64));    }    ctx.audit("empty_bin", &format!("{total} record(s) erased"));    let mut out = Map::new();    out.insert("erased".to_string(), Value::Object(erased));    out.insert("total".to_string(), Value::from(total));    // Said every time, because the alternative is somebody believing Cotton    // reached into their mailbox and destroyed something Google still has.    put(        &mut out,        "note",        Some(Value::from(            "this erased Cotton's copies; Gmail keeps its own bin for about 30 days",        )),    );    if kept_documents > 0 {        out.insert("keptDocuments".to_string(), Value::from(kept_documents));        out.insert(            "keptDocumentsNote".to_string(),            Value::from(if slot_busy {                format!(                    "{kept_documents} document(s) stay in the bin: {}",                    super::documents::tools::SLOT_BUSY_NOTE                )            } else {                format!(                    "{kept_documents} document(s) stay in the bin: each is a statement Cotton has read, \                     whose entries are evidence in the user's money — remove those transactions first"                )            }),        );    }    if at_google > 0 {        out.insert("atGoogle".to_string(), Value::from(at_google));        out.insert(            "atGoogleNote".to_string(),            Value::from(format!(                "{at_google} event(s) are out of the bin now and erased for good once the next sync has cancelled them at Google"            )),        );    }    Ok(Value::Object(out))}#[cfg(test)]mod tests {    use super::*;    /// RULE: a moved occurrence's bin title is line `bin.occurrence`, never a    /// sentence composed in Rust (contract 3): a database that rewords it    /// lists the occurrence in its own words, and the day is read back out of    /// the same words.    #[test]    fn a_moved_occurrence_is_titled_by_the_databases_line() {        assert_eq!(occurrence_title("Swimming", "Thu 8 Oct", &[]), "Swimming on Thu 8 Oct");        assert_eq!(occurrence_day("Swimming on Thu 8 Oct", "Swimming", &[]), Some("Thu 8 Oct"));        let reworded = [LineRow { set: LINES.into(), line: OCCURRENCE.into(), words: "{day} — {title}".into() }];        let listed = occurrence_title("Swimming", "Thu 8 Oct", &reworded);        assert_eq!(listed, "Thu 8 Oct — Swimming");        assert_eq!(occurrence_day(&listed, "Swimming", &reworded), Some("Thu 8 Oct"));        assert_eq!(occurrence_day("Swimming", "Swimming", &[]), None);    }    /// RULE: what a restore that made a moved occurrence its own event says    /// is line `bin.restored_own_event`, never a sentence composed in Rust    /// (contract 3): a database that rewords it is said in its own words.    #[test]    fn a_restore_as_its_own_event_is_said_by_the_databases_line() {        assert_eq!(restored_as_own_event("Swimming", "Thu 8 Oct", &[]), "Restored Swimming, Thu 8 Oct, as its own event");        let reworded = [LineRow { set: LINES.into(), line: RESTORED_OWN_EVENT.into(), words: "{title} is back on {day}, on its own".into() }];        assert_eq!(restored_as_own_event("Swimming", "Thu 8 Oct", &reworded), "Swimming is back on Thu 8 Oct, on its own");    }}