Cotton code
167 lines · 5.6 KB · RustRaw
//! The check marks, and the exact claim each one makes.//!//! The port of `packages/core/src/messages/ticks.ts`.//!//! Ticks are the part of a messenger a person calibrates their trust on: if a//! double tick ever appears for a message the other phone has not got, every tick//! after it is noise. So the rules here are conservative — a claim is made only//! when the FILE can prove it, from cursors the relay wrote.//!//! `receipts` is every non-left member OTHER than this file's owner. A DM has//! exactly one. An empty list means nobody has reported yet, which is `sent`: the//! server has the row (it assigned the seq), and nothing more is known.use serde::{Deserialize, Serialize};use crate::constants::MessageDirection;/// `MESSAGE_TICKS` — declared here rather than in `constants.rs` because the/// TypeScript declares it here too: a tick is not a column, it is what this/// module concludes.////// The order is the TypeScript's and is the escalation order a person reads.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum MessageTick {    #[serde(rename = "sending")]    Sending,    #[serde(rename = "sent")]    Sent,    #[serde(rename = "delivered")]    Delivered,    #[serde(rename = "read")]    Read,    #[serde(rename = "failed")]    Failed,}impl MessageTick {    pub const fn as_str(self) -> &'static str {        match self {            MessageTick::Sending => "sending",            MessageTick::Sent => "sent",            MessageTick::Delivered => "delivered",            MessageTick::Read => "read",            MessageTick::Failed => "failed",        }    }    /// In the TypeScript's declared order.    pub const ALL: [MessageTick; 5] = [        MessageTick::Sending,        MessageTick::Sent,        MessageTick::Delivered,        MessageTick::Read,        MessageTick::Failed,    ];    pub fn parse(value: &str) -> Option<Self> {        Self::ALL.into_iter().find(|tick| tick.as_str() == value)    }}impl std::fmt::Display for MessageTick {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// One reader's two cursors, from `cotton_msg_receipts`.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TickCursor {    pub delivered_seq: i64,    pub read_seq: i64,}#[derive(Debug, Clone, PartialEq, Eq)]pub struct TickInput<'a> {    pub direction: MessageDirection,    /// The server's sequence number. `None` until the server has folded the row.    pub seq: Option<i64>,    /// The outbox gave up on this op (a final rejection, not a retry).    pub failed: bool,    pub receipts: &'a [TickCursor],}/// The tick to draw, or `None` for a message that has none.////// Order of the branches is the whole design:////// * **failed** first, because a failed send with a stale cursor beside it must///   never render as delivered;/// * **sending** — no seq means the server has not seen it: offline, or in///   flight;/// * **read** — every member's READ cursor is at or past this row;/// * **delivered** — every member's delivered cursor, or their read cursor which///   implies it, is at or past it;/// * **sent** — the server has it and that is all we know.pub fn tick_for(input: &TickInput<'_>) -> Option<MessageTick> {    if input.direction != MessageDirection::Out {        return None;    }    if input.failed {        return Some(MessageTick::Failed);    }    let Some(seq) = input.seq else {        return Some(MessageTick::Sending);    };    let cursors = input.receipts;    if cursors.is_empty() {        return Some(MessageTick::Sent);    }    if cursors.iter().all(|cursor| cursor.read_seq >= seq) {        return Some(MessageTick::Read);    }    // A reader who has READ a row has by definition received it, so the delivered    // claim takes the higher of the two cursors — the relay may write them in    // either order, and a lagging delivered_seq must not un-deliver a row    // somebody has already read.    if cursors        .iter()        .all(|cursor| cursor.delivered_seq.max(cursor.read_seq) >= seq)    {        return Some(MessageTick::Delivered);    }    Some(MessageTick::Sent)}/// The columns [`message_ticks`] reads off a message row.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct TickMessage {    pub direction: MessageDirection,    pub seq: Option<i64>,    pub failed: bool,}/// The tick for one message, given the thread's receipt rows and how many people/// are expected to report — the name the UI tracks import it by.////// `members` is why this is not just [`tick_for`] renamed. `tick_for` asks/// whether EVERY cursor it was handed is past the row, which is right for a dm/// and wrong for a group: a five-person thread where only one member's receipt/// has arrived would satisfy the `all()` and draw a double blue tick for a/// message three people may not hold at all. Missing cursors are not silent/// consent — until every expected reader has reported, the strongest honest claim/// is "sent".////// `members` counts the OTHER people expected to report. Zero means nobody is/// expected (a dm with no receipt yet), which reads as "sent" exactly as before.pub fn message_ticks(    message: &TickMessage,    receipts: &[TickCursor],    members: usize,) -> Option<MessageTick> {    let complete = receipts.len() >= members;    tick_for(&TickInput {        direction: message.direction,        seq: message.seq,        failed: message.failed,        receipts: if complete { receipts } else { &[] },    })}#[cfg(test)]#[path = "ticks_tests.rs"]mod tests;