Cotton code
359 lines · 14.8 KB · RustRaw
//! A `connection` row in words, said once here so the generic records read//! (`records.page` / `records.get`) and the MCP tables answer the same sentences://! the kind and the state as a person reads them, what the connection//! brought and where it landed, and for a code host its token, its token line//! and how much of it Cotton holds.//!//! Only what the file holds is said. Google's live status, its detail and its//! Gmail switch come from the serving Mac (`google.status`) and are never//! said here.use cotton_core::rules::repo_ref::{project_repo_refs, OwnCotton};use cotton_store::driver::Driver;use rusqlite::types::Value as SqlValue;use serde_json::Value;use cotton_core::rules::mail_predicate;/// The kinds, as the table stores them and as a person reads them.pub const KIND_WORDS: [(&str, &str); 10] = [    ("whatsapp", "WhatsApp"),    ("google", "Google"),    ("mail", "Mail"),    ("calendar", "Calendar"),    ("cloudflare", "Cloudflare"),    ("git_host", "Code host"),    ("mcp_server", "MCP server"),    ("mac_source", "This Mac"),    ("browser", "Browser"),    ("tailscale", "Tailscale"),];/// The states, as the table stores them and as a person reads them.pub const STATE_WORDS: [(&str, &str); 4] =    [("reading", "Reading"), ("paused", "Paused"), ("needs_sign_in", "Needs sign-in"), ("failed", "Failed")];/// A stored kind in words; `None` for one this build does not know.pub fn kind_word(kind: &str) -> Option<&'static str> {    KIND_WORDS.iter().find(|(stored, _)| *stored == kind).map(|(_, word)| *word)}/// An MCP server's tools as its page lists them: the names its `tools/list`/// answered at sign-in (`config.tools`), the first twelve, then how many more./// `None` when it answered none.pub fn tool_names(config: &serde_json::Value) -> Option<String> {    let names: Vec<&str> = config        .get("tools")?        .as_array()?        .iter()        .filter_map(|tool| tool.get("name")?.as_str())        .filter(|name| !name.trim().is_empty())        .collect();    if names.is_empty() {        return None;    }    let shown = names.iter().take(12).copied().collect::<Vec<_>>().join(", ");    Some(match names.len().saturating_sub(12) {        0 => shown,        more => format!("{shown} and {more} more"),    })}/// A stored state in words; `None` for one this build does not know.pub fn state_word(state: &str) -> Option<&'static str> {    STATE_WORDS.iter().find(|(stored, _)| *stored == state).map(|(_, word)| *word)}/// A browser connection waiting for its sign-in: the profile lives on one/// Mac, so that is where the person signs in again.pub const BROWSER_SIGN_IN_WORD: &str = "Needs sign-in on your Mac";/// The sites whose name is not their key capitalised.const SITE_WORDS: [(&str, &str); 2] = [("linkedin", "LinkedIn"), ("youtube", "YouTube")];/// A browser connection's site (`config.site`, `instagram`) in words:/// `Instagram`.pub fn site_word(site: &str) -> String {    let site = site.trim();    if let Some((_, word)) = SITE_WORDS.iter().find(|(key, _)| key.eq_ignore_ascii_case(site)) {        return (*word).to_string();    }    let mut letters = site.chars();    letters.next().map_or_else(String::new, |first| first.to_uppercase().chain(letters).collect())}/// A browser connection's name before the person gives one: "Instagram · me".pub fn browser_name(site: &str, account: &str) -> String {    format!("{} · {}", site_word(site), account.trim())}/// A row's state in words by its kind: a browser connection says where it/// signs in again ("Needs sign-in on your Mac"); a browser or WhatsApp/// connection says what failed ("Failed: Instagram changed", "Failed: This Mac/// cannot link WhatsApp…", from `last_error`); every other kind its plain word.pub fn state_word_for(kind: &str, state: &str, last_error: Option<&str>) -> Option<String> {    let error = last_error.map(str::trim).filter(|error| !error.is_empty());    match (kind, state) {        ("browser", "needs_sign_in") => Some(BROWSER_SIGN_IN_WORD.to_string()),        ("browser" | "whatsapp", "failed") => {            Some(error.map_or_else(|| "Failed".to_string(), |error| format!("Failed: {error}")))        }        (_, other) => state_word(other).map(str::to_string),    }}/// A code host's token as the vault files it: the secret's id and the tail/// it keeps in the clear (`hint`). Never its value.#[derive(Debug, Clone, PartialEq, Eq)]pub struct CodeHostToken {    pub secret_id: String,    pub hint: Option<String>,}/// The token a host's worker would dial with: the NEWEST live `api_key` on/// the host's own service that holds something (`api_key_for`'s order).pub fn code_host_token(driver: &Driver, host: &str) -> Result<Option<CodeHostToken>, String> {    let row = driver        .get(            "SELECT id, hint FROM cotton_secrets \              WHERE service = ? AND kind = 'api_key' AND trashed_at IS NULL \                AND value_enc IS NOT NULL \              ORDER BY updated_at DESC LIMIT 1",            &[SqlValue::Text(format!("forge.{}", host.trim().to_lowercase()))],        )        .map_err(|error| error.to_string())?;    Ok(row.and_then(|row| {        Some(CodeHostToken {            secret_id: row.text("id")?.to_string(),            hint: row.text("hint").map(str::to_string),        })    }))}/// The household's own Cotton, read with the query the Mac's `repos` worker/// reads it with, so every reader resolves one address to one row.pub fn own_cotton(driver: &Driver) -> Result<OwnCotton, String> {    let at = crate::household_address::read_household_address(driver, None)?;    let held = driver.all(OwnCotton::REPOS_SQL, &[]).map_err(|error| error.to_string())?;    Ok(OwnCotton::new(        at,        held.iter().map(|row| {            (                row.text("host").unwrap_or_default(),                row.text("owner").unwrap_or_default(),                row.text("name").unwrap_or_default(),            )        }),    ))}/// Every code host the file knows, sorted: each host a project names.pub fn code_hosts(driver: &Driver) -> Result<Vec<String>, String> {    let projects = driver        .all("SELECT repos FROM cotton_memory_projects ORDER BY slug", &[])        .map_err(|error| error.to_string())?;    let mut named: Vec<String> = Vec::new();    for row in &projects {        let entries = row.text("repos").and_then(|text| serde_json::from_str::<Value>(text).ok());        for entry in entries.as_ref().and_then(Value::as_array).into_iter().flatten() {            if let Some(text) = entry.as_str() {                named.push(text.to_string());            }        }    }    // The crate's ONE parse of a remote: the column is free text an assistant    // wrote, and the scp form is the shape every naive reading gets wrong.    let refs = project_repo_refs(named.iter().map(String::as_str), &own_cotton(driver)?);    let mut hosts: Vec<String> = Vec::new();    for found in &refs {        if !hosts.contains(&found.host) {            hosts.push(found.host.clone());        }    }    hosts.sort();    Ok(hosts)}/// A code host's token line: "Token not set", "Token set", or "Token set ·/// ends in 9zx4".pub fn token_line(token: Option<&CodeHostToken>) -> String {    match token {        None => "Token not set".to_string(),        Some(CodeHostToken { hint: Some(hint), .. }) => format!("Token set \u{00B7} ends in {hint}"),        Some(_) => "Token set".to_string(),    }}/// The token as a page shows it: never in the clear, only its tail.pub fn masked_token(token: Option<&CodeHostToken>) -> Option<String> {    token.map(|token| format!("{}{}", "\u{2022}".repeat(6), token.hint.as_deref().unwrap_or_default()))}/// A token the row's own vault secret holds, where the host is not one/// the file lists: eight dots, no tail.pub fn held_credential_mask() -> String {    "\u{2022}".repeat(8)}/// What a connection brought and where it landed, in words — "4,100 emails in/// Emails · 312 events in Calendar" — or `None` when nothing it brought can be/// traced to it. Only rows that name the account are counted: mail and Google/// Calendar's events carry the `account` they were read from (v76; Gmail read/// before it, `gmail_account`), a WhatsApp message its linked JID, a bridge's rows the tables its mapping writes, a CalDAV calendar's/// events the Cotton calendars its pass lists in `config.collections` (less the/// ones a Google account holds).pub fn brought(    driver: &Driver,    workspace_id: &str,    kind: &str,    reaches: &str,    config: &Value,) -> Result<Option<String>, String> {    let ws = || SqlValue::Text(workspace_id.to_string());    let text = |value: &str| SqlValue::Text(value.to_string());    let count = |sql: &str, args: &[SqlValue]| -> Result<i64, String> {        let row = driver.get(sql, args).map_err(|error| error.to_string())?;        Ok(row.and_then(|row| row.int("n")).unwrap_or(0))    };    let emails = |address: &str| {        count(            &format!("SELECT COUNT(*) AS n FROM cotton_emails              WHERE workspace_id = ? AND lower(coalesce(account, gmail_account)) = lower(?)                AND {live_mail}", live_mail = mail_predicate::live("")),            &[ws(), text(address)],        )    };    let mut landed: Vec<(i64, String, String, Option<&str>)> = Vec::new();    let noun = |one: &str, many: &str| (one.to_string(), many.to_string());    match kind {        "google" => {            let (one, many) = noun("email", "emails");            landed.push((emails(reaches)?, one, many, Some("Emails")));            let events = count(                "SELECT COUNT(*) AS n FROM cotton_events                  WHERE lower(account) = lower(?) AND gcal_etag IS NOT NULL                    AND trashed_at IS NULL AND erase_requested_at IS NULL",                &[text(reaches)],            )?;            let (one, many) = noun("event", "events");            landed.push((events, one, many, Some("Calendar")));        }        "calendar" => {            let calendars: Vec<String> = config                .get("collections")                .and_then(Value::as_array)                .into_iter()                .flatten()                .filter_map(Value::as_str)                .map(str::to_string)                .collect();            if !calendars.is_empty() {                // An event a Google account holds is that account's to count.                let events = count(                    "SELECT COUNT(*) AS n FROM cotton_events                      WHERE collection_id IN (SELECT value FROM json_each(?))                        AND account IS NULL                        AND trashed_at IS NULL AND erase_requested_at IS NULL",                    &[text(&Value::from(calendars).to_string())],                )?;                let (one, many) = noun("event", "events");                landed.push((events, one, many, Some("Calendar")));            }        }        "mail" => {            let (one, many) = noun("email", "emails");            landed.push((emails(reaches)?, one, many, Some("Emails")));        }        "whatsapp" => {            if let Some(account) = config.get("account").and_then(Value::as_str) {                let messages = count(                    "SELECT COUNT(*) AS n FROM cotton_msg_messages                      WHERE workspace_id = ? AND channel = 'whatsapp'                        AND json_extract(meta, '$.source.account') = ?                        AND deleted_at IS NULL AND hidden_at IS NULL",                    &[ws(), text(account)],                )?;                let (one, many) = noun("message", "messages");                landed.push((messages, one, many, Some("Messages")));            }        }        "mcp_server" => {            let mut tables: Vec<&str> = config                .pointer("/mapping/calls")                .and_then(Value::as_array)                .into_iter()                .flatten()                .filter_map(|call| call.get("into").and_then(Value::as_str))                .collect();            tables.sort_unstable();            tables.dedup();            for table in tables {                // A made table's records are rows of its own table; a name                // that is no table id never reaches SQL, and a table this                // file does not hold yet holds nothing.                if !cotton_core::definitions::is_valid_id(table) {                    continue;                }                let store = crate::mcp::handlers::tables::made_table(table);                let held = count(                    "SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?",                    &[text(&store)],                )?;                let rows = if held == 0 {                    0                } else {                    count(&format!("SELECT COUNT(*) AS n FROM {store} WHERE workspace_id = ? AND deleted_at IS NULL"), &[ws()])?                };                // The table names its own records: "12 domain records".                landed.push((rows, format!("{table} record"), format!("{table} records"), None));            }        }        _ => {}    }    let words: Vec<String> = landed        .into_iter()        .filter(|(n, ..)| *n > 0)        .map(|(n, one, many, place)| {            let noun = if n == 1 { one } else { many };            match place {                Some(place) => format!("{} {noun} in {place}", thousands(n)),                None => format!("{} {noun}", thousands(n)),            }        })        .collect();    Ok((!words.is_empty()).then(|| words.join(" \u{00B7} ")))}/// 4100 → "4,100".pub fn thousands(n: i64) -> String {    let digits = n.unsigned_abs().to_string();    let mut out = String::new();    for (i, digit) in digits.chars().enumerate() {        if i > 0 && (digits.len() - i).is_multiple_of(3) {            out.push(',');        }        out.push(digit);    }    if n < 0 { format!("-{out}") } else { out }}#[cfg(test)]mod state_word_tests {    use super::state_word_for;    // RULE: A failed WhatsApp row says why in its state word ("Failed: " and the server's words) — a Mac with no WhatsApp helper says so rather than a bare "Failed"; other kinds keep their plain word.    #[test]    fn a_failed_whatsapp_row_says_why() {        assert_eq!(            state_word_for("whatsapp", "failed", Some("This Mac cannot link WhatsApp.")).as_deref(),            Some("Failed: This Mac cannot link WhatsApp.")        );        assert_eq!(state_word_for("whatsapp", "failed", Some("  ")).as_deref(), Some("Failed"));        assert_eq!(state_word_for("whatsapp", "reading", None).as_deref(), Some("Reading"));        assert_eq!(state_word_for("mcp_server", "failed", Some("timeout")).as_deref(), Some("Failed"));        assert_eq!(state_word_for("browser", "failed", Some("Instagram changed")).as_deref(), Some("Failed: Instagram changed"));    }}#[cfg(test)]#[path = "words_count_tests.rs"]mod count_tests;