Cotton code
413 lines · 17.1 KB · RustRaw
//! The `cotton_connections` TABLE's writes — one row per thing Cotton keeps reading//! from outside (Cotton note 7767ed9c, Spec 9.7): a WhatsApp number, a Google//! account, a mailbox, a calendar, Cloudflare, a git host, an MCP server.//!//! The code that READS is a source, built once per protocol, on the serving//! Mac. Everything that varies per person is the row: what it reaches, the//! vault secret that signs it in (`secret_id`), the schedule, per-kind config. This module//! spells the row once, for both doors that write it://!//! - the phone's acts (Connect…, Read now, Pause, Resume, Disconnect) write//!   through a [`Ctx`] with [`create`], [`request_read`], [`set_state`] and//!   [`disconnect`];//! - a server reader (a Google account, a git host, the lanes' WhatsApp, mail//!   and MCP readers) builds the same patches with [`row`], [`read_patch`] and//!   [`failed_patch`] on its own job writer, keyed by [`connection_id`] so a//!   reconnect converges on the row that already exists.//!//! The readers' cursors are NOT here: they stay in unsynced tables on the//! serving Mac, and only the active Mac runs a connection.use serde_json::{Map, Value};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{insert_row, now_iso, row_by_id, update_row};use crate::mcp::protocol::ToolFailure;use crate::mcp::writer::Retract;use super::refusal::ConnectionRefusal;/// The table.pub const TABLE: &str = "cotton_connections";/// What a connection reads — the table's `kind` CHECK, spelled once.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ConnectionKind {    /// A WhatsApp number, as a linked device of the person's phone.    Whatsapp,    /// A Google account: Calendar, and Gmail when it is switched on.    Google,    /// A mailbox over IMAP (Fastmail, iCloud, a work server, Gmail).    Mail,    /// A calendar over CalDAV.    Calendar,    /// A Cloudflare account.    Cloudflare,    /// A git host Cotton reads repositories from (Forgejo, GitHub).    GitHost,    /// An MCP server whose tools Cotton calls on a schedule.    McpServer,    /// One of the Mac's own readers (Messages, calls, Photos).    MacSource,    /// A site read through a signed-in browser profile on the serving Mac.    /// The row names the site and the account; the profile — its cookies    /// and session — never leaves that Mac. No site reads through one now    /// (Instagram left, 22 Nov 2026); older rows stay as they were.    Browser,    /// A Tailscale tailnet the household's devices share. `reaches` is the    /// tailnet's name; `secret_id` is one vault login holding its OAuth    /// client (the client id as the username, its secret as the password).    /// Optional: with none, every device reaches the serving Mac the ways it    /// always did; with one, the tailnet is tried after the room and before    /// the relay.    Tailscale,}impl ConnectionKind {    pub const ALL: [ConnectionKind; 10] = [        ConnectionKind::Whatsapp,        ConnectionKind::Google,        ConnectionKind::Mail,        ConnectionKind::Calendar,        ConnectionKind::Cloudflare,        ConnectionKind::GitHost,        ConnectionKind::McpServer,        ConnectionKind::MacSource,        ConnectionKind::Browser,        ConnectionKind::Tailscale,    ];    pub const fn as_str(self) -> &'static str {        match self {            ConnectionKind::Whatsapp => "whatsapp",            ConnectionKind::Google => "google",            ConnectionKind::Mail => "mail",            ConnectionKind::Calendar => "calendar",            ConnectionKind::Cloudflare => "cloudflare",            ConnectionKind::GitHost => "git_host",            ConnectionKind::McpServer => "mcp_server",            ConnectionKind::MacSource => "mac_source",            ConnectionKind::Browser => "browser",            ConnectionKind::Tailscale => "tailscale",        }    }    pub fn parse(text: &str) -> Option<ConnectionKind> {        ConnectionKind::ALL.into_iter().find(|kind| kind.as_str() == text)    }    /// What a connection is called when the person gave it no name.    pub const fn default_name(self) -> &'static str {        match self {            ConnectionKind::Whatsapp => "WhatsApp",            ConnectionKind::Google => "Google",            ConnectionKind::Mail => "Mail",            ConnectionKind::Calendar => "Calendar",            ConnectionKind::Cloudflare => "Cloudflare",            ConnectionKind::GitHost => "Code host",            ConnectionKind::McpServer => "MCP server",            ConnectionKind::MacSource => "This Mac",            ConnectionKind::Browser => "Browser",            ConnectionKind::Tailscale => "Tailscale",        }    }    /// Whether what it reaches is an email address, written lower-case.    pub const fn reaches_an_address(self) -> bool {        matches!(self, ConnectionKind::Google | ConnectionKind::Mail | ConnectionKind::Calendar)    }}/// Where a connection stands — the table's `state` CHECK.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ConnectionState {    /// Its reader runs on schedule.    Reading,    /// The person paused it; the reader skips it until Resume.    Paused,    /// It has no working credential yet, or the service asked again.    NeedsSignIn,    /// The last read failed; `last_error` says why in words.    Failed,}impl ConnectionState {    pub const fn as_str(self) -> &'static str {        match self {            ConnectionState::Reading => "reading",            ConnectionState::Paused => "paused",            ConnectionState::NeedsSignIn => "needs_sign_in",            ConnectionState::Failed => "failed",        }    }    pub fn parse(text: &str) -> Option<ConnectionState> {        [            ConnectionState::Reading,            ConnectionState::Paused,            ConnectionState::NeedsSignIn,            ConnectionState::Failed,        ]        .into_iter()        .find(|state| state.as_str() == text)    }}/// The row id of a connection to `reaches` of `kind`: derived, so the same/// account connected twice — from two phones, or adopted at start and then/// connected again — converges on one row. Case is folded: an address or a/// host is the same one however it was typed.pub fn connection_id(kind: ConnectionKind, reaches: &str) -> String {    format!("conn:{}:{}", kind.as_str(), reaches.trim().to_lowercase())}/// A new connection's columns. The name is trimmed and falls back to the/// kind's own words, so the CHECK never refuses a connection that was made.pub fn row(    workspace_id: &str,    kind: ConnectionKind,    name: &str,    reaches: &str,    state: ConnectionState,    credential: Option<&str>,    config: Value,) -> Map<String, Value> {    let name = name.trim();    // A browser connection is named by its site and account: "Instagram · me".    let site_account = || {        let text = |key: &str| config.get(key).and_then(Value::as_str).map(str::trim).filter(|text| !text.is_empty());        Some(super::words::browser_name(text("site")?, text("account")?))    };    let named = match (name.is_empty(), kind) {        (false, _) => name.to_string(),        (true, ConnectionKind::Browser) => site_account().unwrap_or_else(|| kind.default_name().to_string()),        (true, _) => kind.default_name().to_string(),    };    let name = named.as_str();    let mut patch = Map::new();    patch.insert("workspace_id".into(), Value::from(workspace_id));    patch.insert("kind".into(), Value::from(kind.as_str()));    patch.insert("name".into(), Value::from(name));    patch.insert("reaches".into(), Value::from(reaches.trim()));    patch.insert("state".into(), Value::from(state.as_str()));    patch.insert("secret_id".into(), credential.map_or(Value::Null, Value::from));    patch.insert(        "config".into(),        if config.is_object() { config } else { Value::Object(Map::new()) },    );    patch}/// What a reader writes after a read that worked: reading, when, no error.pub fn read_patch(at: &str) -> Map<String, Value> {    let mut patch = Map::new();    patch.insert("state".into(), Value::from(ConnectionState::Reading.as_str()));    patch.insert("last_read_at".into(), Value::from(at));    patch.insert("last_error".into(), Value::Null);    patch}/// What a reader writes after a read that failed: the error in WORDS a/// person reads on the connection's page, never internals.pub fn failed_patch(state: ConnectionState, error: &str) -> Map<String, Value> {    let mut patch = Map::new();    patch.insert("state".into(), Value::from(state.as_str()));    patch.insert("last_error".into(), Value::from(error.trim()));    patch}/// Whether a reader owes this row a read now: the person asked (Read now)/// after its last read. A paused connection is never read.pub fn read_requested(state: &str, read_requested_at: Option<&str>, last_read_at: Option<&str>) -> bool {    if state == ConnectionState::Paused.as_str() {        return false;    }    match (read_requested_at, last_read_at) {        (Some(asked), Some(read)) => asked > read,        (Some(_), None) => true,        _ => false,    }}/// Connect…: write a new connection (or name again the one already there at/// the same derived id). Answers the row id.pub fn create(    ctx: &mut Ctx<'_>,    kind: ConnectionKind,    name: &str,    reaches: &str,    credential: Option<&str>,    config: Value,) -> Result<String, ToolFailure> {    // An address is one mailbox however it was typed: the readers match it    // against what the Google door stored, which is lower-case.    let folded;    let reaches = if kind.reaches_an_address() {        folded = reaches.trim().to_lowercase();        folded.as_str()    } else {        reaches.trim()    };    let id = if reaches.is_empty() { ctx.new_uuid() } else { connection_id(kind, reaches) };    // A credential is what signs it in; without one it waits for a sign-in.    let state = if credential.is_some() { ConnectionState::Reading } else { ConnectionState::NeedsSignIn };    let mut patch = row(ctx.workspace_id, kind, name, reaches, state, credential, config);    if let Some(existing) = row_by_id(ctx, TABLE, &id)? {        // Connected again: the settings it was given win, and the ones it        // already had (a server, the calendars a reader tied) stay.        let kept = existing.get("config").and_then(|config| match config {            Value::Object(map) => Some(map.clone()),            Value::String(text) => serde_json::from_str::<Map<String, Value>>(text).ok(),            _ => None,        });        if let (Some(mut kept), Some(Value::Object(given))) = (kept, patch.get("config").cloned()) {            kept.extend(given);            patch.insert("config".into(), Value::Object(kept));        }        update_row(ctx, TABLE, &id, patch)?;    } else {        insert_row(ctx, TABLE, &id, patch)?;    }    Ok(id)}/// The connection by id, or the refusal a screen prints.pub fn existing(ctx: &Ctx<'_>, id: &str) -> Result<Map<String, Value>, ToolFailure> {    row_by_id(ctx, TABLE, id)?.ok_or_else(|| ConnectionRefusal::Gone.failure(ctx))}/// Read now: ask the serving Mac's reader to read it at its next pass.pub fn request_read(ctx: &mut Ctx<'_>, id: &str) -> Result<(), ToolFailure> {    let row = existing(ctx, id)?;    if row.get("state").and_then(Value::as_str) == Some(ConnectionState::Paused.as_str()) {        return Err(ConnectionRefusal::Paused.failure(ctx));    }    let mut patch = Map::new();    patch.insert("read_requested_at".into(), Value::from(now_iso(ctx)));    update_row(ctx, TABLE, id, patch)}/// Pause and Resume: the person's switch. Resume puts it back to reading —/// or, for a connection that holds no credential and was never read, back to/// waiting for its sign-in — and the reader moves it on to failed or/// needs-sign-in if the next read says so. Answers the state written.pub fn set_state(ctx: &mut Ctx<'_>, id: &str, state: ConnectionState) -> Result<ConnectionState, ToolFailure> {    let row = existing(ctx, id)?;    let held = |column: &str| row.get(column).and_then(Value::as_str).is_some_and(|text| !text.is_empty());    let state = if state == ConnectionState::Reading && !held("secret_id") && !held("last_read_at") {        ConnectionState::NeedsSignIn    } else {        state    };    let mut patch = Map::new();    patch.insert("state".into(), Value::from(state.as_str()));    update_row(ctx, TABLE, id, patch)?;    Ok(state)}/// Keep a mapping on a connection: `config.mapping` replaced, every other/// config key (the server's `tools`, kept at sign-in) left as it was. The/// caller has validated it; the worker reads it at its next pass.pub fn set_mapping(ctx: &mut Ctx<'_>, id: &str, mapping: Value) -> Result<(), ToolFailure> {    let row = existing(ctx, id)?;    set_config_key(ctx, id, &row, "mapping", mapping)}/// A WhatsApp number's statuses on or off: `config.statuses`, read by the/// link source before every pass. Off passes its statuses over whole — no/// story row, no download — and leaves its messages as they were.pub fn set_statuses(ctx: &mut Ctx<'_>, id: &str, on: bool) -> Result<(), ToolFailure> {    let row = existing(ctx, id)?;    if row.get("kind").and_then(Value::as_str) != Some(ConnectionKind::Whatsapp.as_str()) {        return Err(ConnectionRefusal::NoStories.failure(ctx));    }    // Stories is one choice in this database, shared by its WhatsApp numbers.    let connections = ctx.read.driver().all(        "SELECT id FROM cotton_connections WHERE workspace_id = ? AND kind = 'whatsapp'",        &[rusqlite::types::Value::Text(ctx.workspace_id.to_string())],    ).map_err(|e| ToolFailure::new(e.to_string()))?;    for connection in connections {        let Some(id) = connection.text("id") else { continue; };        let row = existing(ctx, id)?;        set_config_key(ctx, id, &row, STATUSES, Value::Bool(on))?;    }    Ok(())}/// The `config` key that holds a WhatsApp number's statuses switch.pub const STATUSES: &str = "statuses";/// A Google account's "Deleting here also deletes in Gmail": `config.gmail_bin`,/// read by the Gmail push before every pass. Off — the default — keeps a bin/// made in Cotton in Cotton: Gmail is not asked to trash it, while read, star/// and archive still reach Gmail.pub fn set_gmail_bin(ctx: &mut Ctx<'_>, id: &str, on: bool) -> Result<(), ToolFailure> {    let row = existing(ctx, id)?;    if row.get("kind").and_then(Value::as_str) != Some(ConnectionKind::Google.as_str()) {        return Err(ConnectionRefusal::NotGoogle.failure(ctx));    }    set_config_key(ctx, id, &row, GMAIL_BIN, Value::Bool(on))}/// The `config` key that holds a Google account's "Deleting here also deletes/// in Gmail" switch.pub const GMAIL_BIN: &str = "gmail_bin";/// Whether a bin made in Cotton is sent to `account`'s Gmail bin. Off unless/// the person switched it on: no row, no key, or an unreadable config all keep/// the bin here, because a delete that reaches further than asked cannot be/// taken back from Cotton.pub fn gmail_bin_on(ctx: &Ctx<'_>, account: &str) -> Result<bool, ToolFailure> {    let Some(row) = row_by_id(ctx, TABLE, &connection_id(ConnectionKind::Google, account))? else {        return Ok(false);    };    Ok(config_of(&row).ok().and_then(|config| config.get(GMAIL_BIN).and_then(Value::as_bool)).unwrap_or(false))}/// The connection's config as an object: stored as one, or as its JSON text.pub fn config_of(row: &Map<String, Value>) -> Result<Map<String, Value>, ConnectionRefusal> {    match row.get("config") {        Some(Value::Object(map)) => Ok(map.clone()),        Some(Value::String(raw)) => serde_json::from_str::<Value>(raw)            .ok()            .and_then(|value| value.as_object().cloned())            .ok_or(ConnectionRefusal::SettingsUnreadable),        _ => Ok(Map::new()),    }}/// One config key replaced, every other key left as it was.fn set_config_key(    ctx: &mut Ctx<'_>,    id: &str,    row: &Map<String, Value>,    key: &str,    value: Value,) -> Result<(), ToolFailure> {    let mut config = config_of(row).map_err(|refusal| refusal.failure(ctx))?;    config.insert(key.into(), value);    let mut patch = Map::new();    patch.insert("config".into(), Value::Object(config));    update_row(ctx, TABLE, id, patch)}/// Disconnect: the row leaves every device and its reader stops. What it/// brought stays where it landed. Its credential is the caller's to bin.pub fn disconnect(ctx: &mut Ctx<'_>, id: &str) -> Result<Map<String, Value>, ToolFailure> {    let row = existing(ctx, id)?;    // A retract under its verb (on `RETRACT_VERBS`): a connection has no bin —    // what it brought stays, the door goes.    ctx.writer()?.retract(TABLE, id, Retract::Verb("connections.disconnect"));    Ok(row)}#[cfg(test)]#[path = "table_tests.rs"]mod tests;/// The Stories switch, one for the database's WhatsApp numbers. An existing/// off connection keeps a newly linked number off.pub fn stories_enabled(db: &cotton_store::Driver, workspace: &str) -> cotton_store::Result<bool> {    Ok(db.get("SELECT id FROM cotton_connections WHERE workspace_id = ? AND kind = 'whatsapp' AND json_extract(config, '$.statuses') = 0 LIMIT 1",        &[rusqlite::types::Value::Text(workspace.into())])?.is_none())}