//! THE message write. One function, and everybody calls it. //! //! The port of `packages/core/src/messages/applyMessageWrite.ts`. //! //! Before this there were two: `sendOwnerMessage` in the core package wrote the //! row and the thread denorm through `storeWrite`, and `postMessage` on the //! server wrote the same two things through its own adapter — each with its own //! copy of the preview rule and its own copy of the denorm guard. That was //! survivable while the server only ever wrote a visitor's message into one //! person's file. It stops being survivable the moment the RELAY writes the same //! row into N files: three spellings of "what a message row is" would diverge, //! and the divergence would show up as one member's copy of a conversation //! quietly disagreeing with another's. //! //! So: one function, which every writer reaches. It does not know where the rows //! go. The caller supplies a SINK — a function taking a list of row-level changes //! — because the two writers cannot be made to share a shape. //! //! # The async half, in Rust //! //! The TypeScript's `applyMessageWrite` is `async` because one of its two callers //! writes over the network. Rust's async is the CALLER's business and a pure //! library has no runtime, so [`apply_message_write`] here takes a synchronous //! sink and an async caller awaits its own future around [`plan_message_write`]. //! What is ported is the guarantee, which is the part that matters: plan FIRST, //! hand the batch to the sink exactly ONCE, and never touch the sink at all when //! the input is refused — because the message and the thread it moved are ONE //! act, and a half-applied pair is a thread whose preview disagrees with its own //! last line. use serde_json::{Map, Value}; use cotton_store::outbox::LocalChange; use cotton_store::protocol::types::OpKind; use crate::constants::{MessageChannel, MessageDirection, MessageOrigin}; use crate::messages::limits::MESSAGE_BODY_MAX; use crate::messages::preview::{preview_for_message, should_advance_thread, PreviewSource}; use crate::messages::{js_trim, utf16_len, MessageMedia, MessageMeta}; const MESSAGES: &str = "cotton_msg_messages"; const THREADS: &str = "cotton_msg_threads"; /// `/^[0-9]{8,15}$/` — a mention is a phone as digits and nothing else. /// /// Written as a length-and-bytes test rather than a regex for the same reason /// [`crate::messages::ids`] does: JavaScript's `[0-9]` is the ASCII digits, and /// an Arabic-Indic numeral is not a phone number on either side. fn is_phone(value: &str) -> bool { (8..=15).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_digit()) } /// The thread columns the write needs. The CALLER reads the row. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MessageWriteThread<'a> { pub id: &'a str, pub workspace_id: &'a str, pub last_message_at: Option<&'a str>, } /// Everything a message write is told. /// /// `edited_at` and `deleted_at` are `Option>` on purpose, and it is /// the one place in this tree where the double option earns its keep: the OUTER /// `None` is the TypeScript's `undefined` — the key is left out of the patch /// entirely — and `Some(None)` is an explicit SQL `NULL`. They are set only by /// the RELAY, and only for a message that was already edited or already /// deleted-for-everyone by the time it first reached this file. A person /// composing a message has neither, and an op carrying `edited_at: null` would be /// a writer claiming a column it has nothing to say about. pub struct MessageWriteInput<'a> { pub thread: MessageWriteThread<'a>, /// Minted by the caller — a media object key carries it, so it is reserved /// first. pub message_id: &'a str, pub direction: MessageDirection, /// Defaults to `cotton`; an importer or the owner's reply target names its channel. pub channel: Option, /// Defaults to `live`. Only the importer ever passes `imported`. pub origin: Option, pub body: Option<&'a str>, pub media: &'a [MessageMedia], /// Phones, digits only. Behaviour-bearing: a mention overrides mute. pub mentions: &'a [String], pub reply_to_id: Option<&'a str>, pub reply_to_external_id: Option<&'a str>, /// Provenance. May name a row this file does not hold. pub forward_of_id: Option<&'a str>, pub external_id: Option<&'a str>, pub sender_participant_id: Option<&'a str>, /// The server's sequence number. `None` everywhere except a relay mirror. pub seq: Option, /// See the type doc: outer `None` omits the column, `Some(None)` writes NULL. pub edited_at: Option>, /// See the type doc: outer `None` omits the column, `Some(None)` writes NULL. pub deleted_at: Option>, pub meta: Option<&'a MessageMeta>, pub sent_at: &'a str, pub now: &'a str, /// Send-from-the-composer: the draft this message replaces goes in the same /// batch. pub clear_draft: bool, /// A text the serving Mac is to send out (`queued`): the row starts its /// send state and attempt count. `None` everywhere else, and the columns /// are left out of the patch. pub send_state: Option<&'a str>, } impl<'a> MessageWriteInput<'a> { /// The five things a write cannot be without; everything else is a default a /// caller overrides with struct-update syntax. /// /// A `Default` impl would have to invent a direction and a pair of instants, /// and a message with a made-up `sent_at` is a row in the wrong place in /// somebody's conversation. pub fn new( thread: MessageWriteThread<'a>, message_id: &'a str, direction: MessageDirection, sent_at: &'a str, now: &'a str, ) -> Self { MessageWriteInput { thread, message_id, direction, channel: None, origin: None, body: None, media: &[], mentions: &[], reply_to_id: None, reply_to_external_id: None, forward_of_id: None, external_id: None, sender_participant_id: None, seq: None, edited_at: None, deleted_at: None, meta: None, sent_at, now, clear_draft: false, send_state: None, } } } #[derive(Debug, Clone, PartialEq)] pub struct MessageWritePlan { pub message_id: String, /// In order. The message first, so a half-applied pair is never a naked /// denorm. pub changes: Vec, pub preview: String, pub advanced_thread: bool, } /// A write the rule refuses. /// /// The TypeScript throws an `AppError` carrying a CODE the callers switch on; /// `Display` here is the refusal sentence VERBATIM and [`Self::code`] is that /// code, so a handler can hand both to the error envelope unchanged. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum MessageWriteRefused { #[error("Write something first")] Empty, /// `max` is preformatted because the TypeScript interpolates /// `MESSAGE_BODY_MAX.toLocaleString("en-GB")` — the sentence a person reads /// carries the thousands separator, and the number in it must track the /// constant rather than be typed out beside it. #[error("That message is too long — {max} characters maximum.")] TooLong { max: String }, #[error("A mention is a phone as digits, got \"{phone}\"")] BadMention { phone: String }, } impl MessageWriteRefused { pub const fn code(&self) -> &'static str { match self { MessageWriteRefused::Empty => "EMPTY_MESSAGE", MessageWriteRefused::TooLong { .. } => "MESSAGE_TOO_LONG", MessageWriteRefused::BadMention { .. } => "VALIDATION", } } } /// `Number.prototype.toLocaleString("en-GB")` for a non-negative integer: groups /// of three from the right, separated by commas. /// /// en-GB and not the host's locale, because the TypeScript names the locale /// explicitly — a server running under a locale that groups by lakhs would /// otherwise show "4,000" to one person and "4,000" spelled differently to /// another, for the same refusal. fn en_gb_thousands(value: usize) -> String { let digits = value.to_string(); let mut out = String::with_capacity(digits.len() + digits.len() / 3); for (index, ch) in digits.chars().enumerate() { if index > 0 && (digits.len() - index).is_multiple_of(3) { out.push(','); } out.push(ch); } out } /// The row and the denorm, as changes — everything Postgres used to do around an /// insert, because a file has no triggers: /// /// * the workspace comes from the THREAD, never from the caller; /// * the thread's `last_message_at` / `last_message_preview` move in the SAME /// batch, guarded so an old row cannot drag a live thread's preview back; /// * the preview text is spec §7.2's, computed once. /// /// It writes ONLY shared-content columns. Nothing private (`read_at`, /// `starred_at`, `hidden_at`, `read_seq`, `delivered_seq`, `muted_until`, …) /// appears in either patch, because those belong to the file's owner and the /// relay must never contend for them (spec §3.3). /// /// Both patches are `serde_json::Map`s built in the TypeScript object literal's /// own key ORDER: a patch is stored as JSON in the op log, so the order is /// observable, and the workspace enables serde_json's `preserve_order` for /// exactly this. pub fn plan_message_write( input: &MessageWriteInput<'_>, ) -> Result { let body = js_trim(input.body.unwrap_or("")); if body.is_empty() && input.media.is_empty() { return Err(MessageWriteRefused::Empty); } // `body.length` is UTF-16 code units, so a message of 3 000 emoji is 6 000 by // this measure and is refused — on both sides, identically. if utf16_len(body) > MESSAGE_BODY_MAX { return Err(MessageWriteRefused::TooLong { max: en_gb_thousands(MESSAGE_BODY_MAX), }); } for phone in input.mentions { if !is_phone(phone) { return Err(MessageWriteRefused::BadMention { phone: phone.clone(), }); } } let media = serde_json::to_value(input.media).unwrap_or(Value::Array(Vec::new())); let mentions = Value::Array( input .mentions .iter() .map(|phone| Value::from(phone.as_str())) .collect(), ); let meta = match input.meta { Some(meta) => serde_json::to_value(meta).unwrap_or(Value::Object(Map::new())), None => Value::Object(Map::new()), }; let mut patch = Map::new(); patch.insert("id".to_string(), Value::from(input.message_id)); patch.insert("thread_id".to_string(), Value::from(input.thread.id)); // The BEFORE trigger's job: the workspace is the THREAD's, always. patch.insert( "workspace_id".to_string(), Value::from(input.thread.workspace_id), ); patch.insert( "direction".to_string(), Value::from(input.direction.as_str()), ); patch.insert( "channel".to_string(), Value::from(input.channel.unwrap_or(MessageChannel::Cotton).as_str()), ); patch.insert( "origin".to_string(), Value::from(input.origin.unwrap_or(MessageOrigin::Live).as_str()), ); // `body || null` — a body that trimmed to nothing is stored as NULL, never as // an empty string, so a media-only row reads the same everywhere. patch.insert( "body".to_string(), if body.is_empty() { Value::Null } else { Value::from(body) }, ); patch.insert("media".to_string(), media); patch.insert("mentions".to_string(), mentions); patch.insert("external_id".to_string(), optional(input.external_id)); patch.insert("sent_at".to_string(), Value::from(input.sent_at)); patch.insert("created_at".to_string(), Value::from(input.now)); patch.insert("reply_to_id".to_string(), optional(input.reply_to_id)); patch.insert( "reply_to_external_id".to_string(), optional(input.reply_to_external_id), ); patch.insert("forward_of_id".to_string(), optional(input.forward_of_id)); patch.insert( "sender_participant_id".to_string(), optional(input.sender_participant_id), ); patch.insert( "seq".to_string(), match input.seq { Some(seq) => Value::from(seq), None => Value::Null, }, ); // Empty from v9 on — reactions are rows. The column stays so an old build's // op still folds. patch.insert("reactions".to_string(), Value::Array(Vec::new())); patch.insert("meta".to_string(), meta); if let Some(edited_at) = input.edited_at { patch.insert("edited_at".to_string(), optional(edited_at)); } if let Some(deleted_at) = input.deleted_at { patch.insert("deleted_at".to_string(), optional(deleted_at)); } if let Some(state) = input.send_state { patch.insert("send_state".to_string(), Value::from(state)); patch.insert("send_attempts".to_string(), Value::from(0)); } let mut changes = vec![LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: MESSAGES.to_string(), row_id: input.message_id.to_string(), patch: Some(patch), }]; let preview = preview_for_message(&PreviewSource { body: Some(body), media: input.media, deleted_at: None, meta: input.meta, }); let advanced_thread = should_advance_thread(input.thread.last_message_at, input.sent_at); let mut thread_patch = Map::new(); if advanced_thread { thread_patch.insert("last_message_at".to_string(), Value::from(input.sent_at)); thread_patch.insert( "last_message_preview".to_string(), Value::from(preview.as_str()), ); thread_patch.insert("updated_at".to_string(), Value::from(input.now)); } if input.clear_draft { // Cleared whether or not the denorm moved: the person's half-sentence is // now a sent message, and leaving the draft would restore it on reopen. thread_patch.insert("draft".to_string(), Value::Null); thread_patch.insert("draft_reply_to_id".to_string(), Value::Null); } if !thread_patch.is_empty() { changes.push(LocalChange { delete: Default::default(), kind: OpKind::Upsert, table: THREADS.to_string(), row_id: input.thread.id.to_string(), patch: Some(thread_patch), }); } Ok(MessageWritePlan { message_id: input.message_id.to_string(), changes, preview, advanced_thread, }) } /// `x ?? null` for a column the caller may have nothing to say about. fn optional(value: Option<&str>) -> Value { match value { Some(value) => Value::from(value), None => Value::Null, } } /// Either the rule refused, or the sink did. /// /// Two variants and not one flattened error: a refusal is the writer's fault and /// is final, while a sink failure is a transport or a disk and is the caller's to /// retry. Collapsing them would make a caller guess which happened. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ApplyMessageWriteError { #[error("{0}")] Refused(#[from] MessageWriteRefused), #[error("{0}")] Sink(E), } /// Plan, then apply. The batch reaches the sink exactly once — the message and the /// thread it moved are ONE act — and never at all when the input is refused. pub fn apply_message_write( sink: S, input: &MessageWriteInput<'_>, ) -> Result> where E: std::fmt::Display + std::fmt::Debug, S: FnOnce(&[LocalChange]) -> Result<(), E>, { let plan = plan_message_write(input)?; sink(&plan.changes).map_err(ApplyMessageWriteError::Sink)?; Ok(plan) } #[cfg(test)] #[path = "apply_message_write_tests.rs"] mod tests;