Cotton code
340 lines · 12.9 KB · RustRaw
//! Messages, imported: the one seam between a parsed batch and the rows it//! becomes, shared by the Mac's ingest sources and the phone's WhatsApp//! export import.//!//! **Nothing here decides anything.** Which thread a batch lands in, who a//! sender is and what a re-import skips are `cotton_core::import::messages_engine`'s//! answers; what this module owns is the FILE — [`FileContacts`] answers the//! engine's reads with the statements cotton-core declares, [`import_messages`]//! applies its changes through the store's own outbox, and [`media`] moves an//! attachment's bytes into the content-addressed store and queues the upload.//!//! It is feature-free on purpose. It was `ingest::apply` and `ingest::media_leg`,//! behind the host-only `ingest` feature, until the phone needed the same//! applier for a `_chat.txt` export — and a second applier is a conversation//! split down the middle in front of the person whose conversation it is.pub mod file;pub mod media;use cotton_core::import::envelope::ImportBatch;use cotton_core::import::messages_engine::{    probe_import, run_import, ImportArgs, ImportError, ImportReport,};use cotton_store::actor::{Actor, JobName};use cotton_store::file_identity::Namespace;use cotton_store::mint::clock::writer_clock;use cotton_store::mint::{changes_of, mint, Act, Held, History};use cotton_store::outbox::{IdSource, LocalChange};use cotton_store::Driver;pub use file::FileContacts;use crate::seams::{uuid_v4, Clock, Random};/// One file a message in the same batch is waiting on.////// The SOURCE resolves the path, because only the source knows how. By the time/// it reaches the applier it is an absolute path on this device and nothing/// more, so the media leg has ONE job — hash it, store it, key it, ledger it —/// for every message source.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MediaFile {    /// The `external_id` of the message in this batch that this file hangs off.    pub external_id: String,    /// Absolute path on this device.    pub path: std::path::PathBuf,    /// The original filename — a chip's label, and where the extension comes    /// from.    pub name: Option<String>,    /// The type, when the source actually knew it (Messages stores one).    pub content_type: Option<String>,}/// A reader's own counted reasons — numbers only, never a person's words.////// A `BTreeMap` so the order is the same on every run: a panel that reordered/// its own counts between passes reads as a change nobody made.pub type Notes = std::collections::BTreeMap<String, i64>;/// Add to a counted reason.pub fn count(notes: &mut Notes, key: &str, by: i64) {    *notes.entry(key.to_string()).or_insert(0) += by;}/// Where this batch's rows will land, asked before a byte of media moves.////// The answer comes from the ENGINE's own resolution — a probe, which writes/// nothing — so the thread a media key is built against is the thread the/// write will actually use. Where the probe finds none the conversation does/// not exist yet, and the caller's reserved id is what the engine will create/// it under. `None` means no SINGLE thread resolves: a batch carrying neither a/// dm block nor a group block spreads by phone, one thread per counterpart, and/// one reserved id cannot serve several of them.pub fn resolve_thread(db: &Driver, batch: &ImportBatch) -> Result<Option<String>, String> {    if batch.dm.is_none() && batch.thread.is_none() {        return Ok(None);    }    let report = probe_import(&FileContacts(db), batch).map_err(|error| error.to_string())?;    let found = report        .group        .and_then(|group| group.thread_id)        .or_else(|| report.chats.first().and_then(|chat| chat.thread_id.clone()));    Ok(found.or_else(|| batch.new_thread_id.clone()))}/// Which of these messages the thread already holds WITH media: their/// external ids. Their bytes are never read again — a second pass over the/// same iPhone backup hashes nothing. A message held WITHOUT media is not in/// the answer, so its picture is still stored and the engine fills the row.pub fn held_with_media(    db: &Driver,    thread_id: &str,    channel: &str,    external_ids: &[&str],) -> Result<std::collections::BTreeSet<String>, String> {    let mut held = std::collections::BTreeSet::new();    // SQLite's bound-parameter ceiling is far above a batch; chunk anyway so    // no caller can trip it.    for chunk in external_ids.chunks(400) {        let marks = vec!["?"; chunk.len()].join(", ");        let mut bound = vec![            rusqlite::types::Value::Text(thread_id.to_string()),            rusqlite::types::Value::Text(channel.to_string()),        ];        bound.extend(chunk.iter().map(|id| rusqlite::types::Value::Text(id.to_string())));        let rows = db            .all(                &format!(                    "SELECT external_id FROM cotton_msg_messages WHERE thread_id = ? AND channel = ? \                     AND json_array_length(media) > 0 AND external_id IN ({marks})"                ),                &bound,            )            .map_err(|error| error.to_string())?;        held.extend(rows.iter().filter_map(|row| row.text("external_id").map(str::to_string)));    }    Ok(held)}/// One batch of changes, through the store's own outbox — so an imported row/// leaves this device exactly the way a decision does.pub fn write_changes(    db: &Driver,    changes: &[LocalChange],    clock: &dyn Clock,    ids: &mut dyn IdSource,) -> Result<(), String> {    write_changes_as(db, changes, clock, ids, Held::Replica)}/// [`write_changes`] into a file held either way: a replica queues its ops for/// the next push, a served file (a serving Mac's own) does not — its phones/// pull them.pub fn write_changes_as(    db: &Driver,    changes: &[LocalChange],    clock: &dyn Clock,    ids: &mut dyn IdSource,    held: Held,) -> Result<(), String> {    write_changes_by(db, changes, clock, ids, held, "messages-import", "import_messages")}/// [`write_changes_as`] under a named device job and verb — the provenance a/// row written by one of this Mac's own jobs carries.pub fn write_changes_by(    db: &Driver,    changes: &[LocalChange],    clock: &dyn Clock,    ids: &mut dyn IdSource,    held: Held,    job: &'static str,    verb: &str,) -> Result<(), String> {    if changes.is_empty() {        return Ok(());    }    // The import is this device's own job, on the replica it holds: the ops    // are stamped with the file's author and queued for the next push, by the    // replica's judge time (slice 1).    let stamped = writer_clock(db, clock.now().timestamp_millis(), ids).map_err(|error| error.to_string())?;    mint(        db,        &Act {            actor: Actor::DeviceJob(JobName::named(job).map_err(|e| e.to_string())?),            verb: verb.to_string(),            history: History::None,            changes: changes_of(db, changes),        },        &stamped,        ids,        held,    )    .map(|_| ())    .map_err(|error| error.to_string())}/// One import, planned and applied — the engine's two passes, with this/// device's clock, id minter and op-id source threaded through.////// The engine is DRIVER-IN and holds no clock, so `now`, the id minter and the/// op-id source all arrive from here — which is why every stamp in an import/// is the batch's and not a fresh reading per row. `namespace` is the open/// file's, which every derived contact and thread id is made under.pub fn import_messages(    db: &Driver,    namespace: &Namespace,    batch: &ImportBatch,    clock: &dyn Clock,    random: &dyn Random,    ids: &mut dyn IdSource,) -> Result<ImportReport, ImportError> {    import_messages_as(db, namespace, batch, clock, random, ids, Held::Replica)}/// The data key a phone's import keys its sealed rows' telling ids under:/// the database's DK and id ([`crate::seal::keyed_row_id`]).pub struct KeyedIds<'a> {    pub dk: &'a cotton_core::seal::DataKey,    pub database_id: &'a str,}/// The engine's planned rows with each sealed table's telling id keyed/// (`react:<message>:<phone>` → the uuid only the DK makes from it), so this/// phone and the Mac's importer land one row for one reaction and the object/// never holds a phone number in an id. Which tables are sealed is the/// shipped storage map's (the kit's `seal` blocks).pub fn keyed(changes: &[cotton_core::cotton_rules::change::Change], keys: &KeyedIds<'_>) -> Result<Vec<cotton_core::cotton_rules::change::Change>, String> {    let tables = crate::transport::object::ObjectTables::personal();    changes        .iter()        .map(|change| {            let mut change = change.clone();            if let Some(table) = tables.ours(&change.table).filter(|t| t.seal.is_some()) {                change.row_id = crate::seal::keyed_row_id(keys.dk, keys.database_id, &table.table, &change.row_id).map_err(|e| e.to_string())?;            }            Ok(change)        })        .collect()}/// [`import_messages`] with sealed rows' telling ids keyed ([`keyed`]) when/// `keys` is given: the phone's own export import once the kit seals the/// messages tables. `namespace` is then the keyed one/// ([`crate::seal::keyed_namespace`]).#[allow(clippy::too_many_arguments)]pub fn import_messages_keyed(    db: &Driver,    namespace: &Namespace,    batch: &ImportBatch,    clock: &dyn Clock,    random: &dyn Random,    ids: &mut dyn IdSource,    keys: Option<&KeyedIds<'_>>,) -> Result<ImportReport, ImportError> {    import_inner(db, namespace, batch, clock, random, ids, Held::Replica, keys)}/// [`import_messages`] into a file held either way ([`write_changes_as`]).pub fn import_messages_as(    db: &Driver,    namespace: &Namespace,    batch: &ImportBatch,    clock: &dyn Clock,    random: &dyn Random,    ids: &mut dyn IdSource,    held: Held,) -> Result<ImportReport, ImportError> {    import_inner(db, namespace, batch, clock, random, ids, held, None)}#[allow(clippy::too_many_arguments)]fn import_inner(    db: &Driver,    namespace: &Namespace,    batch: &ImportBatch,    clock: &dyn Clock,    random: &dyn Random,    ids: &mut dyn IdSource,    held: Held,    keys: Option<&KeyedIds<'_>>,) -> Result<ImportReport, ImportError> {    let file = FileContacts(db);    let moved = file        .moved_threads(&batch.workspace_id)        .map_err(|e| ImportError::Driver(e.to_string()))?;    if !moved.is_empty() {        let probe = probe_import(&file, batch)?;        let names_moved = probe            .group            .iter()            .filter_map(|group| group.thread_id.as_deref())            .chain(                probe                    .chats                    .iter()                    .filter_map(|chat| chat.thread_id.as_deref()),            )            .any(|thread| moved.iter().any(|(id, _)| id == thread));        if names_moved {            return Err(ImportError::Driver(                "This chat is already filed. Import in its proved home.".into(),            ));        }    }    let now = clock.now_iso();    let mut new_id = || uuid_v4(random);    run_import(        &file,        ImportArgs {            batch,            namespace: namespace.as_str(),            now: &now,            new_id: &mut new_id,        },        &mut |changes| match keys {            Some(keys) => write_changes_as(db, &local(&keyed(changes, keys)?), clock, ids, held),            None => write_changes_as(db, &local(changes), clock, ids, held),        },    )}/// The engine's planned rows (`cotton_rules::change::Change`) as this file writes them.pub(crate) fn local(changes: &[cotton_core::cotton_rules::change::Change]) -> Vec<LocalChange> {    changes.iter().cloned().map(LocalChange::from).collect()}/// Changes to messages already in the file (an edit, a delete for everyone, a/// reaction), on the same outbox as an import — the engine's/// [`cotton_core::import::messages_engine::plan_message_changes`].pub fn apply_message_changes(    db: &Driver,    workspace_id: &str,    channel: &str,    changes: &[cotton_core::import::messages_engine::MessageChange],    clock: &dyn Clock,    ids: &mut dyn IdSource,) -> Result<cotton_core::import::messages_engine::ChangesReport, ImportError> {    apply_message_changes_as(db, workspace_id, channel, changes, clock, ids, Held::Replica)}/// [`apply_message_changes`] into a file held either way ([`write_changes_as`]).pub fn apply_message_changes_as(    db: &Driver,    workspace_id: &str,    channel: &str,    changes: &[cotton_core::import::messages_engine::MessageChange],    clock: &dyn Clock,    ids: &mut dyn IdSource,    held: Held,) -> Result<cotton_core::import::messages_engine::ChangesReport, ImportError> {    let (ops, report) = cotton_core::import::messages_engine::plan_message_changes(        &FileContacts(db),        workspace_id,        channel,        changes,    )?;    write_changes_as(db, &local(&ops), clock, ids, held).map_err(ImportError::Driver)?;    Ok(report)}