Cotton code
350 lines · 13.3 KB · RustRaw
//! One derivation, one writer — the port of//! `packages/core/src/engine/mediaItems.ts` (spec//! `2026-09-04-cotton-photos-videos-design` §D4).//!//! A chat message's `media[]` becomes photo and video rows HERE and nowhere//! else. The server's media-index sweep is the only caller — the phone never//! derives from messages — so a photo that arrived in a chat is minted once, by//! one device, past one cursor, rather than raced for by every phone that has//! the thread. Two writers would eventually disagree about a first sighting,//! and a disagreement here is a picture whose provenance changes under//! somebody.//!//! **Pure**: rows in, rows out, no driver, and no clock beyond the `now` the//! caller passes. That is what lets the sweep's test seed a message and read//! the exact rows the server would write.//!//! Audio, voice and ordinary files are not pictures and produce no photo/video rows.//! A picture key must name a content-addressed object; an old or malformed key//! fails derivation rather than silently omitting the attachment.use cotton_store::protocol::derived_id::{media_sighting_id, photo_record_id, video_record_id};use serde::{Deserialize, Serialize};use serde_json::Value;/// One attachment on a chat message — `MessageMedia` from/// `packages/core/src/models/message/types.ts`.////// The first ROW model this crate carries, and it is here rather than in a/// `models` module because exactly one engine reads it. Move it out the day a/// second does.////// The numbers are `f64` and not integers on purpose: they arrive as/// JavaScript numbers inside a JSON column, an importer may well have written/// `1024.5`, and the flooring below is the TypeScript's own — porting them as/// `i64` would move that decision to whoever deserialises and lose it.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct MessageMedia {    /// The media-store object key — `{workspaceId}/messages/{threadId}/{sha256}.{ext}`.    pub key: String,    /// MIME type as uploaded; the renderer branches on the `image/` prefix.    pub content_type: String,    /// The original filename, when the importer knew it — a chip's label.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub width: Option<f64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub height: Option<f64>,    /// Bytes, when the uploader knew — drives the "still loading" placeholder.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub size_bytes: Option<f64>,    /// Optional display kind; media derivation uses the MIME type.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub kind: Option<crate::constants::MessageMediaKind>,    /// Playback length for video / audio / voice.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub duration_ms: Option<f64>,    /// The same recording in a container the phone plays — a voice note's    /// CAF/Opus beside its Ogg original.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub playback_key: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub playback_content_type: Option<String>,    /// Voice notes: 64 samples in 0..1, drawn as bars.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub waveform: Option<Vec<f64>>,    /// A base64 JPEG (≤ 4 KB) shown blurred until the real bytes are local.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub preview: Option<String>,    /// A shared contact card, read out of the `.vcf` at import.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub contact: Option<Value>,}/// The message the sweep hands over — only the columns a row is derived from.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MediaItemMessage {    pub id: String,    pub thread_id: String,    pub workspace_id: String,    /// ISO instant. Becomes `taken_at`: when a picture arrived is the closest    /// thing a chat can say about when it was taken.    pub sent_at: String,    pub media: Vec<MessageMedia>,}/// Photo or video — what an attachment IS, once the content type has been read.////// An enum rather than two string literals because it is also the sighting's/// `record_kind`, and a sighting pointing at a kind the file does not know is/// a row nothing can ever join back.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum MediaFamily {    Photo,    Video,}impl MediaFamily {    pub const fn as_str(self) -> &'static str {        match self {            MediaFamily::Photo => "photo",            MediaFamily::Video => "video",        }    }}/// Where a sighting was seen. One variant today, and it is an enum rather than/// a `String` so that a caller cannot invent a source the sweep does not walk.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum SightingSource {    Message,}impl SightingSource {    pub const fn as_str(self) -> &'static str {        match self {            SightingSource::Message => "message",        }    }}/// A `cotton_photos` row, in the file's own column names — ready to write.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct PhotoInsert {    pub id: String,    pub workspace_id: String,    pub key: String,    pub sha256: String,    pub content_type: String,    pub size_bytes: i64,    pub width: Option<i64>,    pub height: Option<i64>,    pub taken_at: String,    pub preview: Option<String>,    pub created_at: String,    pub updated_at: String,}/// A `cotton_videos` row — the photo's, plus how long it runs.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct VideoInsert {    pub id: String,    pub workspace_id: String,    pub key: String,    pub sha256: String,    pub content_type: String,    pub size_bytes: i64,    pub width: Option<i64>,    pub height: Option<i64>,    pub taken_at: String,    pub preview: Option<String>,    pub created_at: String,    pub updated_at: String,    pub duration_ms: Option<i64>,}/// A `cotton_media_sightings` row (schema v39) — WHERE the sweep saw it.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct SightingInsert {    pub id: String,    pub workspace_id: String,    pub record_kind: MediaFamily,    pub record_id: String,    pub source: SightingSource,    pub source_id: String,    pub thread_id: String,    /// The message's own thread-scoped key — the object this sighting owns.    pub key: String,    pub seen_at: String,    pub created_at: String,    pub updated_at: String,}#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]pub struct MediaItems {    pub photos: Vec<PhotoInsert>,    pub videos: Vec<VideoInsert>,    /// One per photo or video, in the same order — the writer records the row    /// (or meets it, already there) and then its sighting, every time.    pub sightings: Vec<SightingInsert>,}/// The digest a content-addressed key carries, or `None`.////// `{ws}/messages/{thread}/{sha256}.{ext}` — the filename before its first/// dot. Deliberately strict: 64 lowercase hex and nothing else, because this/// string becomes the row's id and half of its UNIQUE, and a near-miss would/// mint a row the file refuses on the way in.////// An EMPTY key answers `None`, because the TypeScript's guard is `if (!key)`/// and the empty string is falsy there — `Option::is_none` alone would let a/// blank key from a malformed archive reach the regex.pub fn sha256_from_key(key: Option<&str>) -> Option<String> {    let key = key?;    if key.is_empty() {        return None;    }    // `key.split("/").pop() ?? ""` — a trailing slash gives the empty string,    // and a key with no slash at all is its own filename.    let name = key.rsplit('/').next().unwrap_or("");    // `name.split(".", 1)[0]` — everything before the FIRST dot, so    // `<sha>.poster.jpg` still reads as `<sha>` and `.<sha>.jpg` reads as the    // empty string (a dotfile is not a digest).    let stem = name.split('.').next().unwrap_or("");    if stem.len() == 64        && stem            .bytes()            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))    {        Some(stem.to_string())    } else {        None    }}/// An optional positive dimension, or `None` — a zero is not a width.fn dimension(value: Option<f64>) -> Option<i64> {    match value {        Some(v) if v.is_finite() && v > 0.0 => Some(v.floor() as i64),        _ => None,    }}/// What an attachment IS, read from the CONTENT TYPE rather than from `kind`.////// The stored MIME type determines whether bytes are a photo or video.fn family_of(entry: &MessageMedia) -> Option<MediaFamily> {    let type_ = entry.content_type.to_lowercase();    if type_.starts_with("image/") {        return Some(MediaFamily::Photo);    }    if type_.starts_with("video/") {        return Some(MediaFamily::Video);    }    None}/// Every photo and video row one message implies.////// `now` stamps `created_at` / `updated_at` — when the sweep noticed — while/// `taken_at` is the message's own `sent_at`. Two different questions: a grid/// groups by when a picture was taken, and a backfill must not pile a decade/// of archive onto the day it ran./// A picture whose key names no content hash — a storage fault, typed and/// never words; the index worker refuses the message with it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct UnaddressedPicture {    pub key: String,}impl std::fmt::Display for UnaddressedPicture {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        write!(f, "{self:?}")    }}pub fn media_items_for(message: &MediaItemMessage, now: &str) -> Result<MediaItems, UnaddressedPicture> {    let mut items = MediaItems::default();    for entry in &message.media {        let Some(family) = family_of(entry) else {            continue;        };        let sha256 = sha256_from_key(Some(&entry.key)).ok_or_else(|| UnaddressedPicture { key: entry.key.clone() })?;        let key = &entry.key;        // A missing size is 0, not null: the column is NOT NULL because the        // Storage screen adds these up, and a null would make one unknown        // attachment silently poison a total. Zero is honestly "we do not know        // yet", and the ledger corrects it when the bytes land.        let size_bytes = match entry.size_bytes {            Some(v) if v > 0.0 => v.floor() as i64,            _ => 0,        };        let width = dimension(entry.width);        let height = dimension(entry.height);        let sighting_for = |record_kind: MediaFamily, record_id: &str| SightingInsert {            id: media_sighting_id(                record_kind.as_str(),                record_id,                SightingSource::Message.as_str(),                Some(&message.id),            ),            workspace_id: message.workspace_id.clone(),            record_kind,            record_id: record_id.to_string(),            source: SightingSource::Message,            source_id: message.id.clone(),            thread_id: message.thread_id.clone(),            key: key.to_string(),            seen_at: message.sent_at.clone(),            created_at: now.to_string(),            updated_at: now.to_string(),        };        match family {            MediaFamily::Photo => {                let id = photo_record_id(&sha256);                items.photos.push(PhotoInsert {                    id: id.clone(),                    workspace_id: message.workspace_id.clone(),                    key: key.to_string(),                    sha256,                    content_type: entry.content_type.clone(),                    size_bytes,                    width,                    height,                    taken_at: message.sent_at.clone(),                    preview: entry.preview.clone(),                    created_at: now.to_string(),                    updated_at: now.to_string(),                });                items.sightings.push(sighting_for(MediaFamily::Photo, &id));            }            MediaFamily::Video => {                let id = video_record_id(&sha256);                items.sightings.push(sighting_for(MediaFamily::Video, &id));                items.videos.push(VideoInsert {                    id,                    workspace_id: message.workspace_id.clone(),                    key: key.to_string(),                    sha256,                    content_type: entry.content_type.clone(),                    size_bytes,                    width,                    height,                    taken_at: message.sent_at.clone(),                    preview: entry.preview.clone(),                    created_at: now.to_string(),                    updated_at: now.to_string(),                    duration_ms: match entry.duration_ms {                        Some(v) if v.is_finite() && v >= 0.0 => Some(v.floor() as i64),                        _ => None,                    },                });            }        }    }    Ok(items)}#[cfg(test)]#[path = "media_items_tests.rs"]mod tests;