Cotton code
349 lines · 19.0 KB · RustRaw
//! ERASES. What Delete everything and Blocked's 30 days take (SENDERS.md): a sender's messages in their WhatsApp and//! SMS one-to-one chats and the mail they sent, erased from his database on every device, as a disappearing message//! is (`chat_timer`): the row, its history and its search entry, never only hidden. A WhatsApp message leaves a//! wordless marker under its WhatsApp id, so no import run brings it back. What he wrote to them is not theirs and//! stays. Nothing is done at the source (WhatsApp, the mail provider, the phone's SMS): that is the Mac import's//! work and the group calls'.use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::messages::app::list::{self, say};use cotton_core::messages::app::senders::{self as rule, SenderKey};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use crate::phone::chat_timer::{marker_columns, newest_of, unword_lists};use crate::phone::cotton_chat::{exists, iso, now_ms, rows, ws, MESSAGES, THREADS};use super::{chat_shares, Blocked, EMAILS};use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::rules::mail_predicate;/// What an erase by Delete everything names as its reason.pub(crate) const DELETED: &str = "sender_deleted";/// What Blocked's 30 days name.pub(crate) const BLOCKED_DAYS_UP: &str = "blocked";/// Rows one sweep erases at most; the next takes the rest.const SWEEP_MAX: usize = 500;const EMAIL_THREADS: &str = "cotton_email_threads";/// When this process last swept Blocked (ms; 0 never).static LAST_SWEEP: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);/// One row a sender sent.#[derive(Debug, Clone)]struct Theirs {    table: &'static str,    id: String,    thread: String,    channel: String,    external: Option<String>,    sent_at: String,}/// Everything `key` sent that is still here: their messages in their one-to-one chats, and their mail.fn theirs(ctx: &mut Ctx<'_>, key: &SenderKey) -> Result<Vec<Theirs>, String> {    let mut out = Vec::new();    let threads: Vec<String> = chat_shares(ctx)?.into_iter().filter(|c| c.key.key.eq_ignore_ascii_case(&key.key)).map(|c| c.thread).collect();    for thread in threads {        let found = rows(            ctx,            &format!("SELECT id, channel, external_id, sent_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND direction = 'in' AND channel IN ('whatsapp', 'sms') AND trashed_at IS NULL AND json_extract(meta, '$.cotton.erased') IS NULL AND json_extract(meta, '$.system') IS NULL"),            &[ws(ctx), SqlValue::Text(thread.clone())],        )?;        for r in found {            let text = |k: &str| r.get(k).and_then(Value::as_str).map(str::to_string);            let (Some(id), Some(channel), Some(sent_at)) = (text("id"), text("channel"), text("sent_at")) else { continue };            out.push(Theirs { table: MESSAGES, id, thread: thread.clone(), channel, external: text("external_id"), sent_at });        }    }    if let Some(address) = rule::key_of_address(&key.key).filter(|_| key.key.contains('@')) {        let found = rows(ctx, &format!("SELECT id, thread_id, sent_at FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? AND {live_mail}", live_mail = mail_predicate::live("")), &[ws(ctx), SqlValue::Text(address.key)])?;        for r in found {            let text = |k: &str| r.get(k).and_then(Value::as_str).map(str::to_string);            let (Some(id), Some(thread)) = (text("id"), text("thread_id")) else { continue };            out.push(Theirs { table: EMAILS, id, thread, channel: "mail".into(), external: None, sent_at: text("sent_at").unwrap_or_default() });        }    }    Ok(out)}/// Erase `doomed` under `reason`, then tidy what held them: a chat's list line keeps none of their words, a chat left/// with nothing of theirs or his is cleared from the list, and a mail conversation left empty goes with its mail.fn erase(ctx: &mut Ctx<'_>, doomed: &[Theirs], reason: &str, now: &str) -> Result<(), String> {    let going: std::collections::HashSet<&str> = doomed.iter().map(|d| d.id.as_str()).collect();    // A mail conversation owns its mail: one whose every mail goes is erased whole, its mail with it.    let mut emptied: std::collections::HashSet<String> = std::collections::HashSet::new();    for d in doomed.iter().filter(|d| d.table == EMAILS) {        if emptied.contains(&d.thread) {            continue;        }        let here = rows(ctx, &format!("SELECT id FROM {EMAILS} WHERE workspace_id = ? AND thread_id = ?"), &[ws(ctx), SqlValue::Text(d.thread.clone())])?;        if here.iter().all(|r| r.get("id").and_then(Value::as_str).is_some_and(|id| going.contains(id))) {            emptied.insert(d.thread.clone());        }    }    let mut chats: Vec<(String, String)> = Vec::new();    for d in doomed {        if d.table == EMAILS && emptied.contains(&d.thread) {            continue;        }        if !exists(ctx, d.table, &d.id)? {            continue;        }        cotton_tools::mcp::handlers::tables::forget_changes(ctx, &d.id).map_err(|f| f.to_string())?;        ctx.writer().map_err(|f| f.to_string())?.erase(d.table, &d.id, reason);        if d.table == MESSAGES {            // A WhatsApp message, and a text Comms read from Android's store (DECISIONS "SMS on Android"), leave a            // wordless marker under their own id, so neither the Mac's import nor reading the store again brings it back.            if let (Some(external), "whatsapp" | "sms") = (&d.external, d.channel.as_str()) {                let marker = cotton_core::chat::ids::erased_marker_id(&d.thread, &d.channel, external);                if !exists(ctx, MESSAGES, &marker)? {                    let mut columns = marker_columns(&d.thread, external, &d.sent_at);                    columns.insert("channel".into(), json!(d.channel));                    insert_row(ctx, MESSAGES, &marker, columns).map_err(|f| f.to_string())?;                }            }            chats.push((d.thread.clone(), d.sent_at.clone()));        }    }    let touched = newest_of(&chats);    unword_lists(ctx, touched.clone(), true)?;    for (thread, newest) in touched {        // The erases land when this write commits: what is left is what is here less what goes.        let here = rows(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND json_extract(meta, '$.cotton.erased') IS NULL"), &[ws(ctx), SqlValue::Text(thread.clone())])?;        if here.iter().all(|r| r.get("id").and_then(Value::as_str).is_some_and(|id| going.contains(id))) {            let mut patch = Map::new();            // Cut at its newest erased message when that is later than now (a sender's clock ahead of ours), so the            // emptied chat leaves the list (`Summary::deleted`: cut at or after its last message).            let cut = if crate::phone::chat_app::ms(&newest) > crate::phone::chat_app::ms(&now) { newest.clone() } else { now.to_string() };            patch.insert("cleared_before".into(), json!(cut));            update_row(ctx, THREADS, &thread, patch).map_err(|f| f.to_string())?;        }    }    for thread in emptied {        if exists(ctx, EMAIL_THREADS, &thread)? {            cotton_tools::mcp::handlers::tables::forget_changes(ctx, &thread).map_err(|f| f.to_string())?;            ctx.writer().map_err(|f| f.to_string())?.erase(EMAIL_THREADS, &thread, reason);        }    }    Ok(())}/// `chat.sender.act {act: "delete", count}`: erase everything `key` sent, only when `count` is what is here now. `key`/// is a whole sender (with those merged into them) or a domain (`@domain`, every address it holds now). Their mail/// also goes to Trash in his mailbox, through the Mac: one `sender_trash` per address, with no count (the count he/// saw was Cotton's; CONTRACT "Senders 3")./// Their mail here, every one not binned: `(id, external id)`, what Delete everything moves at the Mac when his/// mailbox is not counted yet.pub(crate) fn held_mail(ctx: &mut Ctx<'_>, addresses: &[String]) -> Result<Vec<(String, Option<String>)>, String> {    let mut out = Vec::new();    for address in addresses {        for r in rows(ctx, &format!("SELECT id, external_id FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? AND {live_mail}", live_mail = mail_predicate::live("")), &[ws(ctx), SqlValue::Text(address.clone())])? {            if let Some(id) = r.get("id").and_then(Value::as_str) {                out.push((id.to_string(), r.get("external_id").and_then(Value::as_str).map(str::to_string)));            }        }    }    Ok(out)}/// `count` is what Comms holds of theirs, as the ask said; `mailbox` the Mac's count of his mailbox the ask showed/// (`None`: it showed none, so only the mail here goes to Trash there, one `trash` row a mail).pub(crate) fn delete_everything(client: &ClientController, key: &SenderKey, count: Option<u64>, mailbox: Option<u64>) -> Result<Value, MethodError> {    let lines = list::lines();    let now = iso(now_ms(client));    let mut name = key.key.clone();    let mut erased = 0usize;    let mut filed = false;    let mut refused: Option<MethodError> = None;    crate::phone::cotton_chat::write(client, "chat.sender.delete", |ctx| {        let whole = super::wide::whole(ctx, &key.key)?;        name = whole.name.clone();        if count != Some(whole.sent as u64) {            refused = Some(MethodError::new("count_changed", say(&lines, "app.senders.refused.count_changed", &[("name", &name)])));            return Ok(Value::Null);        }        // The mailbox's count he saw, or none: anything else asks again (a count the Mac answered in between).        let addresses = whole.addresses();        let counts = super::wide::mailbox_counts(ctx, false)?;        if mailbox.is_some() && counts.over(&addresses) != mailbox {            refused = Some(MethodError::new("count_changed", say(&lines, "app.senders.refused.count_changed", &[("name", &name)])));            return Ok(Value::Null);        }        let held = if mailbox.is_none() { held_mail(ctx, &addresses)? } else { Vec::new() };        let mut doomed = Vec::new();        filed = false;        for each in &whole.keys {            // His WhatsApp chat with them deleted for him there too, through the Mac (CONTRACT "Blocking a WhatsApp            // sender, deleting a WhatsApp chat"): queued before the erase, whose marker keeps the newest message's            // WhatsApp id and time, which is all the Mac's drain reads of it.            if each.kind == cotton_core::messages::app::senders::KeyKind::Number {                for thread in super::whatsapp_threads_of(ctx, each)? {                    crate::phone::chat_app::whatsapp_send::queue_delete_chat_if(ctx, &thread)?;                }            }            doomed.extend(theirs(ctx, each)?);        }        if mailbox.is_some() {            // Exactly the set the Mac counted and he saw: its `uid_validity` and `uid_below` (mail that came after            // the count is never touched).            for address in &addresses {                let Some(c) = counts.answered.get(address).filter(|c| c.count > 0) else { continue };                let fixed = json!({ "count": c.count, "uid_validity": c.uid_validity, "uid_below": c.uid_below });                filed |= super::wide::file_sender_wide_with(ctx, super::wide::SENDER_TRASH, address, &name, &fixed)?;            }        } else {            // Not counted: only the mail here, each by its own id at the Mac.            for (id, external) in &held {                if external.is_none() {                    continue;                }                if let Some(mail) = crate::phone::chat_app::mail::acts::mail_of(ctx, id)? {                    filed |= crate::phone::chat_app::mail::acts::queue(ctx, &mail, "delete")?;                }            }        }        erased = doomed.len();        erase(ctx, &doomed, DELETED, &now)?;        Ok(Value::Null)    })?;    if let Some(refusal) = refused {        return Err(refusal);    }    // What Comms erased, and, where their mail goes to Trash too, that the Mac does that next: never "done" for the    // mailbox before the Mac says so (ACTS TRUTH, owner, 24 Nov 2026).    let said = if filed { "app.senders.said.deleted_mail" } else { "app.senders.said.deleted" };    Ok(json!({ "key": key.key, "erased": erased, "said": say(&lines, said, &[("n", &erased.to_string()), ("name", &name)]) }))}/// What Delete on one mail names as its reason.pub(crate) const MAIL_DELETED: &str = "mail_deleted";/// Erase these mails (ERASES): a conversation left empty goes with them, as Delete everything's mail does.pub(crate) fn erase_mails(ctx: &mut Ctx<'_>, mails: &[(String, String)], now: &str) -> Result<(), String> {    let doomed: Vec<Theirs> = mails.iter().map(|(id, thread)| Theirs { table: EMAILS, id: id.clone(), thread: thread.clone(), channel: "mail".into(), external: None, sent_at: String::new() }).collect();    erase(ctx, &doomed, MAIL_DELETED, now)}/// Erase what has sat in Blocked for 30 days: each row 30 days after it came there (the block, or its own arrival/// if later). Answers how many went.pub(crate) fn sweep_blocked(client: &ClientController) -> Result<usize, MethodError> {    let now = now_ms(client);    // Once an hour is enough for a 30-day clock; the list is answered far more often.    let last = LAST_SWEEP.load(std::sync::atomic::Ordering::Relaxed);    // Not under test: the suite's phones share this process, and each sweeps its own copy.    if !cfg!(test) && last != 0 && now >= last && now - last < 3_600_000 {        return Ok(0);    }    // An unblock is the block's row gone: a copy that has not pulled everything may still hold a block he lifted on    // another phone, so it erases nothing until it knows (stale presence, ABSENCE audit item 4).    if !crate::phone::chat_timer::knows_every(client, &["email_sender", "message", "thread", "email"]) {        return Ok(0);    }    LAST_SWEEP.store(now, std::sync::atomic::Ordering::Relaxed);    // Counted days too (ABSENCE 5, item 8): from when THIS copy first saw each block, at most one a calendar day it is    // used, and for an account's copy a caught-up pass after them; a block lifted elsewhere whose removal never came    // down cannot erase on the wall clock alone.    let clock = blocked_days(client)?;    let ripe: std::collections::HashSet<String> = client        .with_writer(|file| {            let db = &file.driver;            db.run("CREATE TABLE IF NOT EXISTS _blocked_seen (address TEXT PRIMARY KEY, day INTEGER NOT NULL)", &[]).map_err(|e| e.to_string())?;            db.run("INSERT OR IGNORE INTO _blocked_seen (address, day) SELECT lower(trim(address)), ? FROM cotton_blocked_senders", &[SqlValue::Integer(clock.days as i64)]).map_err(|e| e.to_string())?;            db.run("DELETE FROM _blocked_seen WHERE address NOT IN (SELECT lower(trim(address)) FROM cotton_blocked_senders)", &[]).map_err(|e| e.to_string())?;            let ripe_day = clock.days as i64 - 30;            let pass_day = if clock.needs_pass { clock.pass_day as i64 - 30 } else { i64::MAX };            Ok(db                .all("SELECT address FROM _blocked_seen WHERE day <= ? AND day <= ?", &[SqlValue::Integer(ripe_day), SqlValue::Integer(pass_day)])                .map_err(|e| e.to_string())?                .iter()                .filter_map(|r| r.text("address").map(str::to_string))                .collect())        })        .map_err(|e| MethodError::new("unreadable", e))?;    let mut gone = 0usize;    crate::phone::cotton_chat::write(client, "chat.senders.sweep", |ctx| {        let blocked = Blocked::read(ctx)?;        if blocked.is_empty() {            return Ok(Value::Null);        }        let mut due: Vec<Theirs> = Vec::new();        let keys: Vec<(String, i64)> = blocked.keys().map(|(k, at)| (k.clone(), *at)).collect();        for (stored, since) in keys {            if due.len() >= SWEEP_MAX {                break;            }            if !ripe.contains(&stored) {                continue;            }            let key = super::stored_key(&stored);            for t in theirs(ctx, &key)? {                let sent = chrono::DateTime::parse_from_rfc3339(&t.sent_at).map(|d| d.timestamp_millis()).unwrap_or(0);                if rule::erased_at(since, sent) <= now && due.len() < SWEEP_MAX {                    due.push(t);                }            }        }        gone = due.len();        if !due.is_empty() {            erase(ctx, &due, BLOCKED_DAYS_UP, &iso(now))?;        }        Ok(Value::Null)    })?;    Ok(gone)}/// This copy's counted days for Blocked (device-local, never sent), and the counted day of its last caught-up pass.struct Days {    days: u32,    pass_day: u32,    needs_pass: bool,}/// Count today once: only when it is later than the latest day counted, so a clock set back and forth counts nothing/// twice (ABSENCE 6, M3). A new pull seen while the copy is caught up in this generation (the sweep only runs then)/// is the pass day.fn blocked_days(client: &ClientController) -> Result<Days, MethodError> {    let today = today();    let pull = client.last_pull_at();    let needs_pass = cotton_client::connection::read_record(&client.layout().connection_json()).ok().flatten().is_some_and(|r| r.mine.mode.has_server());    client        .with_writer(|file| {            let db = &file.driver;            let run = |sql: &str, args: &[SqlValue]| db.run(sql, args).map(|_| ()).map_err(|e| e.to_string());            run("CREATE TABLE IF NOT EXISTS _blocked_clock (k TEXT PRIMARY KEY, v TEXT NOT NULL)", &[])?;            let get = |k: &str| -> Result<Option<String>, String> { Ok(db.get("SELECT v FROM _blocked_clock WHERE k = ?", &[SqlValue::Text(k.into())]).map_err(|e| e.to_string())?.and_then(|r| r.text("v").map(str::to_string))) };            let put = |k: &str, v: String| run("INSERT INTO _blocked_clock (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v", &[SqlValue::Text(k.into()), SqlValue::Text(v)]);            let mut days: u32 = get("days")?.and_then(|v| v.parse().ok()).unwrap_or(0);            let latest = get("day")?;            if latest.as_deref().is_none_or(|d| today.as_str() > d) {                days += 1;                put("day", today.clone())?;            }            let mut pass_day: u32 = get("pass_day")?.and_then(|v| v.parse().ok()).unwrap_or(0);            if pull.is_some() && get("pull")? != pull {                pass_day = days;                put("pull", pull.clone().unwrap_or_default())?;            }            put("days", days.to_string())?;            put("pass_day", pass_day.to_string())?;            Ok(Days { days, pass_day, needs_pass })        })        .map_err(|e| MethodError::new("unreadable", e))}fn today() -> String {    #[cfg(test)]    if let Some(day) = TODAY.with(|t| t.borrow().clone()) {        return day;    }    chrono::Utc::now().format("%Y-%m-%d").to_string()}#[cfg(test)]thread_local! {    /// Tests only: the calendar day Blocked counts.    pub(crate) static TODAY: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };}