Cotton code
683 lines · 22.1 KB · RustRaw
//! Ported case-for-case from `packages/import-core/__tests__/post.test.ts`,//! plus vector tables read out of Node for the two string-valued functions//! (`describeCounts`, `describeFailure`) and Node goldens for the bodies//! `batchBody` composes.//!//! Every fixture is SYNTHETIC — invented numbers, invented names, invented//! words.use super::*;use crate::import::envelope::{    validate_import_batch, Direction, EnvelopeThreadParticipant, MAX_BATCH_MESSAGES,};use crate::import::normalize::ChatReport;use serde_json::json;const WORKSPACE: &str = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";/// `new Date(Date.UTC(2025, 6, 26, 0, 0, index)).toISOString()` — the/// TypeScript fixture's instants, one second apart, read out of Node for/// index 0, 1, 2 and 59.fn sent_at(index: usize) -> String {    let base = js::parse_date_ms("2025-07-26T00:00:00.000Z").expect("the base instant parses");    js::to_iso_string(base + (index as i64) * 1000).expect("an instant in range")}fn message(index: usize, phone: &str) -> EnvelopeMessage {    EnvelopeMessage {        phone: Some(phone.to_string()),        email: None,        sender_label: None,        display_name: None,        direction: if index.is_multiple_of(2) {            Direction::In        } else {            Direction::Out        },        body: format!("message {index}"),        media: None,        sent_at: sent_at(index),        external_id: format!("id-{phone}-{index}"),        reply_to_external_id: None,        reactions: None,        meta: None,    }}fn chat_report(phone: &str, count: i64) -> ChatReport {    ChatReport {        kind: None,        title: None,        participants: None,        system_imported: None,        phone: Some(phone.to_string()),        display_name: None,        messages: count,        inbound: 0,        outbound: 0,        first_sent_at: None,        last_sent_at: None,        reply_refs: 0,        unresolved_reply_refs: 0,        reactions: 0,        attachments: 0,        omitted_media: 0,        system_skipped: 0,        album_containers_dropped: 0,        warnings: Vec::new(),    }}fn chat(phone: &str, count: usize) -> NormalizedChat {    NormalizedChat {        kind: "dm".to_string(),        phone: Some(phone.to_string()),        display_name: Some(format!("Contact {phone}")),        title: None,        external_key: None,        participants: Vec::new(),        counterpart: Some(EnvelopeCounterpart {            label: format!("Contact {phone}"),            email: None,            phone: Some(phone.to_string()),            person_id: None,            handle: None,        }),        messages: (0..count).map(|index| message(index, phone)).collect(),        report: chat_report(phone, count as i64),    }}fn group_chat() -> NormalizedChat {    NormalizedChat {        kind: "group".to_string(),        phone: None,        display_name: Some("Trip".to_string()),        title: Some("Trip".to_string()),        external_key: Some("wa:group:trip".to_string()),        participants: vec![EnvelopeThreadParticipant {            label: "Asha".to_string(),            email: None,            phone: Some("919000000001".to_string()),            person_id: None,            handle: None,        }],        counterpart: None,        messages: vec![message(0, "919000000001"), message(1, "919000000001")],        report: chat_report("919000000001", 2),    }}fn plan(chats: &[NormalizedChat]) -> Vec<Batch> {    plan_batches(chats, DEFAULT_BATCH_SIZE).expect("the default cap is legal")}/* ── planBatches ────────────────────────────────────────────────────────── *//// Keeps a small chat in one request.#[test]fn keeps_a_small_chat_in_one_request() {    let batches = plan(&[chat("919876543210", 10)]);    assert_eq!(batches.len(), 1);    assert_eq!(batches[0].part, 1);    assert_eq!(batches[0].parts, 1);}/// Chunks at the 500-message cap.#[test]fn chunks_at_the_500_message_cap() {    let batches = plan(&[chat("919876543210", 1200)]);    assert_eq!(        batches            .iter()            .map(|batch| batch.messages.len())            .collect::<Vec<_>>(),        vec![500, 500, 200]    );    assert!(batches        .iter()        .all(|batch| batch.messages.len() <= MAX_BATCH_MESSAGES));}/// Never mixes two conversations in one request.#[test]fn never_mixes_two_conversations_in_one_request() {    let batches = plan(&[chat("919876543210", 600), chat("919999999999", 3)]);    for batch in &batches {        let phones: std::collections::HashSet<Option<&str>> = batch            .messages            .iter()            .map(|message| message.phone.as_deref())            .collect();        assert_eq!(phones.len(), 1);    }}/// Keeps a chat's messages contiguous and in order, so replies resolve/// in-batch.#[test]fn keeps_a_chats_messages_contiguous_and_in_order() {    let batches = plan(&[chat("919876543210", 1000)]);    let ids: Vec<String> = batches        .iter()        .flat_map(|batch| batch.messages.iter().map(|m| m.external_id.clone()))        .collect();    let expected: Vec<String> = chat("919876543210", 1000)        .messages        .iter()        .map(|m| m.external_id.clone())        .collect();    assert_eq!(ids, expected);}/// Keeps a chat whose counterpart is only a name — the dm block names them.#[test]fn keeps_a_chat_whose_counterpart_is_only_a_name() {    let mut named = chat("919876543210", 5);    named.phone = None;    named.counterpart = Some(EnvelopeCounterpart {        label: "Asha".to_string(),        email: None,        phone: None,        person_id: None,        handle: None,    });    let batches = plan(&[named]);    assert_eq!(batches.len(), 1);    assert_eq!(        batch_body(&batches[0], WORKSPACE, None).dm,        Some(EnvelopeCounterpart {            label: "Asha".to_string(),            email: None,            phone: None,            person_id: None,            handle: None,        })    );}/// Skips a chat with nobody on the other side.#[test]fn skips_a_chat_with_nobody_on_the_other_side() {    let mut orphan = chat("919876543210", 5);    orphan.phone = None;    orphan.counterpart = None;    assert!(plan(&[orphan]).is_empty());}/// Honours a smaller batch size.#[test]fn honours_a_smaller_batch_size() {    let batches = plan_batches(&[chat("919876543210", 5)], 2).expect("2 is legal");    assert_eq!(        batches            .iter()            .map(|batch| batch.messages.len())            .collect::<Vec<_>>(),        vec![2, 2, 1]    );}/// Refuses a nonsensical batch size — with the TypeScript's own sentence, so a/// handler can pass it to the error envelope unchanged. Node goldens.#[test]fn refuses_a_nonsensical_batch_size() {    let zero = plan_batches(&[chat("919876543210", 5)], 0).unwrap_err();    assert_eq!(zero.to_string(), "Batch size must be at least 1, got 0");    let negative = plan_batches(&[chat("919876543210", 5)], -3).unwrap_err();    assert_eq!(        negative.to_string(),        "Batch size must be at least 1, got -3"    );}/// A chat with no messages never becomes a batch — an address-book shell is/// not a conversation.#[test]fn an_empty_chat_becomes_no_batch() {    assert!(plan(&[chat("919876543210", 0)]).is_empty());}/// A group with no title (or no external key) has no identity for the server/// to find its thread by, and is skipped rather than filed under an invented/// one. Node golden: `planBatches` answers an empty list.#[test]fn skips_a_group_with_no_identity() {    let mut untitled = group_chat();    untitled.title = None;    assert!(plan(&[untitled]).is_empty());    let mut keyless = group_chat();    keyless.external_key = None;    assert!(plan(&[keyless]).is_empty());}/// A group batch carries its thread block, and no dm block — Node golden.#[test]fn a_group_batch_carries_the_thread_block() {    let batches = plan(&[group_chat()]);    assert_eq!(batches.len(), 1);    assert_eq!(batches[0].kind, "group");    assert_eq!(batches[0].phone, None);    assert_eq!(batches[0].display_name.as_deref(), Some("Trip"));    assert_eq!(batches[0].part, 1);    assert_eq!(batches[0].parts, 1);    let body = batch_body(&batches[0], "ws-1", None);    assert_eq!(body.dm, None);    let thread = body.thread.expect("a group batch carries its thread");    assert_eq!(thread.kind, "group");    assert_eq!(thread.title, "Trip");    assert_eq!(thread.external_key, "wa:group:trip");    assert_eq!(thread.participants.len(), 1);    assert_eq!(thread.participants[0].label, "Asha");}/* ── batchBody ──────────────────────────────────────────────────────────── *//// Carries the workspace and channel the importer needs.#[test]fn batch_body_carries_the_workspace_and_channel() {    let batches = plan(&[chat("919876543210", 2)]);    let body = batch_body(&batches[0], WORKSPACE, None);    assert_eq!(body.workspace_id, WORKSPACE);    assert_eq!(body.channel, "whatsapp");    let value = serde_json::to_value(&body).expect("a batch serialises");    assert_eq!(validate_import_batch(&value), Vec::<String>::new());}/// Node golden: the whole dm body, message instants included. The reserved/// thread id rides only when the caller gave one.#[test]fn batch_body_matches_the_node_golden() {    let batches = plan(&[chat("919000000001", 2)]);    let without =        serde_json::to_value(batch_body(&batches[0], WORKSPACE, None)).expect("a batch serialises");    assert_eq!(        without,        json!({            "workspaceId": WORKSPACE,            "channel": "whatsapp",            "messages": [                {                    "phone": "919000000001",                    "direction": "in",                    "body": "message 0",                    "sentAt": "2025-07-26T00:00:00.000Z",                    "externalId": "id-919000000001-0",                },                {                    "phone": "919000000001",                    "direction": "out",                    "body": "message 1",                    "sentAt": "2025-07-26T00:00:01.000Z",                    "externalId": "id-919000000001-1",                },            ],            "dm": { "label": "Contact 919000000001", "phone": "919000000001" },        })    );    let with = batch_body(&batches[0], WORKSPACE, Some("thread-1"));    assert_eq!(with.new_thread_id.as_deref(), Some("thread-1"));}/// The fixture's own instants, read out of Node — the helper above must build/// the same four the TypeScript test does.#[test]fn the_fixture_instants_match_node() {    assert_eq!(sent_at(0), "2025-07-26T00:00:00.000Z");    assert_eq!(sent_at(1), "2025-07-26T00:00:01.000Z");    assert_eq!(sent_at(2), "2025-07-26T00:00:02.000Z");    assert_eq!(sent_at(59), "2025-07-26T00:00:59.000Z");}/* ── addTotals / describeCounts ─────────────────────────────────────────── */fn outcome(totals: Option<ImportTotals>, chats: Vec<ChatResult>) -> BatchOutcome {    BatchOutcome {        batch: plan(&[chat("919876543210", 1)]).remove(0),        ok: true,        status: 200,        body: Some(Value::Null),        totals,        chats,        thread: None,        existing_oldest_sent_at: None,    }}fn chat_row(inserted: Option<f64>, skipped: Option<f64>, unresolved: Option<f64>) -> ChatResult {    ChatResult {        phone: None,        inserted,        skipped,        unresolved_replies: unresolved,        extra: Map::new(),    }}fn totals(inserted: f64, skipped: f64, unresolved: f64) -> ImportTotals {    ImportTotals {        chats: None,        inserted: Some(inserted),        skipped: Some(skipped),        unresolved_replies: Some(unresolved),    }}/// Sums across the batches one conversation was split into.#[test]fn sums_across_the_batches_one_conversation_was_split_into() {    let mut running = EMPTY_TOTALS;    running = add_totals(        &running,        &outcome(Some(totals(500.0, 0.0, 4.0)), Vec::new()),    );    running = add_totals(        &running,        &outcome(Some(totals(120.0, 3.0, 1.0)), Vec::new()),    );    assert_eq!(running.inserted, Some(620.0));    assert_eq!(running.skipped, Some(3.0));    assert_eq!(running.unresolved_replies, Some(5.0));}/// Falls back to the per-chat rows when the response carries no totals.#[test]fn falls_back_to_the_per_chat_rows() {    let running = add_totals(        &EMPTY_TOTALS,        &outcome(None, vec![chat_row(Some(7.0), Some(1.0), Some(0.0))]),    );    assert_eq!(running.inserted, Some(7.0));    assert_eq!(running.skipped, Some(1.0));}/// Node golden: two chat rows, one of which never mentioned `skipped`. The/// missing half stays missing rather than becoming a zero.#[test]fn per_chat_fallback_sums_two_rows_matching_node() {    let running = add_totals(        &EMPTY_TOTALS,        &outcome(            None,            vec![                chat_row(Some(7.0), Some(1.0), Some(0.0)),                chat_row(Some(2.0), None, Some(3.0)),            ],        ),    );    assert_eq!(        running,        ImportTotals {            chats: None,            inserted: Some(9.0),            skipped: Some(1.0),            unresolved_replies: Some(3.0),        }    );}/// Keeps "the server never said" as null rather than reporting a false zero.#[test]fn keeps_the_server_never_said_as_null() {    assert_eq!(        add_totals(&EMPTY_TOTALS, &outcome(None, Vec::new())),        EMPTY_TOTALS    );    assert_eq!(describe_counts(&EMPTY_TOTALS), "");}/// Renders only what is known, and singularises one unresolved reply.#[test]fn renders_only_what_is_known() {    assert_eq!(        describe_counts(&ImportTotals {            chats: None,            inserted: Some(4.0),            skipped: None,            unresolved_replies: Some(1.0),        }),        "4 inserted · 1 reply still unresolved"    );    assert_eq!(        describe_counts(&ImportTotals {            chats: None,            inserted: Some(4.0),            skipped: Some(2.0),            unresolved_replies: Some(0.0),        }),        "4 inserted · 2 skipped"    );}/// Node vectors (11). A zero `inserted` still prints (it is KNOWN to be zero),/// while a zero `unresolvedReplies` does not — the difference is deliberate,/// and so is a NEGATIVE count staying silent on the same `> 0` test.#[test]fn describe_counts_matches_node() {    /// (inserted, skipped, unresolvedReplies, the rendered line).    type CountVector = (Option<f64>, Option<f64>, Option<f64>, &'static str);    let vectors: [CountVector; 11] = [        (None, None, None, ""),        (            Some(4.0),            None,            Some(1.0),            "4 inserted · 1 reply still unresolved",        ),        (Some(4.0), Some(2.0), Some(0.0), "4 inserted · 2 skipped"),        (            Some(12.0),            Some(3.0),            Some(1.0),            "12 inserted · 3 skipped · 1 reply still unresolved",        ),        (            Some(0.0),            Some(0.0),            Some(2.0),            "0 inserted · 0 skipped · 2 replies still unresolved",        ),        (None, Some(7.0), None, "7 skipped"),        (None, None, Some(5.0), "5 replies still unresolved"),        (None, None, Some(1.0), "1 reply still unresolved"),        (            Some(620.0),            Some(3.0),            Some(5.0),            "620 inserted · 3 skipped · 5 replies still unresolved",        ),        (Some(-1.0), None, Some(-2.0), "-1 inserted"),        (Some(0.0), None, None, "0 inserted"),    ];    for (inserted, skipped, unresolved, expected) in vectors {        let value = ImportTotals {            chats: Some(3.0),            inserted,            skipped,            unresolved_replies: unresolved,        };        assert_eq!(            describe_counts(&value),            expected,            "describeCounts({value:?})"        );    }}/* ── describeFailure ────────────────────────────────────────────────────── */fn failure(status: i64, body: Option<Value>) -> BatchOutcome {    BatchOutcome {        batch: plan(&[chat("919876543210", 1)]).remove(0),        ok: false,        status,        body,        totals: None,        chats: Vec::new(),        thread: None,        existing_oldest_sent_at: None,    }}/// Node vectors (12). A numeric `code` is NOT bracketed (the test is/// `typeof === "string"`), an object with no string `error` falls through to/// `JSON.stringify`, and a body nobody read at all renders as the literal/// `undefined` — which is what a JavaScript template does with it.#[test]fn describe_failure_matches_node() {    let vectors: [(i64, Option<Value>, &str); 12] = [        (500, Some(json!("boom")), "HTTP 500 — boom"),        (            400,            Some(json!({ "error": "bad batch" })),            "HTTP 400 — bad batch",        ),        (            400,            Some(json!({ "error": "bad batch", "code": "E_BAD" })),            "HTTP 400 — bad batch (E_BAD)",        ),        (            400,            Some(json!({ "error": "bad batch", "code": 42 })),            "HTTP 400 — bad batch",        ),        (            404,            Some(json!({ "message": "nope" })),            r#"HTTP 404 — {"message":"nope"}"#,        ),        (502, Some(Value::Null), "HTTP 502 — null"),        (503, None, "HTTP 503 — undefined"),        (500, Some(json!([1, 2])), "HTTP 500 — [1,2]"),        (500, Some(json!(17)), "HTTP 500 — 17"),        (            401,            Some(json!({ "error": 7, "code": "X" })),            r#"HTTP 401 — {"error":7,"code":"X"}"#,        ),        (418, Some(json!({})), "HTTP 418 — {}"),        (500, Some(json!("")), "HTTP 500 — "),    ];    for (status, body, expected) in vectors {        assert_eq!(            describe_failure(&failure(status, body.clone())),            expected,            "describeFailure({status}, {body:?})"        );    }}/* ── the response readers ───────────────────────────────────────────────── *//// Everything the reader has no opinion about is KEPT, in the order the/// importer sent it — the importer owns this shape, and today's reader must/// not hide tomorrow's field.#[test]fn parse_chat_result_keeps_the_unknown_keys() {    let parsed = parse_chat_result(&json!({        "phone": "919000000001",        "inserted": 4,        "skipped": 1,        "unresolvedReplies": 0,        "threadId": "t-1",        "resolution": "overlap",    }))    .expect("an object parses");    assert_eq!(parsed.phone.as_deref(), Some("919000000001"));    assert_eq!(parsed.inserted, Some(4.0));    assert_eq!(        parsed.extra.keys().collect::<Vec<_>>(),        vec!["threadId", "resolution"]    );    assert_eq!(parse_chat_result(&json!([1])), None);    assert_eq!(parse_chat_result(&Value::Null), None);}/// A count that is not a finite number is not a count.#[test]fn a_non_finite_count_is_not_a_count() {    let parsed =        parse_chat_result(&json!({ "inserted": "4", "skipped": null })).expect("an object parses");    assert_eq!(parsed.inserted, None);    assert_eq!(parsed.skipped, None);    assert_eq!(parse_totals(&json!("x")), None);    assert_eq!(        parse_totals(&json!({ "chats": 2, "inserted": 9 })),        Some(ImportTotals {            chats: Some(2.0),            inserted: Some(9.0),            skipped: None,            unresolved_replies: None,        })    );}/// The speculative lookup reads the top level, then one level of the usual/// per-chat wrappers — array or single object — and a miss is not an error.#[test]fn find_field_looks_one_level_into_the_usual_wrappers() {    let names = ["existingOldestSentAt", "oldestSentAt"];    assert_eq!(        find_field(            &json!({ "existingOldestSentAt": "2024-03-01T00:00:00.000Z" }),            &names        ),        Some(&json!("2024-03-01T00:00:00.000Z"))    );    assert_eq!(        find_field(            &json!({ "chats": [{ "oldestSentAt": "2024-03-02T00:00:00.000Z" }] }),            &names        ),        Some(&json!("2024-03-02T00:00:00.000Z"))    );    // A single object, not an array — the TypeScript wraps it.    assert_eq!(        find_field(            &json!({ "result": { "oldestSentAt": "2024-03-03T00:00:00.000Z" } }),            &names        ),        Some(&json!("2024-03-03T00:00:00.000Z"))    );    assert_eq!(find_field(&json!({ "data": "nope" }), &names), None);    assert_eq!(find_field(&json!([1, 2]), &names), None);    // A key that IS present but null is FOUND — `!== undefined`, not truthy.    assert_eq!(        find_field(&json!({ "existingOldestSentAt": null }), &names),        Some(&Value::Null)    );}/// A string that is not an instant is not an instant, and a non-string never/// was.#[test]fn as_iso_or_null_keeps_only_a_parseable_instant() {    assert_eq!(        as_iso_or_null(&json!("2024-03-01T04:00:00.000Z")).as_deref(),        Some("2024-03-01T04:00:00.000Z")    );    assert_eq!(as_iso_or_null(&json!("not a date")), None);    assert_eq!(as_iso_or_null(&json!(1_700_000_000_000i64)), None);    assert_eq!(as_iso_or_null(&Value::Null), None);}/// `asCountOrNull` is `typeof === "number" && Number.isFinite`.#[test]fn as_count_or_null_refuses_anything_that_is_not_a_finite_number() {    assert_eq!(as_count_or_null(&json!(4)), Some(4.0));    assert_eq!(as_count_or_null(&json!(-2.5)), Some(-2.5));    assert_eq!(as_count_or_null(&json!("4")), None);    assert_eq!(as_count_or_null(&Value::Null), None);    assert_eq!(as_count_or_null(&json!(true)), None);}/// The cap this module defaults to is the envelope's, not a second opinion.#[test]fn the_default_batch_size_is_the_envelopes_cap() {    assert_eq!(DEFAULT_BATCH_SIZE, MAX_BATCH_MESSAGES as i64);    assert_eq!(DEFAULT_BATCH_SIZE, 500);}