Cotton code
108 lines · 5.3 KB · RustRaw
//! The read-only `everything` settings table.//!//! This composite pages the catalogue before reading each displayed table's//! total and latest change. Stored tables share one read and the canonical//! records handlers; host-backed settings keep their native readers.use serde_json::{json, Value};use cotton_core::everything::{identities, plan, finish};use crate::{handle::CottonHandle, methods::MethodError};/// `records.list {table:"everything"}` as one row per visible table.pub fn list(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let mut planned = None;    let mut refusal = None;    let mut found = std::collections::HashMap::new();    let client = handle.client();    let trace = std::env::var_os("COTTON_PERF_READS").is_some();    client.read_rows("records.list.everything", &mut |ctx| {        let began = trace.then(std::time::Instant::now);        let snapshot = cotton_tools::definitions::shared_table_definitions(ctx).map_err(|error| error.to_string())?;        let definitions = &snapshot.definitions;        if let Some(began) = began { eprintln!("PERF catalogue wall_ms={:.3}", began.elapsed().as_secs_f64()*1000.0); }        let identities = identities(definitions);        let plan = match plan(&identities, request) {            Ok(plan) => plan,            Err(error) => {                let message = error.message.clone();                refusal = Some(MethodError::new(error.code, error.message));                return Err(message);            }        };        for table in plan.tables().into_iter().filter(|table| !native_facts(table)) {            let definition = definitions.iter().find(|definition| definition.id == table).expect("planned definition");            let began = trace.then(|| (std::time::Instant::now(), ctx.db().time_inside()));            // A refused argument read keeps its types (code and details), so            // the answer is that refusal, never an `unreadable` carrying its            // words (294 walk row G).            let args = super::records::read_args(&client, &fact_request(table, request, "count_only"))                .and_then(|count| Ok((count, super::records::read_args(&client, &fact_request(table, request, "last_changed"))?)));            let (count_args, changed_args) = match args {                Ok(args) => args,                Err(error) => {                    let message = error.message.clone();                    refusal = Some(error);                    return Err(message);                }            };            // Everything's one count, as MCP reads it (Passwords as its list).            let facts = cotton_tools::mcp::handlers::tables::everything_facts(ctx, definition, &count_args, &changed_args);            if let Some((at, sql)) = began { eprintln!("PERF facts {table} wall_ms={:.3} sql_ms={:.3}", at.elapsed().as_secs_f64()*1000.0, ctx.db().time_inside().saturating_sub(sql).as_secs_f64()*1000.0); }            found.insert(table.to_string(), facts);        }        planned = Some(plan);        Ok(Value::Null)    }).map_err(|error| refusal.unwrap_or_else(|| MethodError::new("unreadable", error)))?;    let plan = planned.expect("planned inside the read");    // Registry and host engines own these facts. Read them outside the file's    // transaction, as their adapters may themselves need that file.    for table in plan.tables().into_iter().filter(|table| native_facts(table)) {        let count = crate::methods::dispatch(handle, "records.list", &fact_request(table, request, "count_only")).ok();        let changed = crate::methods::dispatch(handle, "records.list", &fact_request(table, request, "last_changed")).ok();        found.insert(table.to_string(), facts(count, changed));    }    finish(plan, request, |table| found.remove(table).unwrap_or_default())        .map_err(|error| MethodError::new(error.code, error.message))}fn fact_request(table: &str, request: &Value, fact: &str) -> Value {    let mut args = json!({"table":table});    args[fact] = Value::Bool(true);    for key in ["today", "timezone"] {        if let Some(value) = request.get(key) { args[key] = value.clone(); }    }    args}fn native_facts(table: &str) -> bool {    super::records::settings_tables::TABLES.iter().any(|(id, _)| *id == table)        || cotton_core::definitions::METERING_READS.contains(&table)        || matches!(table, "device" | "message_import" | "repo_var")}fn facts(count: Option<Value>, changed: Option<Value>) -> (Option<i64>, Option<Value>) {    // An unavailable reader is unknown, never zero.    (count.as_ref().and_then(|answer| answer["total"].as_i64()),     changed.and_then(|answer| answer.get("last_changed").cloned()))}/// `records.get {table:"everything"}` resolves from the same composite.pub fn get(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let id = request["id"]        .as_str()        .filter(|id| !id.is_empty())        .ok_or_else(|| MethodError::new("bad_request", "`records.get` needs a record id"))?;    let listed = list(handle, &json!({"ids":[id]}))?;    listed["records"]        .as_array()        .and_then(|records| records.first())        .cloned()        .ok_or_else(|| {            MethodError::new(                "record_not_found",                format!("the `everything` table has no record `{id}`"),            )        })}