Cotton code
467 lines · 16.9 KB · RustRaw
//! The engine's reads, answered by this file's own SQL.//!//! [`FileContacts`] is the one implementation of cotton-core's two driver//! traits over a replica. Live reads run cotton-core's declared statements;//! retained move facts resolve the owner's chosen home before a connector//! writes. They supply resolution only, never writable old rows. It came out of//! `ingest::apply` so the phone, which has no `ingest`, asks the same questions//! through the same code.use cotton_core::import::messages_engine::{    change_target, held_without_media_sql, known_external_ids_sql, overlap_sql, reply_targets_sql, BareRow,    ChangeTarget, ImportDriver,    OverlapHit, MESSAGE_BY_EXTERNAL_ID_SQL, REAL_ID_BODIES_IN_MINUTE_SQL, ROWS_IN_MINUTE_SQL, MinuteRow,    ParticipantRow, ThreadHit, ThreadKind, ThreadStats, DM_THREAD_BY_CONTACT_SQL,    GROUP_THREAD_BY_KEY_SQL, JID_GROUP_THREADS_SQL, PARTICIPANTS_SQL, SELF_NAMES_SQL, THREAD_BY_ID_SQL,    THREAD_EXTERNAL_KEY_SQL, THREAD_LAST_MESSAGE_AT_SQL, THREAD_STATS_SQL, UNLINKED_REPLIES_SQL,};use cotton_core::messages::resolve_contact::{    ContactDriver, ContactError, ContactHandleKind, ContactRow, PersonHandleRow, Region,};use cotton_store::Driver;/// The three questions cotton-core asks a file, answered with its own SQL.pub struct FileContacts<'a>(pub &'a Driver);/// Resolution may read a moved root's local history, but never its old rows/// as writable data. The receiving project's live row supplies import data.impl FileContacts<'_> {    pub(crate) fn moved_threads(        &self,        workspace: &str,    ) -> Result<Vec<(String, serde_json::Value)>, ContactError> {        if self            .0            .get(                "SELECT name FROM sqlite_master WHERE type='table' AND name='cotton_changes'",                &[],            )            .map_err(as_contact_error)?            .is_none()            || cotton_store::link_rule::file_kind(self.0).map_err(as_contact_error)?                != cotton_store::link_rule::FileKind::Personal        {            return Ok(vec![]);        }        let rows = self.0.all(            "SELECT c.record_id,c.before FROM cotton_changes c WHERE c.workspace_id=? AND c.table_id='cotton_msg_threads' AND c.verb='move' AND NOT EXISTS(SELECT 1 FROM cotton_msg_threads t WHERE t.id=c.record_id) AND NOT EXISTS(SELECT 1 FROM cotton_undos u WHERE u.change_id=c.id) AND NOT EXISTS(SELECT 1 FROM cotton_changes live WHERE live.table_id=c.table_id AND live.record_id=c.record_id AND live.verb!='move' AND live._hlc>c._hlc) ORDER BY c._hlc DESC,c.id DESC",            &[sql(workspace)],        ).map_err(as_contact_error)?;        let mut seen = std::collections::BTreeSet::new();        let mut roots = Vec::new();        for row in rows {            let id = row                .text("record_id")                .ok_or_else(|| ContactError("Moved chat has no identity".into()))?;            if !seen.insert(id.to_owned()) {                continue;            }            let fields: serde_json::Value =                serde_json::from_str(row.text("before").unwrap_or("null"))                    .map_err(as_contact_error)?;            if !fields.is_object() {                return Err(ContactError("Moved chat has no readable history".into()));            }            roots.push((id.to_owned(), fields));        }        Ok(roots)    }}fn one_home(ids: impl IntoIterator<Item = String>) -> Result<Option<String>, ContactError> {    let ids: std::collections::BTreeSet<String> = ids.into_iter().collect();    if ids.len() > 1 {        return Err(ContactError(            "This connection matches more than one chat home; nothing was imported".into(),        ));    }    Ok(ids.into_iter().next())}impl ContactDriver for FileContacts<'_> {    fn people_handles(        &self,        workspace_id: &str,        kind: ContactHandleKind,    ) -> Result<Vec<PersonHandleRow>, ContactError> {        let sql = cotton_core::messages::resolve_contact::people_handles_sql(cotton_store::protocol::who::shared_held(self.0), kind);        let mut statement = self            .0            .connection()            .prepare(&sql)            .map_err(as_contact_error)?;        let rows = statement            .query_map([workspace_id], |row| {                Ok(PersonHandleRow {                    id: row.get(0)?,                    full_name: row.get(1)?,                    value: row.get(2).ok(),                })            })            .map_err(as_contact_error)?;        rows.collect::<rusqlite::Result<Vec<_>>>()            .map_err(as_contact_error)    }    fn contact_by_handle(        &self,        workspace_id: &str,        handle: &cotton_core::messages::resolve_contact::ContactHandle,    ) -> Result<Option<ContactRow>, ContactError> {        let mut statement = self            .0            .connection()            .prepare(&cotton_core::messages::resolve_contact::contact_by_handle_sql(cotton_store::protocol::who::shared_held(self.0)))            .map_err(as_contact_error)?;        one_contact(statement.query_map(            (workspace_id, handle.kind.as_str(), handle.value.as_str()),            read_contact,        ))    }    fn contact_by_phone(        &self,        workspace_id: &str,        phone: &str,    ) -> Result<Option<ContactRow>, ContactError> {        let mut statement = self            .0            .connection()            .prepare(&cotton_core::messages::resolve_contact::contact_by_phone_sql(cotton_store::protocol::who::shared_held(self.0)))            .map_err(as_contact_error)?;        one_contact(statement.query_map((workspace_id, phone), read_contact))    }}fn read_contact(row: &rusqlite::Row<'_>) -> rusqlite::Result<ContactRow> {    Ok(ContactRow {        id: row.get(0)?,        display_name: row.get(1)?,        person_id: row.get(2)?,    })}/// The first row of a contact lookup, or none. Both statements answer at most/// one row, so "first" and "only" are the same question.fn one_contact(    rows: rusqlite::Result<ContactRows<'_>>,) -> Result<Option<ContactRow>, ContactError> {    let mut rows = rows.map_err(as_contact_error)?;    match rows.next() {        Some(row) => Ok(Some(row.map_err(as_contact_error)?)),        None => Ok(None),    }}type ContactRows<'a> =    rusqlite::MappedRows<'a, fn(&rusqlite::Row<'_>) -> rusqlite::Result<ContactRow>>;/// The engine's thirteen reads, each running the statement cotton-core declares/// rather than a paraphrase of it: a `WHERE` written twice is a workspace filter/// that can go missing in one of the two spellings.impl ImportDriver for FileContacts<'_> {    fn dm_thread_for_contact(        &self,        workspace_id: &str,        contact_id: &str,    ) -> Result<Option<String>, ContactError> {        let live = self            .row(                DM_THREAD_BY_CONTACT_SQL,                &[sql(workspace_id), sql(contact_id)],            )?            .and_then(|row| row.text("id").map(str::to_string));        let moved = self            .moved_threads(workspace_id)?            .into_iter()            .filter(|(_, fields)| {                fields["kind"].as_str() == Some("dm")                    && fields["contact_id"].as_str() == Some(contact_id)            })            .map(|(id, _)| id);        one_home(live.into_iter().chain(moved))    }    fn thread_by_id(        &self,        workspace_id: &str,        id: &str,        kind: ThreadKind,    ) -> Result<Option<ThreadHit>, ContactError> {        if let Some(row) = self.row(            THREAD_BY_ID_SQL,            &[sql(id), sql(workspace_id), sql(kind.as_str())],        )? {            return Ok(Some(ThreadHit {                id: row.text("id").unwrap_or_default().into(),                contact_id: row.text("contact_id").map(str::to_owned),            }));        }        Ok(self            .moved_threads(workspace_id)?            .into_iter()            .find(|(root, fields)| root == id && fields["kind"].as_str() == Some(kind.as_str()))            .map(|(id, fields)| ThreadHit {                id,                contact_id: fields["contact_id"].as_str().map(str::to_owned),            }))    }    fn known_external_ids(        &self,        thread_id: &str,        channel: &str,        ids: &[&str],    ) -> Result<std::collections::BTreeSet<String>, ContactError> {        let mut bound = vec![sql(thread_id), sql(channel)];        bound.extend(ids.iter().map(|id| sql(id)));        Ok(self            .rows(&known_external_ids_sql(ids.len()), &bound)?            .iter()            .filter_map(|row| row.text("external_id").map(str::to_string))            .collect())    }    fn thread_stats(&self, thread_id: &str, channel: &str) -> Result<ThreadStats, ContactError> {        Ok(            match self.row(THREAD_STATS_SQL, &[sql(thread_id), sql(channel)])? {                Some(row) => ThreadStats {                    count: row.int("n").unwrap_or(0),                    oldest_sent_at: row.text("oldest").map(str::to_string),                    newest_sent_at: row.text("newest").map(str::to_string),                },                None => ThreadStats::default(),            },        )    }    fn group_thread_by_key(        &self,        workspace_id: &str,        external_key: &str,    ) -> Result<Option<(String, Option<String>)>, ContactError> {        let live = self            .row(                GROUP_THREAD_BY_KEY_SQL,                &[sql(workspace_id), sql(external_key)],            )?            .map(|row| {                (                    row.text("id").unwrap_or_default().to_owned(),                    row.text("title").map(str::to_owned),                )            });        let moved = self            .moved_threads(workspace_id)?            .into_iter()            .filter(|(_, fields)| {                fields["kind"].as_str() == Some("group")                    && fields["external_key"].as_str() == Some(external_key)            })            .map(|(id, fields)| (id, fields["title"].as_str().map(str::to_owned)));        let candidates: Vec<_> = live.into_iter().chain(moved).collect();        let home = one_home(candidates.iter().map(|(id, _)| id.clone()))?;        Ok(home.and_then(|home| candidates.into_iter().find(|(id, _)| *id == home)))    }    fn jid_group_threads(        &self,        workspace_id: &str,    ) -> Result<Vec<(String, Option<String>)>, ContactError> {        Ok(self            .rows(JID_GROUP_THREADS_SQL, &[sql(workspace_id)])?            .iter()            .map(|row| {                (                    row.text("id").unwrap_or_default().to_string(),                    row.text("title").map(str::to_string),                )            })            .collect())    }    fn thread_by_overlap(        &self,        workspace_id: &str,        channel: &str,        kind: ThreadKind,        ids: &[&str],    ) -> Result<Option<OverlapHit>, ContactError> {        let mut bound = vec![sql(workspace_id), sql(kind.as_str()), sql(channel)];        bound.extend(ids.iter().map(|id| sql(id)));        Ok(self            .row(&overlap_sql(ids.len()), &bound)?            .map(|row| OverlapHit {                thread_id: row.text("thread_id").unwrap_or_default().to_string(),                contact_id: row.text("contact_id").map(str::to_string),                matched: row.int("n").unwrap_or(0),            }))    }    fn participants_of(&self, thread_id: &str) -> Result<Vec<ParticipantRow>, ContactError> {        Ok(self            .rows(PARTICIPANTS_SQL, &[sql(thread_id)])?            .iter()            .map(|row| ParticipantRow {                id: row.text("id").unwrap_or_default().to_string(),                contact_id: row.text("contact_id").map(str::to_string),                display_name: row.text("display_name").map(str::to_string),            })            .collect())    }    fn thread_last_message_at(        &self,        thread_id: &str,    ) -> Result<Option<Option<String>>, ContactError> {        Ok(self            .row(THREAD_LAST_MESSAGE_AT_SQL, &[sql(thread_id)])?            .map(|row| row.text("last_message_at").map(str::to_string)))    }    fn thread_external_key(&self, thread_id: &str) -> Result<Option<Option<String>>, ContactError> {        Ok(self            .row(THREAD_EXTERNAL_KEY_SQL, &[sql(thread_id)])?            .map(|row| row.text("external_key").map(str::to_string)))    }    fn unlinked_replies(&self, thread_id: &str) -> Result<Vec<(String, String)>, ContactError> {        Ok(self            .rows(UNLINKED_REPLIES_SQL, &[sql(thread_id)])?            .iter()            .map(|row| {                (                    row.text("id").unwrap_or_default().to_string(),                    row.text("reply_to_external_id")                        .unwrap_or_default()                        .to_string(),                )            })            .collect())    }    fn held_without_media(        &self,        thread_id: &str,        channel: &str,        ids: &[&str],    ) -> Result<Vec<BareRow>, ContactError> {        let mut bound = vec![sql(thread_id), sql(channel)];        bound.extend(ids.iter().map(|id| sql(id)));        Ok(self            .rows(&held_without_media_sql(ids.len()), &bound)?            .iter()            .map(|row| BareRow {                id: row.text("id").unwrap_or_default().to_string(),                external_id: row.text("external_id").unwrap_or_default().to_string(),                body: row.text("body").map(str::to_string),                meta: row.text("meta").map(str::to_string),            })            .collect())    }    fn messages_by_external_ids(        &self,        thread_id: &str,        channel: &str,        ids: &[&str],    ) -> Result<Vec<(String, String)>, ContactError> {        let mut bound = vec![sql(thread_id), sql(channel)];        bound.extend(ids.iter().map(|id| sql(id)));        Ok(self            .rows(&reply_targets_sql(ids.len()), &bound)?            .iter()            .map(|row| {                (                    row.text("id").unwrap_or_default().to_string(),                    row.text("external_id").unwrap_or_default().to_string(),                )            })            .collect())    }    fn rows_in_minute(        &self,        thread_id: &str,        channel: &str,        minute: &str,    ) -> Result<Vec<MinuteRow>, ContactError> {        Ok(self            .rows(ROWS_IN_MINUTE_SQL, &[sql(thread_id), sql(channel), sql(minute), sql(minute)])?            .iter()            .map(|row| MinuteRow {                id: row.text("id").unwrap_or_default().to_string(),                external_id: row.text("external_id").map(str::to_string),                direction: row.text("direction").unwrap_or_default().to_string(),                body: row.text("body").map(str::to_string),                meta: row.text("meta").map(str::to_string),            })            .collect())    }    fn real_id_bodies_in_minute(        &self,        thread_id: &str,        channel: &str,        minute: &str,    ) -> Result<Vec<String>, ContactError> {        Ok(self            .rows(REAL_ID_BODIES_IN_MINUTE_SQL, &[sql(thread_id), sql(channel), sql(minute), sql(minute)])?            .iter()            .filter_map(|row| row.text("body").map(str::to_string))            .collect())    }    fn message_by_external_id(        &self,        workspace_id: &str,        channel: &str,        external_id: &str,    ) -> Result<Option<ChangeTarget>, ContactError> {        Ok(self            .row(MESSAGE_BY_EXTERNAL_ID_SQL, &[sql(workspace_id), sql(channel), sql(external_id)])?            .map(|row| change_target(&row)))    }    fn self_names_json(&self, workspace_id: &str) -> Result<Option<Option<String>>, ContactError> {        Ok(self            .row(SELF_NAMES_SQL, &[sql(workspace_id)])?            .map(|row| row.text("msg_import_self_names").map(str::to_string)))    }    fn owner_region(&self, workspace_id: &str) -> Result<Option<Region>, ContactError> {        cotton_store::phone_fold::region_hint(self.0, workspace_id).map_err(|error| ContactError(error.to_string()))    }}/// A bound string parameter. Every parameter the engine's statements take is/// one — an id, a handle, a channel or a kind.fn sql(value: &str) -> rusqlite::types::Value {    rusqlite::types::Value::Text(value.to_string())}impl FileContacts<'_> {    fn rows(        &self,        statement: &str,        params: &[rusqlite::types::Value],    ) -> Result<Vec<cotton_store::driver::Row>, ContactError> {        self.0            .all(statement, params)            .map_err(|error| ContactError(error.to_string()))    }    fn row(        &self,        statement: &str,        params: &[rusqlite::types::Value],    ) -> Result<Option<cotton_store::driver::Row>, ContactError> {        self.0            .get(statement, params)            .map_err(|error| ContactError(error.to_string()))    }}fn as_contact_error(error: impl std::fmt::Display) -> ContactError {    ContactError(error.to_string())}