Cotton code
212 lines · 11.6 KB · RustRaw
//! The events this database holds with a set of handles — what an activity//! column (`cotton_core::definitions::computed::Activity`) is worked out//! from: messages in a direct chat with a contact a handle names, or sent by//! one in a group; calls with a number; mail from or among an address. The//! same evidence `record_page_read::handle_activity` reads a handle's//! channels from, counted once however many of the handles reach an event.//!//! A database without one of these stores answers what the others hold.use std::collections::{BTreeMap, BTreeSet};use cotton_store::{Driver, Result};use rusqlite::types::Value as SqlValue;use cotton_core::rules::mail_predicate;/// A handle as the handles table keeps it: `(kind, normalised)`.pub type Handle = (String, String);/// `?1` the workspace, `?2` the oldest stamp counted (or NULL), and from/// `?3` the handles, as the CTE `h(kind, value)`.const MESSAGES: &str = "contacts AS (    SELECT ch.contact_id FROM cotton_msg_contact_handles ch JOIN h ON ch.kind = h.kind AND ch.value = h.value WHERE ch.workspace_id = ?1)SELECT MAX(m.sent_at) AS latest, COUNT(CASE WHEN ?2 IS NULL OR m.sent_at >= ?2 THEN 1 END) AS recent  FROM cotton_msg_messages m JOIN cotton_msg_threads t ON t.id = m.thread_id WHERE m.workspace_id = ?1 AND m.deleted_at IS NULL AND t.trashed_at IS NULL   AND ((t.kind = 'dm' AND t.contact_id IN (SELECT contact_id FROM contacts)) OR m.sender_participant_id IN (SELECT id FROM cotton_msg_thread_participants WHERE contact_id IN (SELECT contact_id FROM contacts)))";const CALLS: &str = "phones AS (SELECT value FROM h WHERE kind = 'phone')SELECT MAX(started_at) AS latest, COUNT(CASE WHEN ?2 IS NULL OR started_at >= ?2 THEN 1 END) AS recent  FROM cotton_call_log WHERE workspace_id = ?1 AND (handle IN (SELECT value FROM phones)    OR contact_id IN (SELECT contact_id FROM cotton_msg_contact_handles WHERE workspace_id = ?1 AND kind = 'phone' AND value IN (SELECT value FROM phones)))";static MAIL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {    format!(        "addresses AS (SELECT lower(value) AS value FROM h WHERE kind = 'email')SELECT MAX(sent_at) AS latest, COUNT(CASE WHEN ?2 IS NULL OR sent_at >= ?2 THEN 1 END) AS recent  FROM cotton_emails WHERE workspace_id = ?1 AND {live_mail}   AND (lower(from_email) IN (SELECT value FROM addresses)    OR thread_id IN (SELECT thread_id FROM cotton_email_participants WHERE workspace_id = ?1 AND lower(email) IN (SELECT value FROM addresses)))",        live_mail = mail_predicate::live("")    )});/// The newest event with any of `handles`, and how many fall at or after/// `since` (all of them without one).pub fn of_handles(db: &Driver, workspace: &str, handles: &[Handle], since: Option<&str>) -> Result<(Option<String>, i64)> {    if handles.is_empty() {        return Ok((None, 0));    }    let pairs: Vec<String> = (0..handles.len()).map(|at| format!("(?{}, ?{})", 3 + 2 * at, 4 + 2 * at)).collect();    let mut params = vec![SqlValue::Text(workspace.into()), since.map_or(SqlValue::Null, |since| SqlValue::Text(since.into()))];    for (kind, value) in handles {        params.push(SqlValue::Text(kind.clone()));        params.push(SqlValue::Text(value.clone()));    }    let (mut latest, mut recent): (Option<String>, i64) = (None, 0);    for ask in [MESSAGES, CALLS, MAIL.as_str()] {        let sql = format!("WITH h(kind, value) AS (VALUES {}), {ask}", pairs.join(", "));        // A store this database does not keep holds no events.        let Ok(Some(row)) = db.get(&sql, &params) else { continue };        if let Some(at) = row.text("latest").filter(|at| latest.as_deref().is_none_or(|held| *at > held)) {            latest = Some(at.to_string());        }        recent += row.int("recent").unwrap_or(0);    }    Ok((latest, recent))}/// `?1` the workspace, `?2` the oldest stamp counted (or NULL), over every/// record's handles in `temp._activity_handles`: each record's newest event/// and how many fall at or after `?2`, an event counted once however many of/// its handles reach it.const MESSAGES_ALL: &str = "WITH contacts AS (    SELECT DISTINCT h.record_id, ch.contact_id FROM temp._activity_handles h      JOIN cotton_msg_contact_handles ch ON ch.kind = h.kind AND ch.value = h.value WHERE ch.workspace_id = ?1), events AS (    SELECT c.record_id, m.id, m.sent_at FROM contacts c      JOIN cotton_msg_threads t ON t.kind = 'dm' AND t.contact_id = c.contact_id AND t.trashed_at IS NULL      JOIN cotton_msg_messages m ON m.thread_id = t.id     WHERE m.workspace_id = ?1 AND m.deleted_at IS NULL    UNION    SELECT c.record_id, m.id, m.sent_at FROM contacts c      JOIN cotton_msg_thread_participants p ON p.contact_id = c.contact_id      JOIN cotton_msg_messages m ON m.sender_participant_id = p.id      JOIN cotton_msg_threads t ON t.id = m.thread_id AND t.trashed_at IS NULL     WHERE m.workspace_id = ?1 AND m.deleted_at IS NULL)SELECT record_id, MAX(sent_at) AS latest, COUNT(CASE WHEN ?2 IS NULL OR sent_at >= ?2 THEN 1 END) AS recent  FROM events GROUP BY record_id";const CALLS_ALL: &str = "WITH phones AS (    SELECT DISTINCT record_id, value FROM temp._activity_handles WHERE kind = 'phone'), events AS (    SELECT p.record_id, c.id, c.started_at FROM phones p JOIN cotton_call_log c ON c.handle = p.value WHERE c.workspace_id = ?1    UNION    SELECT p.record_id, c.id, c.started_at FROM phones p      JOIN cotton_msg_contact_handles ch ON ch.workspace_id = ?1 AND ch.kind = 'phone' AND ch.value = p.value      JOIN cotton_call_log c ON c.contact_id = ch.contact_id     WHERE c.workspace_id = ?1)SELECT record_id, MAX(started_at) AS latest, COUNT(CASE WHEN ?2 IS NULL OR started_at >= ?2 THEN 1 END) AS recent  FROM events GROUP BY record_id";// CROSS JOIN: the mail is read once, each address found by the CTE's// automatic index — an address matched by lower() can use no index of mail.static MAIL_ALL: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {    format!(        "WITH addresses AS (    SELECT DISTINCT record_id, lower(value) AS value FROM temp._activity_handles WHERE kind = 'email'), events AS (    SELECT a.record_id, e.id, e.sent_at FROM cotton_emails e CROSS JOIN addresses a ON lower(e.from_email) = a.value     WHERE e.workspace_id = ?1 AND {live_mail}    UNION    SELECT a.record_id, e.id, e.sent_at FROM cotton_email_participants p CROSS JOIN addresses a ON lower(p.email) = a.value      JOIN cotton_emails e ON e.thread_id = p.thread_id     WHERE p.workspace_id = ?1 AND e.workspace_id = ?1 AND {live_mail})SELECT record_id, MAX(sent_at) AS latest, COUNT(CASE WHEN ?2 IS NULL OR sent_at >= ?2 THEN 1 END) AS recent  FROM events GROUP BY record_id",        live_mail = mail_predicate::live("e.")    )});/// [`of_handles`] for many records at once — `(record id, its handles)` —/// in one read of each store, not one a record: a rebuild works out every/// person's activity, and a read a person over all the messages and mail was/// most of a phone's first ten minutes (23 Oct 2026). A record no event/// reaches is absent from the answer.pub fn of_records(    db: &Driver,    workspace: &str,    records: &[(String, Vec<Handle>)],    since: Option<&str>,) -> Result<BTreeMap<String, (Option<String>, i64)>> {    let mut found: BTreeMap<String, (Option<String>, i64)> = BTreeMap::new();    if records.iter().all(|(_, handles)| handles.is_empty()) {        return Ok(found);    }    db.exec(        "CREATE TEMP TABLE IF NOT EXISTS _activity_handles (record_id TEXT NOT NULL, kind TEXT NOT NULL, value TEXT NOT NULL)",    )?;    db.run("DELETE FROM temp._activity_handles", &[])?;    let listed: Vec<(&str, &str, &str)> = records        .iter()        .flat_map(|(id, handles)| handles.iter().map(move |(kind, value)| (id.as_str(), kind.as_str(), value.as_str())))        .collect();    for some in listed.chunks(10_000) {        let json = serde_json::to_string(some).map_err(cotton_store::StoreError::encode)?;        db.run(            "INSERT INTO temp._activity_handles (record_id, kind, value) \             SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]'), json_extract(value, '$[2]') FROM json_each(?)",            &[SqlValue::Text(json)],        )?;    }    let params = [SqlValue::Text(workspace.into()), since.map_or(SqlValue::Null, |since| SqlValue::Text(since.into()))];    for ask in [MESSAGES_ALL, CALLS_ALL, MAIL_ALL.as_str()] {        // A store this database does not keep holds no events.        let Ok(rows) = db.all(ask, &params) else { continue };        for row in rows {            let Some(id) = row.text("record_id") else { continue };            let (latest, recent) = found.entry(id.to_string()).or_default();            if let Some(at) = row.text("latest").filter(|at| latest.as_deref().is_none_or(|held| *at > held)) {                *latest = Some(at.to_string());            }            *recent += row.int("recent").unwrap_or(0);        }    }    db.run("DELETE FROM temp._activity_handles", &[])?;    Ok(found)}/// The handles the events among `rows` — `(store table, row id)`, a fold's/// changed rows — were with: a message's chat or sender's contact handles, a/// call's number and its contact's numbers, a mail's addresses and its/// thread's.pub fn touched(db: &Driver, rows: &[(String, String)]) -> Result<BTreeSet<Handle>> {    const BY_STORE: &[(&str, &str)] = &[        ("cotton_msg_messages", "SELECT ch.kind AS kind, ch.value AS value FROM cotton_msg_messages m JOIN cotton_msg_threads t ON t.id = m.thread_id            LEFT JOIN cotton_msg_thread_participants p ON p.id = m.sender_participant_id            JOIN cotton_msg_contact_handles ch ON ch.contact_id = p.contact_id OR (t.kind = 'dm' AND ch.contact_id = t.contact_id)           WHERE m.id IN (SELECT value FROM json_each(?1))"),        ("cotton_call_log", "SELECT 'phone' AS kind, handle AS value FROM cotton_call_log WHERE id IN (SELECT value FROM json_each(?1)) AND handle IS NOT NULL          UNION SELECT ch.kind, ch.value FROM cotton_call_log c JOIN cotton_msg_contact_handles ch ON ch.contact_id = c.contact_id AND ch.kind = 'phone'           WHERE c.id IN (SELECT value FROM json_each(?1))"),        ("cotton_emails", "SELECT 'email' AS kind, lower(from_email) AS value FROM cotton_emails WHERE id IN (SELECT value FROM json_each(?1)) AND from_email IS NOT NULL          UNION SELECT 'email', lower(p.email) FROM cotton_emails e JOIN cotton_email_participants p ON p.thread_id = e.thread_id           WHERE e.id IN (SELECT value FROM json_each(?1))"),        ("cotton_msg_contact_handles", "SELECT kind, value FROM cotton_msg_contact_handles WHERE id IN (SELECT value FROM json_each(?1))"),    ];    let mut ids: BTreeMap<&str, Vec<&str>> = BTreeMap::new();    for (store, id) in rows {        ids.entry(store.as_str()).or_default().push(id.as_str());    }    let mut found = BTreeSet::new();    for (store, sql) in BY_STORE {        let Some(ids) = ids.get(store) else { continue };        let list = serde_json::to_string(ids).unwrap_or_default();        // A store this database does not keep names no handle.        let Ok(found_rows) = db.all(sql, &[SqlValue::Text(list)]) else { continue };        for row in found_rows {            if let (Some(kind), Some(value)) = (row.text("kind"), row.text("value")) {                found.insert((kind.to_string(), value.to_string()));            }        }    }    Ok(found)}/// Whether a fold's change to `store` can move an activity column: an/// event, or which contact a handle names.pub fn reads(store: &str) -> bool {    matches!(store, "cotton_msg_messages" | "cotton_call_log" | "cotton_emails" | "cotton_msg_contact_handles")}