Cotton code
117 lines · 5.2 KB · RustRaw
//! The engine over a host that answers in JSON: an empty object, so every//! read finds nothing and the plan is the batch's own rows.use std::cell::RefCell;use serde_json::{json, Value};use super::*;/// A host holding nothing; it records what it was asked.#[derive(Default)]struct Empty {    asked: RefCell<Vec<String>>,    ids: RefCell<u32>,}impl Ask for Empty {    fn ask(&self, question: &str, _args: Value) -> Result<Value, String> {        self.asked.borrow_mut().push(question.to_string());        Ok(match question {            "people_handles" | "known_external_ids" | "jid_group_threads" | "participants_of" | "unlinked_replies"            | "messages_by_external_ids" | "held_without_media" | "real_id_bodies_in_minute" | "rows_in_minute" => json!([]),            "owner_region" => json!("IN"),            "new_id" => {                *self.ids.borrow_mut() += 1;                json!(format!("id-{}", self.ids.borrow()))            }            "thread_stats" => json!({"count": 0, "oldestSentAt": null, "newestSentAt": null}),            _ => Value::Null,        })    }}fn batch() -> Value {    json!({        "workspaceId": "db-1",        "channel": "whatsapp",        "messages": [{"externalId": "m1", "direction": "in", "body": "hello", "sentAt": "2026-10-01T10:00:00.000Z", "phone": "098765 43210"}],    })}#[test]fn a_batch_into_an_empty_object_plans_its_contact_thread_and_message() {    let host = Empty::default();    let input = json!({"batch": batch(), "namespace": "db-1", "now": "2026-10-02T00:00:00.000Z"}).to_string();    let plan = run("import", &input, &host).expect("the plan");    let tables: Vec<&str> = plan["changes"].as_array().unwrap().iter().map(|c| c["table"].as_str().unwrap()).collect();    assert_eq!(tables, ["cotton_msg_contacts", "cotton_msg_contact_handles", "cotton_msg_threads", "cotton_msg_messages", "cotton_msg_threads"]);    // A code-less number is read in the owner's country.    assert_eq!(plan["changes"][0]["patch"]["phone_e164"], json!("919876543210"));    assert_eq!(plan["chats"][0]["inserted"], json!(1));    assert!(host.asked.borrow().contains(&"new_id".to_string()));}#[test]fn a_refusal_carries_the_engines_words_and_code() {    let host = Empty::default();    let mut nameless = batch();    nameless["messages"][0].as_object_mut().unwrap().remove("phone");    let input = json!({"batch": nameless, "namespace": "db-1", "now": "2026-10-02T00:00:00.000Z"}).to_string();    let out: Value = serde_json::from_str(&run_json("import", &input, &host)).unwrap();    assert_eq!(out["code"], json!("IMPORT_SHAPE"));    assert!(out["error"].as_str().unwrap().contains("no usable phone or email"));    let out: Value = serde_json::from_str(&run_json("import", "{}", &host)).unwrap();    assert_eq!(out["code"], json!("bad_input"));}#[test]fn a_host_that_cannot_answer_refuses_the_run() {    struct Mute;    impl Ask for Mute {        fn ask(&self, question: &str, _args: Value) -> Result<Value, String> {            Err(format!("cannot answer {question}"))        }    }    let input = json!({"batch": batch(), "namespace": "db-1", "now": "2026-10-02T00:00:00.000Z"}).to_string();    let refused = run("import", &input, &Mute).unwrap_err();    assert!(refused.words.starts_with("cannot answer "), "{}", refused.words);    assert_eq!(refused.code, "UNKNOWN");}/// A host holding one live message (`live`) and one marker of a message the person's own timer erased (`gone`).struct Marked;impl Ask for Marked {    fn ask(&self, question: &str, args: Value) -> Result<Value, String> {        Ok(match question {            "owner_region" => json!("IN"),            "message_by_external_id" => match args["external_id"].as_str() {                Some("live") => json!({ "id": "row-live", "thread_id": "t-1", "meta": {}, "media": [], "newest": false }),                Some("gone") => json!({ "id": "row-gone", "thread_id": "t-1", "meta": { "cotton": { "erased": "disappeared" } }, "media": [], "newest": true }),                _ => Value::Null,            },            _ => Value::Null,        })    }}// RULE: A WhatsApp edit, delete for everyone or reaction to a message the person's own timer erased changes nothing: its marker never takes words, a deletion or a reaction back; the same change to a live message lands.#[test]fn a_change_to_an_erased_message_writes_nothing() {    let changes = |id: &str| {        json!({ "workspaceId": "db-1", "channel": "whatsapp", "changes": [            { "kind": "edit", "external_id": id, "body": "words come back", "at": "2026-11-23T10:00:00.000Z" },            { "kind": "revoke", "external_id": id, "at": "2026-11-23T10:01:00.000Z" },            { "kind": "reaction", "external_id": id, "actor": "owner", "emoji": "👍", "at": "2026-11-23T10:02:00.000Z" },        ]})        .to_string()    };    let gone = run("changes", &changes("gone"), &Marked).expect("plans");    assert_eq!(gone["changes"], json!([]), "nothing written to the marker");    assert_eq!(gone["report"]["missing"], json!(3));    let live = run("changes", &changes("live"), &Marked).expect("plans");    assert_eq!(live["report"]["edited"], json!(1));    assert_eq!(live["report"]["revoked"], json!(1));    assert_eq!(live["report"]["reacted"], json!(1));}