Cotton code
614 lines · 25.1 KB · RustRaw
//! The one door the Worker comes in by: a rule's name and its input as JSON,//! its answer as JSON. Plain strings, numbers, bools, arrays and objects only;//! an input that does not read is a refusal, never a panic.//!//! The WASM shim (`cotton-rules-wasm`) is this function and nothing else, so//! every rule the Worker can call is tested here natively.use serde::de::DeserializeOwned;use serde_json::{json, Value};use crate::computed;/// Why a call was refused: the words say it.pub type Refusal = String;fn input<T: DeserializeOwned>(name: &str, value: Value) -> Result<T, Refusal> {    serde_json::from_value(value).map_err(|error| format!("{name}: the input does not read: {error}"))}/// A rule's refusal in its words. The moment and zone sentences carry the/// `cotton: ` a JavaScript RangeError once printed; a caller reads the words.fn said(error: impl std::fmt::Display) -> Refusal {    let words = error.to_string();    words.strip_prefix("cotton: ").map(str::to_string).unwrap_or(words)}/// Run the rule `name` over `input` (JSON text); its answer, or why not.pub fn call(name: &str, input_text: &str) -> Result<Value, Refusal> {    let value: Value = serde_json::from_str(input_text).map_err(|error| format!("{name}: the input is not JSON: {error}"))?;    match name {        "computed.formula" => {            #[derive(serde::Deserialize)]            struct In {                op: computed::FormulaOp,                values: Vec<Value>,                #[serde(default)]                flip: bool,                #[serde(default)]                separator: Option<String>,            }            let i: In = input(name, value)?;            Ok(computed::formula(i.op, &i.values, i.flip, i.separator.as_deref()))        }        "computed.rollup" => {            #[derive(serde::Deserialize)]            struct In {                op: computed::RollupOp,                count: usize,                values: Vec<Value>,            }            let i: In = input(name, value)?;            Ok(computed::rollup(i.op, i.count, &i.values))        }        "computed.figure" => {            #[derive(serde::Deserialize)]            struct In {                value: f64,                #[serde(default)]                decimals: Option<u32>,            }            let i: In = input(name, value)?;            Ok(json!(computed::figure(i.value, i.decimals)))        }        "visibility.parse" => {            #[derive(serde::Deserialize)]            struct In {                word: Option<String>,            }            let i: In = input(name, value)?;            Ok(match crate::visibility::Visibility::parse(i.word.as_deref()) {                Ok(visibility) => visibility.to_json(),                Err(key) => json!({ "refused": key }),            })        }        "zone.known" => {            #[derive(serde::Deserialize)]            struct In {                zone: String,            }            let i: In = input(name, value)?;            Ok(json!(crate::zoned_clock::zoned_parts(0, &i.zone).is_ok()))        }        "moment.split" => {            #[derive(serde::Deserialize)]            struct In {                at: String,                zone: String,            }            let i: In = input(name, value)?;            let split = crate::moment_split::split_moment(&i.at, &i.zone).map_err(said)?;            Ok(json!({ "date": split.date, "time": split.time }))        }        "moment.join" => {            #[derive(serde::Deserialize)]            struct In {                date: String,                time: Option<String>,                zone: String,            }            let i: In = input(name, value)?;            let moment = crate::moment_split::MomentSplit { date: i.date, time: i.time };            Ok(json!(crate::moment_split::join_moment(&moment, &i.zone).map_err(said)?))        }        "moment.next" => {            #[derive(serde::Deserialize)]            #[serde(tag = "kind", rename_all = "lowercase")]            enum Part {                Unchanged,                Cleared,                Set { value: String },            }            fn change(part: &Part) -> crate::moment_split::PartChange<&str> {                match part {                    Part::Unchanged => crate::moment_split::PartChange::Unchanged,                    Part::Cleared => crate::moment_split::PartChange::Cleared,                    Part::Set { value } => crate::moment_split::PartChange::Set(value),                }            }            #[derive(serde::Deserialize)]            struct In {                current: Option<String>,                date: Part,                time: Part,                zone: String,            }            let i: In = input(name, value)?;            Ok(json!(crate::moment_split::next_moment(i.current.as_deref(), change(&i.date), change(&i.time), &i.zone).map_err(said)?))        }        "todo.rule" => {            #[derive(serde::Deserialize)]            struct In {                rrule: String,            }            let i: In = input(name, value)?;            Ok(crate::rrule::parse_todo_rule(&i.rrule)?.to_json())        }        "todo.plan" => {            #[derive(serde::Deserialize)]            struct Latest {                at: String,                finished: bool,            }            #[derive(serde::Deserialize)]            struct In {                rrule: String,                dtstart: String,                zone: String,                now: String,                latest: Option<Latest>,                mark: Option<String>,                paused: bool,            }            let i: In = input(name, value)?;            let instant = |iso: &str| crate::js::parse_date_ms(iso).ok_or_else(|| format!("{iso:?} is not an instant"));            let template = crate::todo_recurrence::TodoRecurrencePlanInput {                rrule: i.rrule,                dtstart: instant(&i.dtstart)?,                materialized_until: i.mark.as_deref().map(instant).transpose()?,                latest: match i.latest {                    Some(latest) => Some(crate::todo_recurrence::LatestOccurrence { at: instant(&latest.at)?, finished: latest.finished }),                    None => None,                },                paused: i.paused,                timezone: i.zone,            };            let plan = crate::todo_recurrence::plan_materialization(&template, instant(&i.now)?).map_err(said)?;            Ok(json!(plan.occurrences.into_iter().filter_map(crate::js::to_iso_string).collect::<Vec<_>>()))        }        "expression.evaluate" => {            #[derive(serde::Deserialize)]            struct In {                expression: Value,                record: serde_json::Map<String, Value>,                now: String,                today: String,            }            let i: In = input(name, value)?;            crate::expressions::evaluate_at(&i.expression, &i.record, &i.now, &i.today)        }        "balances.book" => {            #[derive(serde::Deserialize)]            struct In {                book: crate::balances::Book,                today: String,            }            let i: In = input(name, value)?;            let worked = crate::balances::work_book(&i.book, &i.today);            Ok(json!({ "transactions": worked.transactions, "accounts": worked.accounts }))        }        "balances.run" => {            #[derive(serde::Deserialize)]            struct In {                account: crate::balances::RunAccount,                rows: Vec<crate::balances::RunRow>,                printed: std::collections::HashMap<String, i64>,                today: String,            }            let i: In = input(name, value)?;            let run = crate::balances::work_run(&i.account, &i.rows, &i.printed, &i.today);            Ok(json!({ "rows": run.rows, "balance": run.balance }))        }        "book.opf" => {            #[derive(serde::Deserialize)]            struct In {                opf: String,            }            let i: In = input(name, value)?;            Ok(crate::opf::read(i.opf.as_bytes()).answer())        }        "book.container" => {            #[derive(serde::Deserialize)]            struct In {                xml: String,            }            let i: In = input(name, value)?;            Ok(json!({ "opf_path": crate::opf::container_rootfile(i.xml.as_bytes()) }))        }        "fetch.stage_line" => {            let i: crate::fetch_stage::Stage = input(name, value)?;            crate::fetch_stage::line(&i).map(|line| json!({ "line": line }))        }        "media.uploads" => Ok(crate::media::upload_table()),        name if name.starts_with("send.") => crate::send::call(name, value),        "voice.languages" | "voice.format" | "voice.lines" | "voice.cues" => crate::voice::call(name, value),        "music.lists" => Ok(crate::music::lists()),        "fingerprint.content" => {            #[derive(serde::Deserialize)]            #[serde(rename_all = "camelCase")]            struct In {                sent_at: String,                body: String,                occurrence: u64,            }            let i: In = input(name, value)?;            let input = crate::fingerprint::message::ContentFingerprintInput { sent_at: &i.sent_at, body: &i.body, occurrence: i.occurrence };            crate::fingerprint::message::content_fingerprint(&input).map(Value::from).map_err(said)        }        "fingerprint.minute" => {            let at: String = input(name, value)?;            crate::fingerprint::message::minute_bucket(&at).map(Value::from).map_err(said)        }        "fingerprint.body" => {            let body: String = input(name, value)?;            Ok(json!(crate::fingerprint::message::normalize_body_for_id(&body)))        }        "phone.normalize" => {            #[derive(serde::Deserialize)]            struct In {                raw: String,                region: Option<String>,            }            let i: In = input(name, value)?;            let region = region_of(i.region.as_deref())?;            Ok(crate::phone::normalize_phone_in(&i.raw, region).map_or(Value::Null, Value::from))        }        "phone.region" => {            let digits: String = input(name, value)?;            Ok(crate::phone::region_of(&digits).map_or(Value::Null, |region| json!(region.as_ref())))        }        "phone.strip" => {            let raw: String = input(name, value)?;            Ok(json!(crate::phone::strip_presentation(&raw)))        }        "handles.normalize" => {            #[derive(serde::Deserialize)]            struct In {                kind: crate::handles::HandleKind,                raw: String,                region: Option<String>,            }            let i: In = input(name, value)?;            let region = region_of(i.region.as_deref())?;            Ok(crate::handles::normalize_contact_handle_in(i.kind, &i.raw, region).map_or(Value::Null, handle_json))        }        "handles.social" => {            #[derive(serde::Deserialize)]            struct In {                kind: crate::handles::HandleKind,                raw: String,            }            let i: In = input(name, value)?;            Ok(crate::handles::social_handle(i.kind, &i.raw).map_or(Value::Null, Value::from))        }        "handles.from" => {            #[derive(serde::Deserialize)]            struct In {                phone: Option<String>,                email: Option<String>,                region: Option<String>,            }            let i: In = input(name, value)?;            let region = region_of(i.region.as_deref())?;            let source = crate::handles::ContactSource { phone: i.phone.as_deref(), email: i.email.as_deref() };            Ok(Value::Array(crate::handles::handles_from(&source, region).into_iter().map(handle_json).collect()))        }        "names.key" => {            let name: String = input(name, value)?;            Ok(json!(crate::name_match::name_key(&name)))        }        "names.score" => {            let (a, b): (String, String) = input(name, value)?;            Ok(json!(crate::name_match::name_match_score(&a, &b)))        }        "names.suggest" => {            #[derive(serde::Deserialize)]            #[serde(rename_all = "camelCase")]            struct In {                candidate: crate::name_match::PersonNamed,                people: Vec<crate::name_match::PersonNamed>,                min_score: Option<f64>,                max: Option<usize>,            }            let i: In = input(name, value)?;            let options = crate::name_match::SuggestPersonMatchesOptions { min_score: i.min_score, max: i.max };            Ok(json!(crate::name_match::suggest_person_matches(&i.candidate, &i.people, options)))        }        "briefing.compile" => {            #[derive(serde::Deserialize)]            struct In {                input: crate::memory_briefing::BriefingInput,                whole: bool,            }            let i: In = input(name, value)?;            let result = if i.whole { crate::memory_briefing::compile_briefing_whole(&i.input) } else { crate::memory_briefing::compile_briefing(&i.input) };            Ok(json!(result))        }        "briefing.limits" => Ok(json!({            "budget": crate::memory_briefing::MEMORY_BRIEFING_BUDGET_TOKENS,            "owner": crate::memory_briefing::MEMORY_BRIEFING_OWNER_TOKENS,            "positionStep": crate::memory_order::POSITION_STEP,            "similarity": crate::memory_briefing::MEMORY_SIMILARITY_THRESHOLD,        })),        "briefing.tokens" => {            let text: String = input(name, value)?;            Ok(json!(crate::memory_briefing::estimate_tokens(&text)))        }        "briefing.owner_tokens" => {            let entries: Vec<crate::memory_briefing::BriefingEntry> = input(name, value)?;            Ok(json!(crate::memory_briefing::owner_section_tokens(&entries)))        }        "briefing.trigger" => {            let body: String = input(name, value)?;            Ok(crate::memory_briefing::procedure_trigger(&body).map_or(Value::Null, Value::from))        }        "briefing.first_sentence" => {            let trigger: String = input(name, value)?;            Ok(json!(crate::memory_briefing::first_sentence(&trigger)))        }        "briefing.mint_slug" => {            #[derive(serde::Deserialize)]            struct In {                title: String,                taken: std::collections::BTreeSet<String>,            }            let i: In = input(name, value)?;            Ok(json!(crate::memory_briefing::mint_memory_slug(&i.title, &i.taken)))        }        "briefing.secret" => {            let text: String = input(name, value)?;            Ok(crate::memory_briefing::looks_like_secret(&text).map_or(Value::Null, |kind| json!(kind.line_key().trim_start_matches("memory.secret."))))        }        "briefing.technical" => {            #[derive(serde::Deserialize)]            #[serde(rename_all = "camelCase")]            struct In {                title: String,                machine_scoped: bool,            }            let i: In = input(name, value)?;            Ok(crate::memory_technical::technical_mark(&i.title, i.machine_scoped).map_or(Value::Null, |mark| json!(mark.line().trim_start_matches("memory.technical."))))        }        "briefing.similarity" => {            let (a, b): (String, String) = input(name, value)?;            Ok(json!(crate::memory_briefing::title_similarity(&a, &b)))        }        "briefing.repo" => {            let raw: String = input(name, value)?;            Ok(json!(crate::memory_briefing::normalize_repo_url(&raw)))        }        "group.slug" => {            let title: String = input(name, value)?;            Ok(json!(crate::import::group::slugify_title(&title)))        }        "group.key" => {            let title: String = input(name, value)?;            Ok(json!(crate::import::group::group_external_key(&title)))        }        "envelope.message" => {            #[derive(serde::Deserialize)]            struct In {                value: Value,                at: String,                context: String,            }            let i: In = input(name, value)?;            let kind = match i.context.as_str() {                "dm" => crate::import::envelope::EnvelopeKind::Dm,                "group" => crate::import::envelope::EnvelopeKind::Group,                other => return Err(format!("{other} is not dm or group")),            };            Ok(json!(crate::import::envelope::validate_envelope_message(&i.value, &i.at, kind)))        }        "envelope.batch" => Ok(json!(crate::import::envelope::validate_import_batch(&value))),        "envelope.check" => {            // The batch's first issue, else what serde refuses in it: null            // only for a batch the import engine can read whole.            if let Some(issue) = crate::import::envelope::validate_import_batch(&value).into_iter().next() {                return Ok(json!(issue));            }            Ok(serde_json::from_value::<crate::import::envelope::ImportBatch>(value).err().map_or(Value::Null, |error| json!(error.to_string())))        }        "ids.derive" => {            #[derive(serde::Deserialize)]            struct In {                table: String,                parts: Vec<String>,            }            let i: In = input(name, value)?;            let parts: Vec<&str> = i.parts.iter().map(String::as_str).collect();            Ok(json!(crate::ids::derived_id(&i.table, &parts)))        }        "ids.reaction" => {            #[derive(serde::Deserialize)]            #[serde(rename_all = "camelCase")]            struct In {                message_id: String,                actor: String,            }            let i: In = input(name, value)?;            Ok(crate::chat_ids::reaction_row_id(&i.message_id, &i.actor).map_or(Value::Null, Value::from))        }        "contacts.handle_row" => {            #[derive(serde::Deserialize)]            struct HandleIn {                kind: crate::handles::HandleKind,                value: String,            }            #[derive(serde::Deserialize)]            #[serde(rename_all = "camelCase")]            struct In {                workspace_id: String,                namespace: String,                contact_id: String,                handle: HandleIn,                now: String,            }            let i: In = input(name, value)?;            let handle = crate::handles::ContactHandle { kind: i.handle.kind, value: i.handle.value };            Ok(json!(crate::messages::resolve_contact::contact_handle_changes(&i.namespace, &i.workspace_id, &i.contact_id, &handle, &i.now)))        }        "open_bundle.lay" => crate::open_bundle::lay_json(value),        // Cotton Story (crate::story): the pure halves the Worker's story_*        // verbs run over rows it has opened.        "story.lines" => {            #[derive(serde::Deserialize)]            struct In {                #[serde(default)]                body: String,                #[serde(default)]                names: Vec<String>,            }            let i: In = input(name, value)?;            Ok(json!({ "lines": crate::story::lines(&i.body, &i.names) }))        }        "story.figures" => {            #[derive(serde::Deserialize)]            struct In {                #[serde(default)]                heading: String,                #[serde(default)]                body: String,                #[serde(default)]                names: Vec<String>,            }            let i: In = input(name, value)?;            Ok(json!(crate::story::figures::of_scene(&i.heading, &i.body, &i.names)))        }        "story.heading.parse" => {            #[derive(serde::Deserialize)]            struct In {                heading: String,            }            let i: In = input(name, value)?;            Ok(json!(crate::story::heading::parse(&i.heading)))        }        "story.heading.compose" => {            let parts: crate::story::heading::Parts = input(name, value)?;            Ok(json!(crate::story::heading::compose(&parts)))        }        // A summary written back by the person's own assistant, laid out as the Mac's local model's is        // (owner, 23 Nov 2026: Cotton has no model of its own): the `summary` and `actions` columns, and the        // actions that are new beside those already added to his to-dos (`kept`), each task once.        "meetings.summary.land" => {            use crate::meetings_summary as m;            #[derive(serde::Deserialize)]            struct In {                points: Vec<String>,                #[serde(default)]                actions: Vec<m::Action>,                #[serde(default)]                voices: Vec<m::Voice>,                #[serde(default)]                kept: Vec<m::Action>,            }            let i: In = input(name, value)?;            let actions: Vec<m::Action> = m::one_list(i.actions.into_iter().filter(|a| !a.words.trim().is_empty()).collect());            let fresh: Vec<&m::Action> = actions.iter().filter(|a| !i.kept.iter().any(|k| m::same_task(k, a))).collect();            Ok(json!({ "summary": m::summary_text(&i.points), "actions": m::actions_text(&actions, &i.voices), "fresh": fresh }))        }        "story.fountain.write" => {            let doc: crate::story::fountain::Doc = input(name, value)?;            Ok(json!(crate::story::fountain::write(&doc)))        }        "story.fountain.read" => {            #[derive(serde::Deserialize)]            struct In {                text: String,            }            let i: In = input(name, value)?;            Ok(json!(crate::story::fountain::read(&i.text)))        }        // A scene's lines as rows that keep their ids (crate::story::identity).        "story.beats.read" => {            #[derive(serde::Deserialize)]            struct In {                #[serde(default)]                body: String,                #[serde(default)]                names: Vec<String>,            }            let i: In = input(name, value)?;            Ok(json!(crate::story::beats::read(&i.body, &i.names)))        }        "story.beats.compose" => {            #[derive(serde::Deserialize)]            struct In {                beats: Vec<crate::story::beats::Beat>,                #[serde(default)]                names: Vec<String>,                /// Someone entering, worded with `{name}`.                #[serde(default)]                enters: String,            }            let i: In = input(name, value)?;            let enters = |who: &str| i.enters.replace("{name}", who);            Ok(json!(crate::story::beats::compose(&i.beats, &i.names, &enters)))        }        "story.beats.reconcile" => {            #[derive(serde::Deserialize)]            struct In {                held: Vec<crate::story::identity::Held>,                #[serde(default)]                body: String,                #[serde(default)]                names: Vec<String>,            }            let i: In = input(name, value)?;            let new = crate::story::beats::read(&i.body, &i.names);            Ok(json!(crate::story::identity::reconcile(&i.held, &new)))        }        "story.drafts.changes" => {            #[derive(serde::Deserialize)]            struct In {                then: Vec<crate::story::identity::SceneAt>,                now: Vec<crate::story::identity::SceneAt>,            }            let i: In = input(name, value)?;            Ok(json!(crate::story::identity::changes(&i.then, &i.now)))        }        "story.fdx.write" => {            #[derive(serde::Deserialize)]            struct In {                #[serde(flatten)]                doc: crate::story::fountain::Doc,                #[serde(default)]                names: Vec<String>,            }            let i: In = input(name, value)?;            Ok(json!(crate::story::fdx::write(&i.doc, &i.names)))        }        _ => Err(format!("no rule named {name}")),    }}/// A region code as the Worker names it ("IN"), or its refusal.fn region_of(code: Option<&str>) -> Result<Option<crate::phone::Region>, Refusal> {    code.map(|code| code.parse::<crate::phone::Region>().map_err(|_| format!("{code} is not a region"))).transpose()}/// A contact handle as the Worker holds one: `{kind, value}`.fn handle_json(handle: crate::handles::ContactHandle) -> Value {    json!({ "kind": handle.kind, "value": handle.value })}/// `call` as the Worker reads it: `{"ok": answer}` or `{"error": words}`.pub fn call_json(name: &str, input_text: &str) -> String {    match call(name, input_text) {        Ok(answer) => json!({ "ok": answer }).to_string(),        Err(words) => json!({ "error": words }).to_string(),    }}#[cfg(test)]mod tests {    use super::*;    #[test]    fn a_rule_answers_ok_and_a_bad_call_is_refused_in_words() {        assert_eq!(call_json("computed.formula", r#"{"op":"sign","values":[-3]}"#), r#"{"ok":-1}"#);        assert!(call_json("computed.formula", r#"{"op":"cube","values":[]}"#).starts_with(r#"{"error":"computed.formula: the input does not read"#));        assert!(call_json("computed.formula", "not json").starts_with(r#"{"error":"computed.formula: the input is not JSON"#));        assert_eq!(call_json("nothing", "{}"), r#"{"error":"no rule named nothing"}"#);    }}