Cotton code
100 lines · 5.1 KB · RustRaw
//! The words a `connection` row is read in — the sentences the app's//! `ConnectionTableSource` said in Swift, answered by the generic read from//! the one copy in `crate::connections::words`, so a page draws them off//! `records.list` / `records.get` like every other table's.//!//! Only what the file holds is said: the kind and the state in words, what//! the connection brought, and for a code host its token (masked), its token//! line, whether and how much of it Cotton holds. Google's live status, its//! detail and its Gmail switch are the serving Mac's, answered by the app.use cotton_core::definitions::TableDefinition;use rusqlite::types::Value as SqlValue;use serde_json::Value;use super::{sql_err, Stored};use crate::connections::words;use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::Valid;/// Answer the words of every `connection` record read.pub(super) fn connection_words(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> {    if !definition.has_engine() || definition.id != "connection" || records.is_empty() {        return Ok(());    }    let kind_choices = definition.columns.iter().find(|column| column.key == "kind_choices")        .and_then(|column| column.choices.as_ref()).map(|choices| serde_json::json!(choices));    let driver = ctx.read.driver();    let mut hosts: Option<Vec<String>> = None;    for record in records.iter_mut() {        if let Some(choices) = &kind_choices {            record.data.insert("kind_choices".into(), choices.clone());        }        let row = driver            .get(                "SELECT c.kind, c.state, c.last_error, c.reaches, c.config, c.database_id,                        EXISTS (SELECT 1 FROM cotton_secrets s                                 WHERE s.id = c.secret_id AND s.trashed_at IS NULL) AS credential_held                   FROM cotton_connections c WHERE c.workspace_id = ? AND c.id = ?",                &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(record.id.clone())],            )            .map_err(sql_err)?;        let Some(row) = row else { continue };        let kind = row.text("kind").unwrap_or_default().to_string();        let reaches = row.text("reaches").unwrap_or_default().to_string();        let said = |word: Option<&str>| word.map_or(Value::Null, Value::from);        record.data.insert("kind".into(), said(words::kind_word(&kind)));        let state = words::state_word_for(&kind, row.text("state").unwrap_or_default(), row.text("last_error"));        record.data.insert("state".into(), said(state.as_deref()));        let config = row            .text("config")            .and_then(|text| serde_json::from_str::<Value>(text).ok())            .filter(Value::is_object)            .unwrap_or_else(|| serde_json::json!({}));        if kind == "browser" {            for key in ["site", "account"] {                record.data.insert(key.into(), said(config.get(key).and_then(Value::as_str)));            }            // The local worker's ledger is not synced. Its live answer may            // supply these words on the serving Mac; this replica cannot.            record.data.insert("browser_facts".into(), Value::Null);        }        // Its rows land in another database; this file cannot count them.        if row.text("database_id").is_none() {            let brought = words::brought(driver, ctx.workspace_id, &kind, &reaches, &config).map_err(sql_err)?;            record.data.insert("brought".into(), said(brought.as_deref()));        }        if kind == "mcp_server" {            record.data.insert("tools".into(), said(words::tool_names(&config).as_deref()));        }        if kind == "whatsapp" {            // On unless switched off: absent reads its statuses.            let on = config.get(crate::connections::STATUSES).and_then(Value::as_bool).unwrap_or(true);            record.data.insert("statuses".into(), Value::Bool(on));        }        if kind == "google" {            // Off unless switched on: a bin made here stays here.            let on = config.get(crate::connections::GMAIL_BIN).and_then(Value::as_bool).unwrap_or(false);            record.data.insert("gmail_bin".into(), Value::Bool(on));        }        if kind != "git_host" {            continue;        }        if hosts.is_none() {            hosts = Some(words::code_hosts(driver).map_err(sql_err)?);        }        let listed = hosts.iter().flatten().find(|host| host.eq_ignore_ascii_case(&reaches)).cloned();        if let Some(host) = listed {            let token = words::code_host_token(driver, &host).map_err(sql_err)?;            record.data.insert("status".into(), Value::from(words::token_line(token.as_ref())));            record.data.insert("token".into(), said(words::masked_token(token.as_ref()).as_deref()));        }        // A token the row's own vault secret holds is held, whether or not a        // project names the host yet.        let unsaid = record.data.get("token").is_none_or(Value::is_null);        if unsaid && row.int("credential_held").unwrap_or(0) != 0 {            record.data.insert("token".into(), Value::from(words::held_credential_mask()));        }    }    Ok(())}