Cotton code
284 lines · 13.3 KB · RustRaw
//! The Cotton package at the tools' altitude: which stored tables a list of//! table ids means, and the answers the app and an assistant read.//!//! [`cotton_store::cottonpkg`] packages STORED tables; a person and an//! assistant name tables as a tool does — `todo`, `person`, a table a person//! made. A built-in id is its store table ([`TableDefinition::store_table`]);//! a made table is its own `cotton_<id>` table AND its definition row, so the//! database that imports it can make the table before its records land.//!//! The two MCP tools: `export_package` files the package as a document of//! this database and answers its id; `import_package` imports a document that//! is a package. Both need the object store (`media_get` and `media_put`),//! and refuse by name on a server without one.use std::collections::BTreeMap;use serde_json::{json, Map, Value};use cotton_store::cottonpkg::{Exported, Filter, Imported, Match, MediaSink, MediaSource, Package, Selection, EXTENSION};use rusqlite::types::Value as SqlValue;use sha2::{Digest, Sha256};use crate::mcp::dispatch::{Ctx, HandlerGroup, MediaGetRail, MediaPutRail, ToolResult};use crate::mcp::handlers::common::{insert_row, now_iso, require_string, workspace_timezone, Valid};use crate::mcp::handlers::documents::paths::{assert_path_in_workspace, original_path_for};use crate::mcp::handlers::documents::tools::{document_with_bytes, new_document_id};use crate::mcp::handlers::tables::{definition, made_table};use crate::mcp::protocol::ToolFailure;pub fn handlers() -> HandlerGroup {    &[("export_package", export_package), ("import_package", import_package)]}/// The most a package may weigh to pass through the server in one call: it is/// read whole into memory, on the way out and on the way in.pub const PACKAGE_MAX_BYTES: usize = 256 * 1024 * 1024;const NO_STORE: &str = "this server has no object store, so it cannot hold a package's file. \     Export from the Cotton app instead.";const DEFINITIONS: &str = "cotton_table_definitions";/// `where` in `list_records`' grammar, over the stored columns: a value, a/// list of values (any one), `{"values": [..]}` or `{"present": true|false}`.pub fn filter_of(filter: Option<&Value>) -> Valid<Vec<(String, Match)>> {    let Some(filter) = filter else {        return Ok(Vec::new());    };    let entries = filter        .as_object()        .ok_or_else(|| ToolFailure::new("`where` is an object of column → what it must hold"))?;    entries        .iter()        .map(|(column, wanted)| {            let wanted = match wanted {                Value::Array(values) => Match::Values(values.clone()),                Value::Object(shape) => match (shape.get("values"), shape.get("present")) {                    (Some(Value::Array(values)), None) => Match::Values(values.clone()),                    (None, Some(Value::Bool(present))) => Match::Present(*present),                    _ => {                        return Err(ToolFailure::new(format!(                            "`where.{column}` is a value, a list of values, {{\"values\": [..]}} or {{\"present\": true|false}}"                        )))                    }                },                value => Match::Values(vec![value.clone()]),            };            Ok((column.clone(), wanted))        })        .collect()}/// The stored tables `args.tables` names, each with its filter. An entry is a/// table id, or `{table, ids?, where?}`; a top-level `where` holds for every/// entry that names none of its own.pub fn selections(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<Vec<Selection>> {    let tables = args        .get("tables")        .and_then(Value::as_array)        .filter(|tables| !tables.is_empty())        .ok_or_else(|| ToolFailure::new("`tables` names at least one table to export"))?;    let shared = args.get("where");    let mut chosen: BTreeMap<String, Filter> = BTreeMap::new();    let mut order: Vec<String> = Vec::new();    let mut made_definitions: Vec<String> = Vec::new();    for entry in tables {        let (id, ids, filter) = match entry {            Value::String(id) => (id.clone(), None, shared),            Value::Object(fields) => {                let id = fields                    .get("table")                    .and_then(Value::as_str)                    .ok_or_else(|| ToolFailure::new("a `tables` entry names its `table`"))?                    .to_string();                let ids = match fields.get("ids") {                    None | Some(Value::Null) => None,                    Some(Value::Array(ids)) => Some(                        ids.iter()                            .map(|id| id.as_str().map(str::to_string))                            .collect::<Option<Vec<_>>>()                            .ok_or_else(|| ToolFailure::new("`ids` is a list of record ids"))?,                    ),                    Some(_) => return Err(ToolFailure::new("`ids` is a list of record ids")),                };                (id, ids, fields.get("where").or(shared))            }            _ => return Err(ToolFailure::new("a `tables` entry is a table id or {table, ids?, where?}")),        };        let definition = definition(ctx, &id)?;        let stored = match definition.store_table() {            Some(store) => store.to_string(),            None => {                made_definitions.push(definition.rows_table().to_string());                made_table(definition.rows_table())            }        };        if chosen.contains_key(&stored) {            return Err(ToolFailure::new(format!("{id} is named twice in one export")));        }        order.push(stored.clone());        chosen.insert(stored, Filter { ids, columns: filter_of(filter)? });    }    let mut out = Vec::new();    if !made_definitions.is_empty() {        made_definitions.sort();        made_definitions.dedup();        out.push(Selection { table: DEFINITIONS.to_string(), filter: Filter { ids: Some(made_definitions), columns: Vec::new() } });    }    for table in order {        let filter = chosen.remove(&table).unwrap_or_default();        out.push(Selection { table, filter });    }    Ok(out)}/// Package what `args` names out of this context's file.pub fn export(ctx: &Ctx<'_>, args: &Map<String, Value>, media: &mut dyn MediaSource, now: &str) -> Valid<Exported> {    let selections = selections(ctx, args)?;    cotton_store::cottonpkg::export_package(ctx.db(), &selections, media, now).map_err(|error| ToolFailure::new(error.to_string()))}/// The package a file the person brought is — a `.cottonpkg`, or a `.vcf` or/// `.ics` read into one ([`cotton_core::import::package_readers`]) with this/// database's phone region and time zone.pub fn package_of_file(ctx: &Ctx<'_>, file_name: &str, bytes: &[u8]) -> Valid<Package> {    let region = cotton_store::phone_fold::region_hint(ctx.db(), ctx.workspace_id).map_err(|error| ToolFailure::new(error.to_string()))?;    let zone = workspace_timezone(ctx)?;    cotton_core::import::package_readers::package_of_file(file_name, bytes, ctx.db(), region, &zone, &now_iso(ctx)).map_err(ToolFailure::new)}/// What an export answers beside where its file is.pub fn exported_answer(exported: &Exported) -> Map<String, Value> {    let mut answer = Map::new();    answer.insert(        "tables".to_string(),        Value::Array(            exported                .manifest                .tables                .iter()                .map(|table| json!({"table": table.table, "rows": table.rows}))                .collect(),        ),    );    answer.insert("sizeBytes".to_string(), Value::from(exported.bytes.len() as u64));    answer.insert("missingMedia".to_string(), json!(exported.missing_media));    answer}/// What an import answers: per table, what it made, changed and left alone,/// and every record it could not write with why.pub fn imported_answer(imported: &Imported) -> Value {    json!({        "created": imported.created,        "changed": imported.changed,        "unchanged": imported.unchanged,        "refused": imported.refused.iter().map(|refused| json!({            "table": refused.table,            "id": refused.id,            "reason": refused.reason,        })).collect::<Vec<_>>(),        "mediaWritten": imported.media_written,    })}/// The bytes the server's object store holds, by key.struct Objects(MediaGetRail);impl MediaSource for Objects {    fn read(&mut self, key: &str) -> cotton_store::Result<Option<Vec<u8>>> {        (self.0)(key).map_err(cotton_store::StoreError::refused)    }}/// The server's object store, as an import lands bytes in it.struct Landing(MediaPutRail);impl MediaSink for Landing {    fn write(&mut self, key: &str, bytes: &[u8]) -> cotton_store::Result<()> {        (self.0)(key, bytes, content_type_of(key)).map_err(cotton_store::StoreError::refused)    }}fn content_type_of(key: &str) -> &'static str {    let ext = std::path::Path::new(key).extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();    cotton_core::import::media_plan::content_type_for_extension(&ext).unwrap_or("application/octet-stream")}fn rails(ctx: &Ctx<'_>) -> Valid<(MediaGetRail, MediaPutRail)> {    match (ctx.services.media_get.clone(), ctx.services.media_put.clone()) {        (Some(get), Some(put)) => Ok((get, put)),        _ => Err(ToolFailure::new(NO_STORE)),    }}/// `export_package` — package the tables named, file the package as a/// document of this database, and answer the document's id.pub fn export_package(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let (get, put) = rails(ctx)?;    let now = now_iso(ctx);    let exported = export(ctx, args, &mut Objects(get), &now)?;    if exported.bytes.len() > PACKAGE_MAX_BYTES {        return Err(ToolFailure::new(format!(            "this package is {} bytes, over the {PACKAGE_MAX_BYTES}-byte limit for one call: export fewer tables, or name ids or where",            exported.bytes.len()        )));    }    let sha256 = hex::encode(Sha256::digest(&exported.bytes));    let file_name = format!("cotton-{}.{EXTENSION}", now.get(..10).unwrap_or("package"));    let mut answer = exported_answer(&exported);    answer.insert("fileName".to_string(), Value::from(file_name.clone()));    if let Some(existing) = document_with_bytes(ctx, &sha256)? {        answer.insert("document".to_string(), existing.get("id").cloned().unwrap_or(Value::Null));        return Ok(Value::Object(answer));    }    let document_id = new_document_id(ctx, &sha256)?;    let storage_path = original_path_for(ctx.workspace_id, &document_id, &file_name);    put(&storage_path, &exported.bytes, "application/zip").map_err(ToolFailure::new)?;    let tables: Vec<&str> = exported.manifest.tables.iter().map(|table| table.table.as_str()).collect();    let mut patch = Map::new();    patch.insert("original_name".to_string(), Value::from(file_name));    patch.insert("mime".to_string(), Value::from("application/zip"));    patch.insert("byte_size".to_string(), Value::from(exported.bytes.len() as u64));    patch.insert("sha256".to_string(), Value::from(sha256));    patch.insert("storage_path".to_string(), Value::from(storage_path));    patch.insert("source".to_string(), Value::from("agent"));    // A package is read by `import_package`, never by the documents    // pipeline: it is filed ready, with nothing for the reader to do.    patch.insert("status".to_string(), Value::from("ready"));    patch.insert("status_changed_at".to_string(), Value::from(now));    patch.insert("doc_type".to_string(), Value::from("other"));    patch.insert("facts".to_string(), json!({}));    patch.insert("text_extracted".to_string(), Value::from(false));    patch.insert("title".to_string(), Value::from(format!("Cotton package: {}", tables.join(", "))));    insert_row(ctx, "cotton_documents", &document_id, patch)?;    ctx.commit()?;    answer.insert("document".to_string(), Value::from(document_id));    Ok(Value::Object(answer))}/// `import_package` — import a document that is a Cotton package, a contacts/// file (`.vcf`) or a calendar file (`.ics`) into this database.pub fn import_package(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let (get, put) = rails(ctx)?;    let id = require_string(args, "document").ok_or_else(|| ToolFailure::new("`document` names the package document to import"))?;    let row = ctx        .db()        .get(            "SELECT storage_path, byte_size, original_name FROM cotton_documents WHERE id = ? AND trashed_at IS NULL",            &[SqlValue::Text(id.clone())],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .ok_or_else(|| ToolFailure::new(format!("this database holds no document {id}")))?;    if row.int("byte_size").unwrap_or(0) > PACKAGE_MAX_BYTES as i64 {        return Err(ToolFailure::new(format!("document {id} is over the {PACKAGE_MAX_BYTES}-byte limit for one call")));    }    let path = assert_path_in_workspace(row.text("storage_path"), ctx.workspace_id).map_err(ToolFailure::new)?;    let bytes = get(&path)        .map_err(ToolFailure::new)?        .ok_or_else(|| ToolFailure::new(format!("document {id}'s file has not reached the server yet — try again later")))?;    let package = package_of_file(ctx, row.text("original_name").unwrap_or(&path), &bytes)?;    let imported = ctx.writer()?.import_package(&package, &mut Landing(put)).map_err(|error| ToolFailure::new(error.to_string()))?;    Ok(imported_answer(&imported))}