//! The messages engine over a host that answers in JSON: the Worker's door. //! //! The engine is DRIVER-IN (`ImportDriver`, `ContactDriver`): one method per //! fixed question. A host that holds its rows elsewhere — the Worker's Durable //! Object, reached from WASM — answers each question by its name with JSON //! ([`Ask`]); [`Asked`] turns those answers into the driver, and [`run`] is //! the one call that plans: `import`, `replies` or `changes`, its input as //! JSON, its plan as JSON (each change `{table, id, patch}` or //! `{table, id, retract: true}`), or a refusal with the engine's words and //! code. //! //! The questions and their answers (every argument object also carries //! `workspace_id` where the trait has one): //! //! | question | arguments | answer | //! |---|---|---| //! | `people_handles` | `kind` | `[{id, full_name, value}]` | //! | `contact_by_handle` | `kind`, `value` | `{id, display_name, person_id}` or null | //! | `contact_by_phone` | `phone` | the same | //! | `dm_thread_for_contact` | `contact_id` | id or null | //! | `thread_by_id` | `id`, `kind` | `{id, contact_id}` or null | //! | `known_external_ids` | `thread_id`, `channel`, `ids` | `[external id]` | //! | `thread_stats` | `thread_id`, `channel` | `{count, oldestSentAt, newestSentAt}` | //! | `group_thread_by_key` | `external_key` | `{id, title}` or null | //! | `jid_group_threads` | | `[{id, title}]` | //! | `thread_by_overlap` | `channel`, `kind`, `ids` | `{thread_id, contact_id, matched}` or null | //! | `participants_of` | `thread_id` | `[{id, contact_id, display_name}]` | //! | `thread_last_message_at` | `thread_id` | `{at}` (at may be null), or null when no such thread | //! | `thread_external_key` | `thread_id` | key or null | //! | `unlinked_replies` | `thread_id` | `[{id, reply_to_external_id}]` | //! | `messages_by_external_ids` | `thread_id`, `channel`, `ids` | `[{id, external_id}]` | //! | `held_without_media` | `thread_id`, `channel`, `ids` | `[{id, external_id, body, meta}]` | //! | `real_id_bodies_in_minute` | `thread_id`, `channel`, `minute` | `[body]` | //! | `rows_in_minute` | `thread_id`, `channel`, `minute` | `[{id, external_id, direction, body, meta}]` | //! | `message_by_external_id` | `channel`, `external_id` | `{id, thread_id, meta, media, newest}` or null | //! | `self_names_json` | | `{names}` (names: JSON text or null), or null when no workspace | //! | `owner_region` | | a region code (`"IN"`) or null | //! | `new_id` | | a fresh id | //! //! A row's `meta` is the column's JSON text (`held_without_media`, //! `rows_in_minute`), or the parsed object (`message_by_external_id`, whose //! `media` is the parsed array) — what the phone's driver reads in each place. use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet}; use serde::de::DeserializeOwned; use serde::Deserialize; use serde_json::{json, Map, Value}; use super::messages_engine::{ plan_import, plan_message_changes, plan_reply_links, BareRow, ChangeTarget, ImportArgs, ImportDriver, ImportError, MessageChange, MinuteRow, OverlapHit, ParticipantRow, ThreadHit, ThreadKind, ThreadStats, }; use crate::import::envelope::ImportBatch; use crate::messages::resolve_contact::{ find_contact_by_handle, people_by_handle, resolve_contact, ContactDriver, ContactError, ContactHandle, ContactHandleKind, ContactRow, MatchedPerson, PersonHandleRow, Region, ResolveContactArgs, }; use crate::messages::MessageMedia; /// A host that answers the engine's questions by name, in JSON. pub trait Ask { fn ask(&self, question: &str, args: Value) -> Result; } /// The engine's driver over an [`Ask`]. pub struct Asked<'a, A: Ask + ?Sized>(pub &'a A); impl Asked<'_, A> { fn answer(&self, question: &str, args: Value) -> Result { let answer = self.0.ask(question, args).map_err(ContactError)?; serde_json::from_value(answer).map_err(|error| ContactError(format!("the answer to {question} does not read: {error}"))) } } #[derive(Deserialize)] struct PersonHandleAnswer { id: String, full_name: Option, value: Value, } #[derive(Deserialize)] struct ContactAnswer { id: String, display_name: Option, person_id: Option, } impl From for ContactRow { fn from(row: ContactAnswer) -> ContactRow { ContactRow { id: row.id, display_name: row.display_name, person_id: row.person_id } } } #[derive(Deserialize)] struct ThreadAnswer { id: String, contact_id: Option, } #[derive(Deserialize)] struct TitledAnswer { id: String, title: Option, } #[derive(Deserialize)] struct OverlapAnswer { thread_id: String, contact_id: Option, matched: i64, } #[derive(Deserialize)] struct ParticipantAnswer { id: String, contact_id: Option, display_name: Option, } #[derive(Deserialize)] struct AtAnswer { at: Option, } #[derive(Deserialize)] struct ReplyAnswer { id: String, reply_to_external_id: String, } #[derive(Deserialize)] struct ExternalAnswer { id: String, external_id: String, } #[derive(Deserialize)] struct BareAnswer { id: String, external_id: String, body: Option, meta: Option, } #[derive(Deserialize)] struct MinuteAnswer { id: String, external_id: Option, direction: String, body: Option, meta: Option, } #[derive(Deserialize)] struct TargetAnswer { id: String, thread_id: String, meta: Value, media: Value, newest: bool, } #[derive(Deserialize)] struct NamesAnswer { names: Option, } impl ContactDriver for Asked<'_, A> { fn people_handles(&self, workspace_id: &str, kind: ContactHandleKind) -> Result, ContactError> { let rows: Vec = self.answer("people_handles", json!({ "workspace_id": workspace_id, "kind": kind.as_str() }))?; // A value that is not a string is stepped over by the engine, as the phone's driver leaves it `None`. Ok(rows .into_iter() .map(|row| PersonHandleRow { id: row.id, full_name: row.full_name, value: row.value.as_str().map(str::to_string) }) .collect()) } fn contact_by_handle(&self, workspace_id: &str, handle: &ContactHandle) -> Result, ContactError> { let row: Option = self.answer("contact_by_handle", json!({ "workspace_id": workspace_id, "kind": handle.kind.as_str(), "value": handle.value }))?; Ok(row.map(ContactRow::from)) } fn contact_by_phone(&self, workspace_id: &str, phone: &str) -> Result, ContactError> { let row: Option = self.answer("contact_by_phone", json!({ "workspace_id": workspace_id, "phone": phone }))?; Ok(row.map(ContactRow::from)) } } impl ImportDriver for Asked<'_, A> { fn dm_thread_for_contact(&self, workspace_id: &str, contact_id: &str) -> Result, ContactError> { self.answer("dm_thread_for_contact", json!({ "workspace_id": workspace_id, "contact_id": contact_id })) } fn thread_by_id(&self, workspace_id: &str, id: &str, kind: ThreadKind) -> Result, ContactError> { let row: Option = self.answer("thread_by_id", json!({ "workspace_id": workspace_id, "id": id, "kind": kind.as_str() }))?; Ok(row.map(|row| ThreadHit { id: row.id, contact_id: row.contact_id })) } fn known_external_ids(&self, thread_id: &str, channel: &str, ids: &[&str]) -> Result, ContactError> { let found: Vec = self.answer("known_external_ids", json!({ "thread_id": thread_id, "channel": channel, "ids": ids }))?; Ok(found.into_iter().collect()) } fn thread_stats(&self, thread_id: &str, channel: &str) -> Result { self.answer("thread_stats", json!({ "thread_id": thread_id, "channel": channel })) } fn group_thread_by_key(&self, workspace_id: &str, external_key: &str) -> Result)>, ContactError> { let row: Option = self.answer("group_thread_by_key", json!({ "workspace_id": workspace_id, "external_key": external_key }))?; Ok(row.map(|row| (row.id, row.title))) } fn jid_group_threads(&self, workspace_id: &str) -> Result)>, ContactError> { let rows: Vec = self.answer("jid_group_threads", json!({ "workspace_id": workspace_id }))?; Ok(rows.into_iter().map(|row| (row.id, row.title)).collect()) } fn thread_by_overlap(&self, workspace_id: &str, channel: &str, kind: ThreadKind, ids: &[&str]) -> Result, ContactError> { let row: Option = self.answer("thread_by_overlap", json!({ "workspace_id": workspace_id, "channel": channel, "kind": kind.as_str(), "ids": ids }))?; Ok(row.map(|row| OverlapHit { thread_id: row.thread_id, contact_id: row.contact_id, matched: row.matched })) } fn participants_of(&self, thread_id: &str) -> Result, ContactError> { let rows: Vec = self.answer("participants_of", json!({ "thread_id": thread_id }))?; Ok(rows.into_iter().map(|row| ParticipantRow { id: row.id, contact_id: row.contact_id, display_name: row.display_name }).collect()) } fn thread_last_message_at(&self, thread_id: &str) -> Result>, ContactError> { let row: Option = self.answer("thread_last_message_at", json!({ "thread_id": thread_id }))?; Ok(row.map(|row| row.at)) } fn thread_external_key(&self, thread_id: &str) -> Result>, ContactError> { // The engine reads only the key (`.flatten()`); a host that cannot tell a missing thread from a keyless one answers null for both. let key: Option = self.answer("thread_external_key", json!({ "thread_id": thread_id }))?; Ok(Some(key)) } fn unlinked_replies(&self, thread_id: &str) -> Result, ContactError> { let rows: Vec = self.answer("unlinked_replies", json!({ "thread_id": thread_id }))?; Ok(rows.into_iter().map(|row| (row.id, row.reply_to_external_id)).collect()) } fn messages_by_external_ids(&self, thread_id: &str, channel: &str, ids: &[&str]) -> Result, ContactError> { let rows: Vec = self.answer("messages_by_external_ids", json!({ "thread_id": thread_id, "channel": channel, "ids": ids }))?; Ok(rows.into_iter().map(|row| (row.id, row.external_id)).collect()) } fn held_without_media(&self, thread_id: &str, channel: &str, ids: &[&str]) -> Result, ContactError> { let rows: Vec = self.answer("held_without_media", json!({ "thread_id": thread_id, "channel": channel, "ids": ids }))?; Ok(rows.into_iter().map(|row| BareRow { id: row.id, external_id: row.external_id, body: row.body, meta: row.meta }).collect()) } fn real_id_bodies_in_minute(&self, thread_id: &str, channel: &str, minute: &str) -> Result, ContactError> { self.answer("real_id_bodies_in_minute", json!({ "thread_id": thread_id, "channel": channel, "minute": minute })) } fn rows_in_minute(&self, thread_id: &str, channel: &str, minute: &str) -> Result, ContactError> { let rows: Vec = self.answer("rows_in_minute", json!({ "thread_id": thread_id, "channel": channel, "minute": minute }))?; Ok(rows .into_iter() .map(|row| MinuteRow { id: row.id, external_id: row.external_id, direction: row.direction, body: row.body, meta: row.meta }) .collect()) } fn message_by_external_id(&self, workspace_id: &str, channel: &str, external_id: &str) -> Result, ContactError> { let row: Option = self.answer("message_by_external_id", json!({ "workspace_id": workspace_id, "channel": channel, "external_id": external_id }))?; // The phone's `change_target`: a meta that is not an object reads as empty, a media list that does not read as none. Ok(row.map(|row| ChangeTarget { id: row.id, thread_id: row.thread_id, meta: match row.meta { Value::Object(map) => map, _ => Map::new(), }, media: serde_json::from_value::>(row.media).unwrap_or_default(), newest: row.newest, })) } fn self_names_json(&self, workspace_id: &str) -> Result>, ContactError> { let row: Option = self.answer("self_names_json", json!({ "workspace_id": workspace_id }))?; Ok(row.map(|row| row.names)) } fn owner_region(&self, workspace_id: &str) -> Result, ContactError> { let code: Option = self.answer("owner_region", json!({ "workspace_id": workspace_id }))?; code.map(|code| code.parse::().map_err(|_| ContactError(format!("{code} is not a region")))).transpose() } } /// Why a run was refused: the engine's words and its code (`IMPORT_SHAPE`, /// `NOT_FOUND`, …; `bad_input` for an input that does not read). #[derive(Debug, Clone, PartialEq, Eq)] pub struct Refused { pub words: String, pub code: &'static str, } impl From for Refused { fn from(error: ImportError) -> Refused { Refused { code: error.code(), words: error.to_string() } } } /// A normalised handle as the host holds one: `{kind, value}`, taken as given. #[derive(Deserialize)] struct HandleIn { kind: ContactHandleKind, value: String, } impl From for ContactHandle { fn from(handle: HandleIn) -> ContactHandle { ContactHandle { kind: handle.kind, value: handle.value } } } /// A fresh id from the host. The engine's id source cannot fail, so a host /// that could not mint one is remembered and the run refused once planned. fn minted(db: &Asked<'_, A>, failed: &RefCell>) -> String { match db.answer::("new_id", json!({})) { Ok(id) => id, Err(error) => { failed.borrow_mut().get_or_insert(error.0); String::new() } } } fn input(name: &str, text: &str) -> Result { serde_json::from_str(text).map_err(|error| Refused { words: format!("{name}: the input does not read: {error}"), code: "bad_input" }) } /// Plan `name` over `input` (JSON text), asking `asker` every read: /// /// * `import` — `{batch, namespace, now}` → `{changes, chats, group}`; /// each fresh id is `new_id`'s answer. /// * `replies` — `{threadId, channel}` → `{changes, unresolved}`. /// * `changes` — `{workspaceId, channel, changes}` → `{changes, report}`. /// * `people` — `{workspaceId}` → `{handle key: {id, full_name}}`, the people /// fold (a handle two people claim is nobody's). /// * `contact` — `{workspaceId, handle}` → `{id, display_name, person_id}` or /// null: the contact a normalised handle already belongs to. /// * `resolve` — `{workspaceId, namespace, handle, displayName, personId, now, /// people}` → `{contactId, changes, created}`: the one contact reachable at /// a normalised handle, found or made (`people` is the fold, when the caller /// has it). pub fn run(name: &str, input_text: &str, asker: &A) -> Result { let db = Asked(asker); match name { "import" => { #[derive(Deserialize)] struct In { batch: ImportBatch, namespace: String, now: String, } let i: In = input(name, input_text)?; // A fresh id the host could not mint refuses the run once it is planned: the closure cannot fail. let failed: RefCell> = RefCell::new(None); let mut new_id = || minted(&db, &failed); let plan = plan_import(&db, ImportArgs { batch: &i.batch, namespace: &i.namespace, now: &i.now, new_id: &mut new_id })?; if let Some(words) = failed.into_inner() { return Err(ImportError::Driver(words).into()); } Ok(json!({ "changes": plan.changes, "chats": plan.chats, "group": plan.group })) } "replies" => { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct In { thread_id: String, channel: String, } let i: In = input(name, input_text)?; let links = plan_reply_links(&db, &i.thread_id, &i.channel)?; Ok(json!({ "changes": links.changes, "unresolved": links.unresolved })) } "changes" => { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct In { workspace_id: String, channel: String, changes: Vec, } let i: In = input(name, input_text)?; let (changes, report) = plan_message_changes(&db, &i.workspace_id, &i.channel, &i.changes)?; Ok(json!({ "changes": changes, "report": report })) } "people" => { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct In { workspace_id: String, } let i: In = input(name, input_text)?; Ok(json!(people_by_handle(&db, &i.workspace_id).map_err(ImportError::from)?)) } "contact" => { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct In { workspace_id: String, handle: HandleIn, } let i: In = input(name, input_text)?; Ok(json!(find_contact_by_handle(&db, &i.workspace_id, &i.handle.into()).map_err(ImportError::from)?)) } "resolve" => { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct In { workspace_id: String, namespace: String, handle: HandleIn, display_name: Option, person_id: Option, now: String, people: Option>, } let i: In = input(name, input_text)?; let failed: RefCell> = RefCell::new(None); let mut new_id = || minted(&db, &failed); let resolved = resolve_contact(ResolveContactArgs { db: &db, workspace_id: &i.workspace_id, namespace: &i.namespace, handle: &i.handle.into(), display_name: i.display_name.as_deref(), person_id: i.person_id.as_deref(), now: &i.now, new_id: &mut new_id, people: i.people.as_ref(), }) .map_err(ImportError::from)?; if let Some(words) = failed.into_inner() { return Err(ImportError::Driver(words).into()); } Ok(json!({ "contactId": resolved.contact_id, "changes": resolved.changes, "created": resolved.created })) } name if name.starts_with("send.") => crate::send::run(name, input_text, asker).map_err(|r| Refused { words: r.words, code: r.code }), _ => Err(Refused { words: format!("no engine run named {name}"), code: "bad_input" }), } } /// [`run`] as the Worker reads it: `{"ok": plan}` or `{"error": words, "code": code}`. pub fn run_json(name: &str, input_text: &str, asker: &A) -> String { match run(name, input_text, asker) { Ok(plan) => json!({ "ok": plan }).to_string(), Err(refused) => json!({ "error": refused.words, "code": refused.code }).to_string(), } } #[cfg(test)] #[path = "asked_tests.rs"] mod tests;