//! THE MESSAGE IMPORT ENGINE — the port of //! `packages/core/src/services/messagesImport.service.ts`. //! //! One implementation of "who this message is from, which thread it belongs to, //! which contact it resolves to, and what a re-import skips". The TypeScript is //! shared by the phone, the server and the Mac for exactly that reason, and a //! second copy of it would be a second answer to the only question an importer //! is ever asked. //! //! ## Why it lives in `cotton-rules` //! //! It runs on the phone (re-exported at `cotton_core::import::messages_engine`) //! and in the Worker as WASM, over a JS driver (`cotton-rules-wasm`), and it //! earns that the same way [`crate::messages::resolve_contact`] does: it is //! DRIVER-IN. It //! opens nothing, holds no connection and mints no id — every read is a method //! on [`ImportDriver`], every write is returned as a [`Change`], and the //! clock and the id source arrive as arguments. What is left is the DECISION //! layer, which is what this crate is for, and which the phone, the server and //! the Mac all have to agree about. //! //! ## The two-phase write, and why it is two //! //! `runBatch` writes twice on purpose. The first batch carries the thread, its //! contacts, its participants, its messages and its reactions — one act, so a //! conversation never lands half-built. The reply pass runs AFTER those rows //! exist, because an archive arrives in batches and a reply routinely lands //! before the line it quotes; it is idempotent, so it runs after every import //! and links whatever the previous run could not. //! //! So the surface here is [`plan_import`] → write → [`plan_reply_links`] → //! write, with [`run_import`] composing the four for a caller that just wants //! the batch applied. A probe ([`probe_import`]) resolves the same threads and //! reports the same difference and writes NOTHING — it takes `&D` and returns no //! changes at all, so "a probe must never write" is a property of the type //! rather than a rule somebody has to remember. //! //! ## What the port could not keep //! //! * **`previewForMessage`'s `try`/`catch`.** The TypeScript casts the //! envelope's `media`/`meta` JSON to the typed shapes and catches whatever the //! preview throws on a malformed entry, because the preview is cosmetic and //! must not sink the batch that carries the messages. Rust has no cast: the //! same JSON is DESERIALISED here, and a deserialisation that fails takes the //! same fallback line the `catch` writes. Same two branches, reached the same //! way. //! * **`storeNewId` / `storeNow` / `storeDb`.** Three process-wide singletons //! in the TypeScript, three arguments here. //! * **The `ApiResponse` envelope.** A `Result` says the same thing, and the //! `NOT_AUTHENTICATED` arm belongs to whatever calls this — there is no //! session in this crate to check. use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use crate::change::Change; use crate::ids::{dm_thread_id, group_thread_id}; use crate::fingerprint::message::{ content_fingerprint, minute_bucket, normalize_body_for_id, ContentFingerprintInput, CONTENT_EXTERNAL_ID_PREFIX, }; use crate::js::collapse_whitespace_and_trim; use crate::ids::REACTION_ACTOR_SELF; use crate::import::envelope::{ EnvelopeMessage, EnvelopeThread, EnvelopeThreadParticipant, ImportBatch, }; use crate::import::group::{group_external_key, slugify_title, GROUP_EXTERNAL_KEY_PREFIX}; use crate::phone::normalize_phone_in; use crate::chat_ids::reaction_row_id; use crate::messages::media_only::{body_is_wordless, media_only_kind}; use crate::messages::preview::{preview_for_message, should_advance_thread, PreviewSource, MESSAGE_PREVIEW_MAX}; use crate::messages::resolve_contact::{ contact_handle_changes, find_contact_by_handle, handle_key, handles_from, normalize_contact_handle_in, people_by_handle, require_handle, resolve_contact, ContactDriver, ContactError, ContactHandle, Region, ContactHandleKind, ContactSource, MatchedPerson, ResolveContactArgs, }; use crate::messages::{js_trim, slice_utf16, MessageMedia, MessageMeta, MessagePoll, MessagePollVoter}; const THREADS: &str = "cotton_msg_threads"; const MESSAGES: &str = "cotton_msg_messages"; const PARTICIPANTS: &str = "cotton_msg_thread_participants"; const REACTIONS: &str = "cotton_msg_reactions"; const WORKSPACES: &str = "cotton_workspaces"; /// How many messages the overlap probe fingerprints against. pub const OVERLAP_PROBE_IDS: usize = 300; /* ---------------------------------------------------------------- helpers -- */ /// The comparison key for a label: layout and case are not identity. /// /// `label.replace(/\s+/g, " ").trim().toLowerCase()` — ECMAScript's whitespace /// class on both the collapse and the trim, and the Unicode default case fold, /// which is what Rust's `to_lowercase` performs. pub fn import_label_key(label: &str) -> String { collapse_whitespace_and_trim(label).to_lowercase() } /// A label that is a number is not a name worth storing as one. /// /// `/^\+?[\d\s().-]{8,}$/` over the trimmed label. `\d` is the ASCII digits (no /// `u` flag), `\s` is ECMAScript's class, and every character the class admits /// is one UTF-16 unit wide — so counting `chars` counts what `{8,}` counts. pub fn label_looks_like_phone(label: &str) -> bool { let trimmed = js_trim(label); let rest = trimmed.strip_prefix('+').unwrap_or(trimmed); rest.chars().count() >= 8 && rest.chars().all(|ch| { ch.is_ascii_digit() || crate::js::is_js_whitespace(ch) || matches!(ch, '(' | ')' | '.' | '-') }) } /// The `{ phone?, email? }` an envelope names its counterpart by. fn source_of(message: &EnvelopeMessage) -> ContactSource<'_> { ContactSource { phone: message.phone.as_deref(), email: message.email.as_deref(), } } /// The same, for a participant block. fn participant_source(participant: &EnvelopeThreadParticipant) -> ContactSource<'_> { ContactSource { phone: participant.phone.as_deref(), email: participant.email.as_deref(), } } /// All identities the source supplied for a participant, with the same /// normalisation the contact and People stores use: a phone without a code is /// read in `region`, the owner's own number's country. pub fn participant_handles(participant: &EnvelopeThreadParticipant, region: Option) -> Vec { let mut handles=handles_from(&participant_source(participant),region); if let Some(handle)=participant.handle.as_ref().and_then(|h|normalize_contact_handle_in(h.kind,&h.value,region)) { if !handles.contains(&handle){handles.push(handle);} } handles } fn sender_handles(message: &EnvelopeMessage, region: Option) -> Vec { let mut handles=handles_from(&source_of(message),region); if let Some(raw)=message.meta.as_ref().and_then(|m|m.get("source")).and_then(|source|source.get("senderHandle")) { if let Ok(raw)=serde_json::from_value::(raw.clone()) { if let Some(handle)=normalize_contact_handle_in(raw.kind,&raw.value,region) { if !handles.contains(&handle){handles.push(handle);} } } } handles } #[derive(Default)] struct ParticipantSeats { labels:BTreeMap>, handles:BTreeMap>, /// The region a sender's code-less number is read in, as the seats' were. region:Option, } impl ParticipantSeats { fn in_region(region:Option)->Self{ParticipantSeats{region,..Default::default()}} fn insert(&mut self,label:&str,handles:&[ContactHandle],seat:&str) { fn add(map:&mut BTreeMap>,key:String,seat:&str){ match map.get(&key){ Some(Some(old)) if old!=seat=>{map.insert(key,None);}, None=>{map.insert(key,Some(seat.into()));}, _=>{}, } } add(&mut self.labels,import_label_key(label),seat); for handle in handles {add(&mut self.handles,handle_key(handle),seat);} } fn sender(&self,message:&EnvelopeMessage)->Option<&str>{ let handles=if message.direction==crate::import::envelope::Direction::In{sender_handles(message,self.region)}else{vec![]}; if !handles.is_empty(){ let mut found=None; for handle in handles { let Some(Some(seat))=self.handles.get(&handle_key(&handle)) else{continue;}; if found.is_some_and(|old|old!=seat.as_str()){return None;} found=Some(seat.as_str()); } return found; } message.sender_label.as_deref().and_then(|label|self.labels.get(&import_label_key(label))).and_then(|seat|seat.as_deref()) } fn len(&self)->usize { self.labels.values().chain(self.handles.values()).filter_map(Option::as_deref).collect::>().len() } } /* ------------------------------------------------------------ the seam ---- */ /// One participant row, as the engine reads it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParticipantRow { pub id: String, pub contact_id: Option, pub display_name: Option, } /// A thread the engine found, and the one column it decides with. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ThreadHit { pub id: String, pub contact_id: Option, } /// What a probe says about a thread that already holds part of this chat. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreadStats { pub count: i64, pub oldest_sent_at: Option, pub newest_sent_at: Option, } /// The winner of the overlap probe: a thread and how many of the probed ids it /// holds. The MAJORITY test is the engine's, not the driver's — a driver that /// applied it would be a second place the rule lives. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OverlapHit { pub thread_id: String, pub contact_id: Option, pub matched: i64, } /// Which kind of thread a question is about. The column holds the string. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ThreadKind { Dm, Group, } impl ThreadKind { pub const fn as_str(self) -> &'static str { match self { ThreadKind::Dm => "dm", ThreadKind::Group => "group", } } } /// The reads this engine asks a file for. /// /// One method per QUESTION rather than a general `all(sql, params)`, for the /// reason [`ContactDriver`] gives: the statements are fixed and declared above, /// so an implementation runs them rather than composing a paraphrase in which a /// workspace filter can go missing. pub trait ImportDriver: ContactDriver { /// `DM_THREAD_BY_CONTACT_SQL`. fn dm_thread_for_contact( &self, workspace_id: &str, contact_id: &str, ) -> Result, ContactError>; /// `THREAD_BY_ID_SQL`. fn thread_by_id( &self, workspace_id: &str, id: &str, kind: ThreadKind, ) -> Result, ContactError>; /// `known_external_ids_sql`. An empty `ids` is never asked. fn known_external_ids( &self, thread_id: &str, channel: &str, ids: &[&str], ) -> Result, ContactError>; /// `THREAD_STATS_SQL`. fn thread_stats(&self, thread_id: &str, channel: &str) -> Result; /// `GROUP_THREAD_BY_KEY_SQL` — the id and the stored title. fn group_thread_by_key( &self, workspace_id: &str, external_key: &str, ) -> Result)>, ContactError>; /// `JID_GROUP_THREADS_SQL` — each thread's id and stored title. fn jid_group_threads( &self, workspace_id: &str, ) -> Result)>, ContactError>; /// `overlap_sql` — the top thread and its count, NOT the majority test. fn thread_by_overlap( &self, workspace_id: &str, channel: &str, kind: ThreadKind, ids: &[&str], ) -> Result, ContactError>; /// `PARTICIPANTS_SQL`. fn participants_of(&self, thread_id: &str) -> Result, ContactError>; /// `THREAD_LAST_MESSAGE_AT_SQL`. The OUTER option is "is there a row at /// all" — a thread this batch is creating has none, which is exactly /// "advance from nothing". fn thread_last_message_at( &self, thread_id: &str, ) -> Result>, ContactError>; /// `THREAD_EXTERNAL_KEY_SQL`, with the same two-level option. fn thread_external_key(&self, thread_id: &str) -> Result>, ContactError>; /// `UNLINKED_REPLIES_SQL` — `(message id, quoted external id)`. fn unlinked_replies(&self, thread_id: &str) -> Result, ContactError>; /// `reply_targets_sql` — `(message id, external id)`. fn messages_by_external_ids( &self, thread_id: &str, channel: &str, ids: &[&str], ) -> Result, ContactError>; /// `held_without_media_sql`. An empty `ids` is never asked. fn held_without_media( &self, thread_id: &str, channel: &str, ids: &[&str], ) -> Result, ContactError>; /// `REAL_ID_BODIES_IN_MINUTE_SQL` — bodies, oldest first. fn real_id_bodies_in_minute( &self, thread_id: &str, channel: &str, minute: &str, ) -> Result, ContactError>; /// `ROWS_IN_MINUTE_SQL` — a thread's rows in one UTC minute, oldest first. fn rows_in_minute( &self, thread_id: &str, channel: &str, minute: &str, ) -> Result, ContactError>; /// `MESSAGE_BY_EXTERNAL_ID_SQL` — the message a later change names. fn message_by_external_id( &self, workspace_id: &str, channel: &str, external_id: &str, ) -> Result, ContactError>; /// `SELF_NAMES_SQL`. The outer option is "is there a workspace row" — /// the TypeScript throws `NOT_FOUND` when there is not. fn self_names_json(&self, workspace_id: &str) -> Result>, ContactError>; /// The country a code-less number in a batch is read in: /// `cotton_store::phone_fold::region_hint` — the owner's first valid phone. /// `None` when the owner has no number. fn owner_region(&self, workspace_id: &str) -> Result, ContactError>; } /* ---------------------------------------------------------------- errors -- */ /// Why an import could not run. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ImportError { /// Whatever the file said. #[error("{0}")] Driver(String), /// `requireHandle`'s refusal, verbatim. #[error("An imported message arrived with no usable phone or email and the batch names no counterpart")] NoUsableHandle, /// `readSelfNames`' `AppError("Workspace not found", "NOT_FOUND")`. #[error("Workspace not found")] WorkspaceNotFound, /// `setSelfName`'s `AppError(…, "VALIDATION")`. #[error("A self name cannot be blank")] BlankSelfName, } impl ImportError { /// The `AppError` code the TypeScript answers with, for a caller that has to /// put one on the wire. pub const fn code(&self) -> &'static str { match self { ImportError::Driver(_) => "UNKNOWN", ImportError::NoUsableHandle => "IMPORT_SHAPE", ImportError::WorkspaceNotFound => "NOT_FOUND", ImportError::BlankSelfName => "VALIDATION", } } } impl From for ImportError { fn from(error: ContactError) -> ImportError { ImportError::Driver(error.0) } } /* --------------------------------------------------------------- reports -- */ /// One chat's outcome — the TypeScript's `results` row. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChatResult { /// The counterpart's number where there is one. An email-keyed chat reports /// `null` rather than an address in a field every caller reads as a number; /// a group reports its external key, which is what the TypeScript puts here. pub phone: Option, pub contact_id: Option, pub thread_id: String, pub inserted: i64, pub skipped: i64, /// Always `0` per chat: the reply pass is per RUN, and its count lands in /// the totals. Kept because the TypeScript's callers read the key. pub unresolved_replies: i64, } /// What the group leg resolved. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GroupResult { pub thread_id: String, pub title: String, pub external_key: String, pub participant_count: i64, pub thread_created: bool, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ImportTotals { pub chats: i64, pub inserted: i64, pub skipped: i64, pub unresolved_replies: i64, } /// What one applied batch did. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ImportReport { pub chats: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub group: Option, pub totals: ImportTotals, } /// The rows a batch owes the file, and what it resolved — everything except the /// reply links, which cannot be planned until these have landed. #[derive(Debug, Clone, PartialEq)] pub struct ImportPlan { pub changes: Vec, pub chats: Vec, pub group: Option, } /// The reply pass's answer. #[derive(Debug, Clone, PartialEq)] pub struct ReplyLinks { pub changes: Vec, /// Still unlinked — a non-zero count on a full-history import means the /// export was silently truncated. pub unresolved: i64, } /* ----------------------------------------------------------------- probe -- */ /// How a probe found a group. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum MatchedBy { Key, Overlap, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProbeChat { /// The external key for a group, the handle's value for a dm, and /// `label: