Cotton code
312 lines · 14.1 KB · RustRaw
//! `package.export` and `package.import` — the Cotton package, below the//! boundary.//!//! A `.cottonpkg` ([`cotton_store::cottonpkg`]) is how records leave one//! database and enter another: Cotton's into Rigby's, a phone's into a Mac's.//! Both methods take and answer a PATH, never bytes — a package carries//! pictures, and a body that size crossing the FFI as a string is the jetsam//! kill build 106 already paid for (`export.build`'s rule).//!//! - **`package.export`** `{tables, where?, now?}` → `{path, fileName,//!   sizeBytes, tables: [{table, rows}], missingMedia}`. `tables` is a list of//!   table ids as tools name them, each a string or `{table, ids?, where?}`//!   (`cotton_tools::mcp::handlers::package::selections`). The file lands in//!   the data directory's `cache/exports/`, for the share sheet; an earlier//!   package there is removed first.//! - **`package.import`** `{path}` → `{created, changed, unchanged, refused,//!   mediaWritten}`. The file is one the person was handed (the share sheet,//!   a picked file): a `.cottonpkg`, or a contacts `.vcf` or calendar `.ics`,//!   read into a package by the core's readers. Every record is minted as this device's owner, so it//!   travels like a tap; its bytes land in this device's media store with a//!   ledger row each, exactly as a capture's do.//! - **`package.exportOpen`** `{kit, dir, media?, now?}` → `{dir, files,//!   missingMedia, kit, exportedAt}`. The open bundle//!   ([`cotton_store::open_bundle`]): `kit` (`books`, `music` or//!   `films`) laid as the folder tree other apps open, under `dir`, which is//!   empty or not there yet. `files` counts what was written. Media are the//!   bytes this phone keeps (its ledger's local copies, where the reader and//!   the players read theirs); a key it does not keep is listed in//!   `missingMedia` and never fetched here. `media: false` lays the metadata//!   alone and lists nothing missing, since no bytes were asked for. The//!   answer is the folder, never a zip: whether it is zipped for the share//!   sheet is the shell's.use std::path::{Path, PathBuf};use serde_json::{Map, Value};use cotton_client::layout::Layout;use cotton_client::media::store::media_file_path;use cotton_store::cottonpkg::{MediaSink, MediaSource, EXTENSION};use cotton_store::driver::Driver;use cotton_store::media_holdings::Tier as HoldTier;use cotton_store::media_ledger::{enqueue_media, media_by_key, MediaEnqueueInput};use cotton_store::open_bundle::{write_open_bundle, Kit};use cotton_tools::mcp::handlers::package::{export as export_records, exported_answer, imported_answer, package_of_file};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;fn args_of(request: &Value) -> Map<String, Value> {    request.get("args").and_then(Value::as_object).cloned().unwrap_or_default()}/// `package.export` — package the tables `args.tables` names, leave the file/// in `cache/exports/`, and answer where.pub fn export(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    export_on(&handle.client(), handle.app_name(), &args_of(request))}/// What an exported package is called: the app that made it and the day it/// was made on this phone's own clock, `rigby-2026-11-08.cottonpkg` (Rigby/// 11 walk, 8 Nov 2026: Rigby's Export shared `cotton-<UTC date>`). The app/// is its manifest's name in lower case, words joined by hyphens and nothing/// else kept ("Nancy's Naga Kitchen" is `nancys-naga-kitchen`); an app that/// declares no name is Cotton. A phone with no zone dates it in UTC.pub fn package_file_name(app: &str, now: &str, zone: Option<&str>) -> String {    let words: Vec<String> = app        .split_whitespace()        .map(|word| word.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase())        .filter(|word| !word.is_empty())        .collect();    let app = if words.is_empty() { "cotton".to_string() } else { words.join("-") };    let local = zone.and_then(|zone| {        let instant = chrono::DateTime::parse_from_rfc3339(now).ok()?.timestamp_millis();        cotton_core::import::ical::date_key_in(instant, zone)    });    let day = local.unwrap_or_else(|| now.get(..10).unwrap_or("package").to_string());    format!("{app}-{day}.{EXTENSION}")}/// [`export`]'s body, over a controller a test can hold; `app` is the/// manifest's name the package is called after ([`package_file_name`]).pub fn export_on(client: &ClientController, app: &str, args: &Map<String, Value>) -> Result<Value, MethodError> {    let now = match args.get("now").and_then(Value::as_str) {        Some(now) => now.to_string(),        None => client.now_iso(),    };    let layout = client.layout().clone();    let zone = client.time_zone().map(str::to_string);    client        .read_rows("package.export", &mut |ctx| {            let mut source = Ledger { db: ctx.db() };            let exported = export_records(ctx, args, &mut source, &now).map_err(|error| error.to_string())?;            let file_name = package_file_name(app, &now, zone.as_deref());            let path = write_package(&layout, &file_name, &exported.bytes)?;            let mut answer = exported_answer(&exported);            answer.insert("path".to_string(), Value::from(path.to_string_lossy().to_string()));            answer.insert("fileName".to_string(), Value::from(file_name));            Ok(Value::Object(answer))        })        .map_err(|reason| MethodError::new("export_refused", reason))}/// `package.exportOpen` — lay one kit's open bundle under `args.dir`, and/// answer where and what.pub fn export_open(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    export_open_on(&handle.client(), &args_of(request))}/// [`export_open`]'s body, over a controller a test can hold.pub fn export_open_on(client: &ClientController, args: &Map<String, Value>) -> Result<Value, MethodError> {    let named = args.get("kit").and_then(Value::as_str).unwrap_or_default();    let kit = match named {        "books" => Kit::Books,        "music" => Kit::Music,        "films" => Kit::Films,        _ => {            return Err(MethodError::new(                "bad_request",                format!("`kit` is books, music or films, and {named:?} is none of them"),            ))        }    };    let dir = args        .get("dir")        .and_then(Value::as_str)        .filter(|dir| !dir.is_empty())        .map(PathBuf::from)        .ok_or_else(|| MethodError::new("bad_request", "`dir` names the empty folder the open bundle is laid in"))?;    // The whole folder is what the shell hands on, so nothing of anyone    // else's may already be in it.    if std::fs::read_dir(&dir).map(|mut entries| entries.next().is_some()).unwrap_or(false) {        return Err(MethodError::new(            "export_refused",            format!("{} is already there and holds files: an open bundle is laid into an empty folder", dir.display()),        ));    }    let media = match args.get("media") {        None | Some(Value::Null) => true,        Some(Value::Bool(media)) => *media,        Some(other) => return Err(MethodError::new("bad_request", format!("`media` is true or false, not {other}"))),    };    let now = match args.get("now").and_then(Value::as_str) {        Some(now) => now.to_string(),        None => client.now_iso(),    };    client        .read_rows("package.exportOpen", &mut |ctx| {            let db = ctx.db();            let written = if media {                write_open_bundle(db, kit, &dir, &mut Ledger { db }, &now)            } else {                write_open_bundle(db, kit, &dir, &mut NoBytes, &now).map(|mut written| {                    written.missing_media.clear();                    written                })            }            .map_err(|error| error.to_string())?;            Ok(serde_json::json!({                "dir": dir.to_string_lossy(),                "files": written.files.len(),                "missingMedia": written.missing_media,                "kit": named,                "exportedAt": now,            }))        })        .map_err(|reason| MethodError::new("export_refused", reason))}/// `package.import` — import the package at `args.path` into this device's/// database.pub fn import(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    import_on(&handle.client(), &args_of(request))}/// [`import`]'s body, over a controller a test can hold.pub fn import_on(client: &ClientController, args: &Map<String, Value>) -> Result<Value, MethodError> {    let path = args        .get("path")        .and_then(Value::as_str)        .filter(|path| !path.is_empty())        .ok_or_else(|| MethodError::new("bad_request", "`path` names the package file to import"))?;    let bytes = std::fs::read(path)        .map_err(|error| MethodError::new("unreadable", format!("the package at {path} could not be read: {error}")))?;    let file_name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string();    let layout = client.layout().clone();    let answer = client        .write_rows("package.import", &mut |ctx| {            let package = package_of_file(ctx, &file_name, &bytes).map_err(|error| error.to_string())?;            let db = ctx.db();            let mut sink = Store {                db,                layout: &layout,                workspace_id: ctx.workspace_id.to_string(),                now: cotton_tools::mcp::handlers::common::now_iso(ctx),            };            let imported = ctx                .writer()                .map_err(|error| error.to_string())?                .import_package(&package, &mut sink)                .map_err(|error| error.to_string())?;            Ok(imported_answer(&imported))        })        .map_err(|reason| MethodError::new("import_refused", reason))?;    Ok(crate::authoring::own_answer(answer))}/// The bytes this device holds, by key: the ledger's local copy.struct Ledger<'a> {    db: &'a Driver,}impl MediaSource for Ledger<'_> {    fn read(&mut self, key: &str) -> cotton_store::Result<Option<Vec<u8>>> {        let Some(path) = media_by_key(self.db, key)?.and_then(|row| row.local_path) else {            return Ok(None);        };        match std::fs::read(&path) {            Ok(bytes) => Ok(Some(bytes)),            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),            Err(error) => Err(cotton_store::StoreError::refused(format!("the bytes at {path} could not be read: {error}"))),        }    }}/// No bytes at all: the open bundle's metadata alone.struct NoBytes;impl MediaSource for NoBytes {    fn read(&mut self, _key: &str) -> cotton_store::Result<Option<Vec<u8>>> {        Ok(None)    }}/// This device's media store: the content-addressed file, then its ledger row.struct Store<'a> {    db: &'a Driver,    layout: &'a Layout,    workspace_id: String,    now: String,}impl MediaSink for Store<'_> {    fn write(&mut self, media: &str, bytes: &[u8]) -> cotton_store::Result<()> {        let refused = |error: std::io::Error| cotton_store::StoreError::refused(format!("the bytes for {media} could not be stored: {error}"));        let sha256 = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(bytes));        let ext = Path::new(media).extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();        let path = media_file_path(self.layout, &self.workspace_id, &sha256, &ext);        if !path.exists() {            let _backup = cotton_store::media_backup_lock::mutating(&self.layout.client_media_dir()).map_err(refused)?;            if let Some(parent) = path.parent() {                std::fs::create_dir_all(parent).map_err(refused)?;            }            // A scratch name and a rename, so a killed import never leaves            // half a file under a name that promises a digest.            let scratch = path.with_extension(format!("part-{}", std::process::id()));            // not a copy: package files.            std::fs::write(&scratch, bytes).and_then(|()| std::fs::rename(&scratch, &path)).map_err(|error| {                // not a copy: package files.                let _ = std::fs::remove_file(&scratch);                refused(error)            })?;        }        enqueue_media(            self.db,            &MediaEnqueueInput {                key: media.to_string(),                workspace_id: self.workspace_id.clone(),                sha256,                content_type: cotton_core::import::media_plan::content_type_for_extension(&ext)                    .unwrap_or("application/octet-stream")                    .to_string(),                size_bytes: bytes.len() as i64,                local_path: Some(path.to_string_lossy().to_string()),                state: None,                after: None,                after_row_id: None,                tier: Some(HoldTier::Original),                // The package was the person's own file: these bytes may be                // nowhere else, so the budgeted cache never drops them.                captured_here: true,                now: self.now.clone(),            },        )?;        Ok(())    }}/// Write the package under `cache/exports/`, leaving no earlier one behind.fn write_package(layout: &Layout, file_name: &str, bytes: &[u8]) -> Result<PathBuf, String> {    let dir = layout.exports_dir();    std::fs::create_dir_all(&dir).map_err(|error| format!("the exports folder could not be made: {error}"))?;    if let Ok(entries) = std::fs::read_dir(&dir) {        for entry in entries.flatten() {            let name = entry.file_name();            let Some(name) = name.to_str() else { continue };            if name != file_name && name.ends_with(&format!(".{EXTENSION}")) {                // not a copy: package files.                let _ = std::fs::remove_file(entry.path());            }        }    }    let path = dir.join(file_name);    // not a copy: package files.    std::fs::write(&path, bytes).map_err(|error| format!("the package could not be written to {}: {error}", path.display()))?;    Ok(path)}#[cfg(test)]#[path = "package_tests.rs"]mod tests;