Cotton code
404 lines · 12.7 KB · RustRaw
//! Vector tables (`vectors/import.json`, keys `envelopeMessages`, `batches`,//! `caps`) hold every issue SENTENCE the envelope pass produces.//!//! The sentences are the point. They reach a person deciding whether to press//! the button, so a port that validated the same shapes while wording them//! differently would still be a broken port.use super::*;use serde::Deserialize;use serde_json::json;const WORKSPACE: &str = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";fn message(overrides: Value) -> Value {    let mut base = json!({        "phone": "919876543210",        "direction": "in",        "body": "hello",        "sentAt": "2025-07-26T10:12:45.000Z",        "externalId": "3EB0A1B2C3D4E5F60718",    });    let target = base.as_object_mut().expect("an object");    for (key, value) in overrides.as_object().expect("an object") {        if value.is_null() && key.starts_with("__delete_") {            continue;        }        target.insert(key.clone(), value.clone());    }    base}/// `message({ phone: undefined })` in the TypeScript — the key is not there at/// all, which is a different thing from `phone: null`.fn message_without(overrides: Value, drop: &[&str]) -> Value {    let mut value = message(overrides);    let target = value.as_object_mut().expect("an object");    for key in drop {        target.remove(*key);    }    value}fn dm(value: &Value) -> Vec<String> {    validate_envelope_message(value, "message", EnvelopeKind::Dm)}// ── validateEnvelopeMessage ──────────────────────────────────────────────────#[test]fn accepts_the_minimal_section_eight_shape() {    assert_eq!(dm(&message(json!({}))), Vec::<String>::new());}#[test]fn accepts_every_optional_field() {    let value = message(json!({        "displayName": "Anita Rao",        "replyToExternalId": "3EB0000000000000AAAA",        "reactions": [{ "emoji": "x", "actor": "owner", "at": "2025-07-26T10:13:00.000Z" }],        "meta": { "edited": true },    }));    assert_eq!(dm(&value), Vec::<String>::new());}#[test]fn rejects_a_phone_carrying_a_leading_plus_the_canonical_form_has_none() {    let issues = dm(&message(json!({ "phone": "+919876543210" })));    assert!(issues.iter().any(|issue| issue.contains("message.phone")));}#[test]fn rejects_a_bad_direction_sent_at_external_id_or_body() {    for (field, patch) in [        ("direction", json!({ "direction": "outgoing" })),        ("sentAt", json!({ "sentAt": "26/07/2025" })),        ("externalId", json!({ "externalId": "" })),        ("body", json!({ "body": 42 })),    ] {        let joined = dm(&message(patch)).join(" ");        assert!(joined.contains(field), "{field}: {joined}");    }}#[test]fn rejects_a_reaction_missing_its_actor() {    let joined = dm(&message(json!({ "reactions": [{ "emoji": "x" }] }))).join(" ");    assert!(joined.contains("actor"), "{joined}");}#[test]fn reports_the_path_so_a_failing_message_in_a_batch_can_be_found() {    let value = message(json!({ "direction": "sideways" }));    let joined = validate_envelope_message(&value, "messages[7]", EnvelopeKind::Dm).join(" ");    assert!(joined.contains("messages[7].direction"), "{joined}");}/// Rust CAN tell an absent key from an explicit `null`, and it must: JS's/// `!== undefined` treats `{phone: null}` as present and reports it.#[test]fn an_explicit_null_is_present_where_an_absent_key_is_not() {    let joined = dm(&message(json!({ "phone": Value::Null }))).join(" ");    assert!(joined.contains("got null"), "{joined}");    assert_eq!(        dm(&message_without(json!({}), &["phone"])),        Vec::<String>::new()    );}// ── validateImportBatch ──────────────────────────────────────────────────────#[test]fn accepts_a_well_formed_batch() {    let batch = json!({        "workspaceId": WORKSPACE,        "channel": "whatsapp",        "messages": [message(json!({}))],    });    assert_eq!(validate_import_batch(&batch), Vec::<String>::new());}#[test]fn requires_a_uuid_workspace() {    let batch = json!({        "workspaceId": "mine",        "channel": "whatsapp",        "messages": [message(json!({}))],    });    assert!(validate_import_batch(&batch)        .join(" ")        .contains("workspaceId"));}#[test]fn requires_the_channel_which_the_envelope_items_do_not_carry() {    let batch = json!({ "workspaceId": WORKSPACE, "messages": [message(json!({}))] });    assert!(validate_import_batch(&batch).join(" ").contains("channel"));}#[test]fn enforces_the_five_hundred_message_cap() {    let messages: Vec<Value> = (0..MAX_BATCH_MESSAGES + 1)        .map(|_| message(json!({})))        .collect();    let batch = json!({ "workspaceId": WORKSPACE, "channel": "whatsapp", "messages": messages });    assert!(validate_import_batch(&batch)        .join(" ")        .contains("exceeds the 500-message cap"));}#[test]fn accepts_exactly_the_cap() {    let messages: Vec<Value> = (0..MAX_BATCH_MESSAGES)        .map(|_| message(json!({})))        .collect();    let batch = json!({ "workspaceId": WORKSPACE, "channel": "whatsapp", "messages": messages });    assert_eq!(validate_import_batch(&batch), Vec::<String>::new());}// ── group context ────────────────────────────────────────────────────────────fn group(value: &Value) -> Vec<String> {    validate_envelope_message(value, "m", EnvelopeKind::Group)}#[test]fn requires_a_sender_label_on_inbound_human_messages_and_forbids_phone() {    assert_eq!(        group(&message_without(            json!({ "senderLabel": "Asha" }),            &["phone"]        )),        Vec::<String>::new()    );    assert!(group(&message_without(json!({}), &["phone"]))        .join(" ")        .contains("senderLabel"));    assert!(group(&message(json!({ "senderLabel": "Asha" })))        .join(" ")        .contains("phone"));    assert!(group(&message_without(        json!({ "direction": "out", "senderLabel": "Asha" }),        &["phone"]    ))    .join(" ")    .contains("senderLabel"));    assert_eq!(        group(&message_without(            json!({ "meta": { "system": true } }),            &["phone"]        )),        Vec::<String>::new()    );}#[test]fn forbids_a_sender_label_in_a_dm() {    assert!(dm(&message(json!({ "senderLabel": "Asha" })))        .join(" ")        .contains("senderLabel"));}// ── identity blocks ──────────────────────────────────────────────────────────fn thread() -> Value {    json!({        "kind": "group",        "title": "T",        "externalKey": "wa:group:t",        "participants": [            { "label": "Asha" },            { "label": "Vik", "phone": "918123456780", "personId": "p1" },        ],    })}#[test]fn accepts_a_dm_batch_whose_messages_carry_no_phone_when_the_dm_block_names_the_person() {    let batch = json!({        "workspaceId": WORKSPACE,        "channel": "whatsapp",        "dm": { "label": "Asha" },        "messages": [message_without(json!({}), &["phone"])],    });    assert_eq!(validate_import_batch(&batch), Vec::<String>::new());}#[test]fn accepts_participants_with_or_without_a_phone_and_rejects_a_blank_label_or_a_bad_phone() {    let messages = json!([message_without(        json!({ "senderLabel": "Asha" }),        &["phone"]    )]);    let batch = json!({        "workspaceId": WORKSPACE,        "channel": "whatsapp",        "thread": thread(),        "messages": messages,    });    assert_eq!(validate_import_batch(&batch), Vec::<String>::new());    let mut blank = thread();    blank["participants"] = json!([{ "label": " " }]);    let batch = json!({        "workspaceId": WORKSPACE,        "channel": "whatsapp",        "thread": blank,        "messages": messages,    });    assert!(validate_import_batch(&batch).join(" ").contains("label"));    let mut bad_phone = thread();    bad_phone["participants"] = json!([{ "label": "Asha", "phone": "+91" }]);    let batch = json!({        "workspaceId": WORKSPACE,        "channel": "whatsapp",        "thread": bad_phone,        "messages": messages,    });    assert!(validate_import_batch(&batch).join(" ").contains("phone"));}#[test]fn refuses_a_batch_that_is_both_a_dm_and_a_group() {    let batch = json!({        "workspaceId": WORKSPACE,        "channel": "whatsapp",        "thread": thread(),        "dm": { "label": "Asha" },        "messages": [message_without(json!({ "senderLabel": "Asha" }), &["phone"])],    });    assert!(validate_import_batch(&batch).join(" ").contains("not both"));}// ── the Node vector tables ───────────────────────────────────────────────────#[derive(Deserialize)]struct MessageVector {    name: String,    value: Value,    #[serde(default)]    at: Option<String>,    #[serde(default)]    kind: Option<String>,    issues: Vec<String>,}#[derive(Deserialize)]struct BatchVector {    name: String,    value: Value,    issues: Vec<String>,}#[derive(Deserialize)]struct CapVector {    count: usize,    issues: Vec<String>,}#[derive(Deserialize)]struct Vectors {    #[serde(rename = "envelopeMessages")]    envelope_messages: Vec<MessageVector>,    batches: Vec<BatchVector>,    caps: Vec<CapVector>,}fn vectors() -> Vectors {    serde_json::from_str(include_str!("../../vectors/import.json"))        .expect("vectors/import.json")}#[test]fn every_message_issue_is_the_typescripts_own_sentence() {    let vectors = vectors();    assert!(        vectors.envelope_messages.len() >= 27,        "the table should not shrink"    );    for case in &vectors.envelope_messages {        let kind = match case.kind.as_deref() {            Some("group") => EnvelopeKind::Group,            _ => EnvelopeKind::Dm,        };        let at = case.at.as_deref().unwrap_or("message");        assert_eq!(            validate_envelope_message(&case.value, at, kind),            case.issues,            "{}",            case.name        );    }}#[test]fn every_batch_issue_is_the_typescripts_own_sentence() {    let vectors = vectors();    assert!(vectors.batches.len() >= 16, "the table should not shrink");    for case in &vectors.batches {        assert_eq!(            validate_import_batch(&case.value),            case.issues,            "{}",            case.name        );    }}#[test]fn the_cap_is_the_typescripts_cap() {    for case in &vectors().caps {        let messages: Vec<Value> = (0..case.count).map(|_| message(json!({}))).collect();        let batch =            json!({ "workspaceId": WORKSPACE, "channel": "whatsapp", "messages": messages });        assert_eq!(validate_import_batch(&batch), case.issues, "{}", case.count);    }}// RULE: The normalized import envelope carries owned media keys, never retired worker URLs.#[test]fn media_needs_a_key_and_refuses_remote_urls() {    for scheme in ["http", "https"] {        let entry = json!({ "url": format!("{scheme}://example.invalid/synthetic.jpg"), "contentType": "image/jpeg" });        let joined = dm(&message(json!({ "media": [entry.clone()] }))).join(" ");        assert!(joined.contains("expected a non-empty \"key\""), "{joined}");        assert!(serde_json::from_value::<EnvelopeMedia>(entry).is_err());    }}/// The envelope round-trips: what the normalizer produces deserialises back/// into the same value, and its camelCase spelling is the wire's.#[test]fn the_typed_message_serialises_to_the_wire_spelling() {    let message = EnvelopeMessage {        phone: Some("919876543210".to_string()),        email: None,        sender_label: None,        display_name: Some("Anita Rao".to_string()),        direction: Direction::In,        body: "hello".to_string(),        media: None,        sent_at: "2025-07-26T10:12:45.000Z".to_string(),        external_id: "txt2:abc".to_string(),        reply_to_external_id: None,        reactions: None,        meta: None,    };    let value = serde_json::to_value(&message).expect("serialises");    assert_eq!(        value,        json!({            "phone": "919876543210",            "displayName": "Anita Rao",            "direction": "in",            "body": "hello",            "sentAt": "2025-07-26T10:12:45.000Z",            "externalId": "txt2:abc",        })    );    assert_eq!(        validate_envelope_message(&value, "message", EnvelopeKind::Dm),        Vec::<String>::new()    );}