//! Batching and counting for the message import — the port of//! `packages/import-core/src/post.ts`.//!//! ## Batching//!//! Spec §8 caps a request at 500 messages. Chunks are cut PER CHAT and in time//! order, which matters for more than tidiness: the importer resolves//! `reply_to_external_id` against the same batch, so keeping a conversation//! contiguous and chronological maximises how many reply links land on the//! first pass. Unresolved refs are kept raw on the row either way, so nothing//! is lost — they just need a later pass.//!//! ## What is NOT here, and why the name still is//!//! `postBatch` used to live in this module: it POSTed a batch to the//! `cotton-msg-import` edge function with `Authorization: Bearer <token>` and//! the Supabase `apikey` beside it. It went with the cells (pairing PR 6) —//! there is no edge function and no anon key, its only caller had already//! gone, and a credential-building path re-exported from that barrel is//! reachable from the phone's bundle even with nobody calling it. The//! PLANNING and COUNTING halves are live and stay, which is all this port is.//!//! What the app does instead is compose the same body with [`batch_body`] and//! post it through the server transport, which signs with the device's key and//! sends no bearer.//!//! ## What the port changed//!//! The response readers ([`parse_chat_result`], [`parse_totals`],//! [`find_field`], [`as_iso_or_null`], [`as_count_or_null`]) are PRIVATE in the//! TypeScript, because `postBatch` was their only caller and it is gone. They//! are public here: the caller that rebuilds that leg lives in another crate,//! and a private unused function in Rust is a warning rather than a quiet//! module-scope declaration.//!//! Counts are `f64`, not integers, because they are JSON `number`s the server//! sends and [`describe_counts`] renders them with JavaScript's own//! number-to-string. A server that ever answered `4.5` would read the same on//! both sides rather than being silently truncated by the reader.use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use thiserror::Error;usecrate::import::envelope::{EnvelopeCounterpart, EnvelopeMessage, EnvelopeThread, ImportBatch, MAX_BATCH_MESSAGES,};usecrate::import::normalize::NormalizedChat;use cotton_store::protocol::js;/// One request's worth of one conversation.#[derive(Debug, Clone, PartialEq)]pubstructBatch {/// `"dm"` or `"group"` — the chat's own `kind`, carried verbatim.pub kind: String,/// dm: canonical contact phone. Group: `None` — identity lives in/// `thread`.pub phone: Option<String>,pub display_name: Option<String>,/// Group batches carry the thread block on EVERY part — the server is/// stateless.pub thread: Option<EnvelopeThread>,/// dm batches carry the counterpart on every part, phone or not.pub dm: Option<EnvelopeCounterpart>,pub messages: Vec<EnvelopeMessage>,/// 1-based part number within this chat, and how many parts it has.pub part: usize,pub parts: usize,}#[derive(Debug, Clone, PartialEq, Eq, Error)]pubenumPostError {/// The TypeScript's sentence verbatim, so a handler can pass it straight/// to the error envelope. #[error("Batch size must be at least 1, got {0}")]BatchSizeTooSmall(i64),}/// Cut every chat into contiguous, chronological chunks no larger than the cap.////// `size` is `MAX_BATCH_MESSAGES` in the TypeScript's default position; Rust/// has no default arguments, so every caller states it (pass/// [`MAX_BATCH_MESSAGES`]).pubfn plan_batches(chats: &[NormalizedChat], size: i64) -> Result<Vec<Batch>, PostError> {if size < 1 {returnErr(PostError::BatchSizeTooSmall(size)); }let size = size as usize;letmut batches: Vec<Batch> = Vec::new();for chat in chats {if chat.messages.is_empty() {continue; }letmut thread: Option<EnvelopeThread> = None;letmut dm: Option<EnvelopeCounterpart> = None;if chat.kind == "group" {// A group with no title or no external key has no identity for the// server to find the thread by, and inventing one would make every// re-import a second thread.let (Some(title), Some(external_key)) = (chat.title.as_ref(), chat.external_key.as_ref())else {continue; }; thread = Some(EnvelopeThread { kind: "group".to_string(), title: title.clone(), external_key: external_key.clone(), participants: chat.participants.clone(), }); } else {// Nobody but the owner spoke and no number was given: there is no// person to file this against.letSome(counterpart) = chat.counterpart.as_ref() else {continue; }; dm = Some(counterpart.clone()); }let parts = chat.messages.len().div_ceil(size);for part in0..parts {let from = part * size;let to = ((part + 1) * size).min(chat.messages.len()); batches.push(Batch { kind: chat.kind.clone(), phone: chat.phone.clone(), display_name: chat.display_name.clone(), thread: thread.clone(), dm: dm.clone(), messages: chat.messages[from..to].to_vec(), part: part + 1, parts, }); } }Ok(batches)}/// The POST body one batch becomes.////// `new_thread_id` is the id the caller reserved so it could key this batch's/// attachments before the write. Honoured only if the thread has to be created/// (see `ImportBatch`).pubfn batch_body(batch: &Batch, workspace_id: &str, new_thread_id: Option<&str>) -> ImportBatch {ImportBatch { workspace_id: workspace_id.to_string(), channel: "whatsapp".to_string(), thread: batch.thread.clone(), dm: batch.dm.clone(), messages: batch.messages.clone(), new_thread_id: new_thread_id.map(str::to_string), }}/// One conversation's result, as the importer reports it.////// Extra fields are preserved rather than dropped: the importer owns this/// shape, and a reader that only understands today's keys should not hide/// tomorrow's. `extra` is a `serde_json::Map`, which the workspace builds with/// `preserve_order`, so the passthrough keeps the order the server sent.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructChatResult {pub phone: Option<String>,pub inserted: Option<f64>,pub skipped: Option<f64>,pub unresolved_replies: Option<f64>,/// Everything the importer sent that this reader has no opinion about./// A NESTED field, exactly as the TypeScript interface declares it — not a/// flattened passthrough, or a server key called `extra` would collide/// with the bag meant to hold it.pub extra: Map<String, Value>,}#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructImportTotals {pub chats: Option<f64>,pub inserted: Option<f64>,pub skipped: Option<f64>,pub unresolved_replies: Option<f64>,}#[derive(Debug, Clone, PartialEq)]pubstructBatchOutcome {pub batch: Batch,pub ok: bool,pub status: i64,/// The response body. `None` is JavaScript's `undefined` (no body was/// read at all) and `Some(Value::Null)` is a literal `null` — the two/// render differently in [`describe_failure`], as they do in the/// TypeScript.pub body: Option<Value>,/// `totals` from the response, when it carried a recognisable one.pub totals: Option<ImportTotals>,/// `chats[]` from the response — one entry per conversation in the batch.pub chats: Vec<ChatResult>,/// The importer's group-thread outcome (`{threadId, resolution:/// "external-key" | "overlap" | "created"}`), passed through untyped — the/// importer owns the shape.pub thread: Option<Map<String, Value>>,/// The oldest message the thread already held, IF the importer reports it.////// Spec §2.3 wants a truncation warning when an import's oldest message is/// YOUNGER than what is already stored. The importer does not send this/// today, so it is read speculatively and is simply absent — the/// report-side heuristics stand in until it exists.pub existing_oldest_sent_at: Option<String>,}/// JavaScript's `isRecord`: an object, and NOT an array. `null` is neither.fn as_record(value: &Value) -> Option<&Map<String, Value>> { value.as_object()}/// Speculative field lookup, used only for `existingOldestSentAt` — a fact the/// importer does not report yet.////// Checks the top level and one level of the usual per-chat wrappers, in both/// cases. A miss is not an error. `None` here is JavaScript's `undefined`; a/// key present but `null` is found and answers `Value::Null`, exactly as/// `body[name] !== undefined` does.pubfn find_field<'a>(body: &'a Value, names: &[&str]) -> Option<&'a Value> {let record = as_record(body)?;for name in names {ifletSome(found) = record.get(*name) {returnSome(found); } }for wrapper in ["chats", "results", "chat", "result", "data"] {letSome(nested) = record.get(wrapper) else {continue; };// `Array.isArray(nested) ? nested : [nested]` — a single object is// wrapped, and a non-record (a string, a null) simply fails `isRecord`// below.let rows: Vec<&Value> = match nested.as_array() {Some(array) => array.iter().collect(),None => vec![nested], };for row in rows {letSome(row) = as_record(row) else { continue };for name in names {ifletSome(found) = row.get(*name) {returnSome(found); } } } }None}/// A string that parses as an instant, or `None`.////// The TypeScript asks `new Date(value)`, which accepts implementation-defined/// spellings beyond the ISO grammar; `js::parse_date_ms` accepts the Date Time/// String Format only. Nothing the importer sends uses another spelling, and/// the store's own instants are all ISO — but a `"March 1, 2024"` would be/// kept by Node and dropped here, which is the one place the two can differ.pubfn as_iso_or_null(value: &Value) -> Option<String> {let text = value.as_str()?; js::parse_date_ms(text).map(|_| text.to_string())}/// `typeof value === "number" && Number.isFinite(value)`.pubfn as_count_or_null(value: &Value) -> Option<f64> { value.as_f64().filter(|number| number.is_finite())}/// The keys this reader interprets; everything else on a chat row is kept in/// `extra`.const KNOWN_CHAT_RESULT_KEYS: [&str; 4] = ["phone", "inserted", "skipped", "unresolvedReplies"];/// One `chats[]` row of the response, or `None` when it is not an object.pubfn parse_chat_result(value: &Value) -> Option<ChatResult> {let record = as_record(value)?;letmut extra = Map::new();for (key, entry) in record {if !KNOWN_CHAT_RESULT_KEYS.contains(&key.as_str()) { extra.insert(key.clone(), entry.clone()); } }Some(ChatResult { phone: record .get("phone") .and_then(Value::as_str) .map(str::to_string), inserted: record.get("inserted").and_then(as_count_or_null), skipped: record.get("skipped").and_then(as_count_or_null), unresolved_replies: record.get("unresolvedReplies").and_then(as_count_or_null), extra, })}/// The response's `totals` block, or `None` when it is not an object.pubfn parse_totals(value: &Value) -> Option<ImportTotals> {let record = as_record(value)?;Some(ImportTotals { chats: record.get("chats").and_then(as_count_or_null), inserted: record.get("inserted").and_then(as_count_or_null), skipped: record.get("skipped").and_then(as_count_or_null), unresolved_replies: record.get("unresolvedReplies").and_then(as_count_or_null), })}/// Nothing has been counted yet.pubconst EMPTY_TOTALS: ImportTotals = ImportTotals { chats: None, inserted: None, skipped: None, unresolved_replies: None,};/// Fold one batch's outcome into the running totals.////// The response's own `totals` wins; without one the per-chat rows are summed,/// and `chats` stays `None` because a count of conversations is not something/// a list of rows can honestly answer for the run.pubfn add_totals(running: &ImportTotals, outcome: &BatchOutcome) -> ImportTotals {let source = outcome.totals.unwrap_or_else(|| { outcome .chats .iter() .fold(EMPTY_TOTALS, |accumulator, chat| ImportTotals { chats: None, inserted: sum(accumulator.inserted, chat.inserted), skipped: sum(accumulator.skipped, chat.skipped), unresolved_replies: sum(accumulator.unresolved_replies, chat.unresolved_replies), }) });ImportTotals { chats: sum(running.chats, source.chats), inserted: sum(running.inserted, source.inserted), skipped: sum(running.skipped, source.skipped), unresolved_replies: sum(running.unresolved_replies, source.unresolved_replies), }}/// `null + null` stays `null`, so "the server never told us" never renders as/// 0.fn sum(a: Option<f64>, b: Option<f64>) -> Option<f64> {match (a, b) { (None, b) => b, (a, None) => a, (Some(a), Some(b)) => Some(a + b), }}/// `12 inserted · 3 skipped · 1 reply still unresolved`, omitting what is/// unknown.////// The numbers go through JavaScript's own number-to-string, so a count the/// server sent as `4.5` reads the same on both sides.pubfn describe_counts(totals: &ImportTotals) -> String {letmut parts: Vec<String> = Vec::new();ifletSome(inserted) = totals.inserted { parts.push(format!("{} inserted", js::number_to_string(inserted))); }ifletSome(skipped) = totals.skipped { parts.push(format!("{} skipped", js::number_to_string(skipped))); }ifletSome(unresolved) = totals.unresolved_replies {// `> 0` — a zero is not worth a line, and a NEGATIVE one is not worth// one either, exactly as the TypeScript's comparison decides.if unresolved > 0.0 {let noun = if unresolved == 1.0 {"reply" } else {"replies" }; parts.push(format!("{} {noun} still unresolved", js::number_to_string(unresolved) )); } } parts.join(" · ")}/// Human-readable failure line for a batch that did not land.////// A string body is the detail; an object with a string `error` is that/// sentence plus a string `code` in brackets; anything else is the body as/// JSON. `undefined` (no body) renders as the literal `"undefined"`, which is/// what a JavaScript template does with it.pubfn describe_failure(outcome: &BatchOutcome) -> String {let detail = match outcome.body.as_ref() {None => "undefined".to_string(),Some(Value::String(text)) => text.clone(),Some(body) => {let error = as_record(body) .and_then(|record| record.get("error")) .and_then(Value::as_str);match error {Some(error) => {let code = as_record(body) .and_then(|record| record.get("code")) .and_then(Value::as_str);match code {Some(code) => format!("{error} ({code})"),None => error.to_string(), } }None => js::json_stringify(body), } } }; format!("HTTP {} — {detail}", outcome.status)}/// Re-exported so a caller can spell the cap without reaching into/// `envelope`, as the TypeScript's default argument does.pubconst DEFAULT_BATCH_SIZE: i64 = MAX_BATCH_MESSAGES as i64;#[cfg(test)]#[path = "post_tests.rs"]mod tests;