Cotton code
1033 lines · 45.9 KB · RustRaw
//! Where a person's media lives, spelled once — the port of//! `packages/core/src/media/keys.ts`.//!//! The TypeScript module's three reasons carry over unchanged://!//! - **One spelling.** The phone builds a key, the server validates and//!   presigns it, the migration tool maps the old one onto it, and the export//!   manifest enumerates it. Four readers of the same string.//! - **One prefix.** Every key starts `{file_id}/` — the file's OWN id, never//!   its namespace: two files sharing a namespace must never share a folder.//!   There is no bucket RLS in front of the object store and the server holds//!   a credential that spans all of it, so [`assert_key_in_workspace`] IS the//!   wall. Every builder and check takes a `FileId`, which only an open file//!   hands out.//! - **No I/O.** Pure functions over values, callable from a handler, a//!   worker or a test.//!//! Two places need JavaScript's own semantics rather than Rust's, and both are//! spelled out where they happen: `String.prototype.trim` / `\s` (the//! ECMAScript whitespace class, which is not Rust's `char::is_whitespace`) and//! `String.prototype.slice` / `.length` (UTF-16 code units, not `char`s or//! bytes — a `🎉` in a filename is TWO units and becomes `--`, which the//! vectors in the tests below pin against Node).use std::collections::BTreeSet;use cotton_store::file_identity::FileId;use cotton_store::media_holdings::Tier;use cotton_store::protocol::js::is_js_whitespace;pub use cotton_rules::media::{MediaKind, MediaLimit, media_limits, BOOK_EXTENSIONS, SONG_EXTENSIONS, song_content_type, FILM_WHOLE_EXTENSIONS, FILM_SOURCE_EXTENSIONS, film_content_type};/// The longest key the store will accept, in UTF-16 code units — S3 allows/// 1024, and half of that is more than any real filename needs.pub const MAX_KEY_LENGTH: usize = 512;/// Everything this workspace owns lives under here. The trailing slash is/// load-bearing: without it, listing `ws-1` also returns `ws-10/...`.pub fn workspace_prefix(file_id: &FileId) -> String {    format!("{file_id}/")}// ─────────────────────────────────────────────────────────────────────────────// JavaScript string semantics, where a key's bytes depend on them.// ─────────────────────────────────────────────────────────────────────────────/// `String.prototype.trim()` — the ECMAScript whitespace class, which is not/// Rust's `char::is_whitespace` (it excludes U+FEFF and includes U+0085).fn js_trim(input: &str) -> &str {    input.trim_matches(is_js_whitespace)}/// The length JavaScript reports — UTF-16 code units.fn utf16_len(input: &str) -> usize {    input.encode_utf16().count()}/// Strip a filename down to what an object key may carry, keeping the/// extension — a viewer judges a presigned URL by it.////// Per UTF-16 CODE UNIT, because the TypeScript regex carries no `u` flag: a/// non-BMP character is two units and becomes two dashes, and `.slice(-80)`/// counts units too. Every character that survives is ASCII, so the collapse/// and the tail can then work on bytes.////// The dot run-collapse is not cosmetic: [`assert_key_in_workspace`] refuses/// any key containing `..`, and a real filename can arrive carrying one./// Without this, a key this module BUILT would fail the check this module/// enforces.fn safe_name(name: &str) -> String {    let mapped: String = name        .encode_utf16()        .map(|unit| {            let ch = char::from_u32(u32::from(unit)).unwrap_or('-');            if ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == '-' {                ch            } else {                '-'            }        })        .collect();    // `.replace(/\.{2,}/g, ".")`    let mut collapsed = String::with_capacity(mapped.len());    let mut dots = 0usize;    for ch in mapped.chars() {        if ch == '.' {            dots += 1;            continue;        }        if dots > 0 {            collapsed.push('.');            dots = 0;        }        collapsed.push(ch);    }    if dots > 0 {        collapsed.push('.');    }    // `.slice(-80)` — ASCII by now, so bytes and code units agree.    if collapsed.len() > 80 {        collapsed[collapsed.len() - 80..].to_string()    } else {        collapsed    }}/// `.ext`, or nothing — normalised so a caller may pass `"jpg"`, `".jpg"` or/// `"JPG"` and the key comes out the same.////// Anything that is not a plain alphanumeric run is dropped rather than/// escaped: an extension is a hint for a viewer, and a key/// [`is_key_in_workspace`] would then refuse is worse than none.fn ext_suffix(ext: &str) -> String {    let without_leading_dot = ext.strip_prefix('.').unwrap_or(ext);    let cleaned: String = without_leading_dot        .encode_utf16()        .filter_map(|unit| char::from_u32(u32::from(unit)))        .filter(|ch| ch.is_ascii_alphanumeric())        .collect::<String>()        .to_ascii_lowercase();    let cleaned = if cleaned.len() > 12 {        &cleaned[..12]    } else {        &cleaned[..]    };    if cleaned.is_empty() {        String::new()    } else {        format!(".{cleaned}")    }}// ─────────────────────────────────────────────────────────────────────────────// The key builders.// ─────────────────────────────────────────────────────────────────────────────/// `{file_id}/{folder}/original.{ext}` — a document's permanent bytes.////// The middle segment is the document's id when the SERVER files it and a/// per-upload TOKEN when the PHONE does. Both are opaque here; what matters is/// that a document's original and its unlocked rendition share one folder, so/// a delete sweeps a prefix.pub fn document_original_key(file_id: &FileId, document_id: &str, ext: &str) -> String {    // Deliberately NOT `ext_suffix`: the TypeScript strips one leading dot and    // otherwise passes the extension through verbatim, so `tar.gz` survives.    let suffix = if ext.is_empty() {        String::new()    } else {        format!(".{}", ext.strip_prefix('.').unwrap_or(ext))    };    format!("{file_id}/{document_id}/original{suffix}")}/// `{file_id}/{folder}/unlocked.pdf` — the decrypted rendition the/// pipeline writes beside the original.pub fn document_unlocked_key(file_id: &FileId, document_id: &str) -> String {    format!("{file_id}/{document_id}/unlocked.pdf")}/// `{file_id}/_staging/{sha256}/{name}` — where an assistant's upload/// lands before it is a document.////// Keyed by the file's own hash so a re-run of the same harvest overwrites/// rather than accumulating, and under a reserved folder so a staged blob can/// never be mistaken for a filed one.pub fn document_staging_key(file_id: &FileId, sha256: &str, original_name: &str) -> String {    format!(        "{file_id}/_staging/{sha256}/{}",        safe_name(original_name)    )}/// `{file_id}/{token}-{name}` — a bank statement, immutable per upload.pub fn statement_key(file_id: &FileId, token: &str, file_name: &str) -> String {    format!("{file_id}/{token}-{}", safe_name(file_name))}/// The container a meeting's audio is in when nothing says otherwise — what/// the recorder produces, and what every meeting written before the key carried/// its own extension is stored as.pub const MEETING_AUDIO_DEFAULT_EXT: &str = "m4a";/// `{file_id}/meetings/{meeting_id}/full.m4a` — the assembled recording in/// the default container.////// The FALLBACK spelling, kept as its own function because it is what a row/// with no manifest means (`meeting_audio_object`) and what the conformance/// vectors pin. A recording whose container is known goes through/// [`meeting_full_key_of`].pub fn meeting_full_key(file_id: &FileId, meeting_id: &str) -> String {    meeting_full_key_of(file_id, meeting_id, MEETING_AUDIO_DEFAULT_EXT)}/// `{file_id}/meetings/{meeting_id}/full.<ext>` — the recording, in the/// container it actually arrived in.////// **The extension follows the source.** A WhatsApp voice note is Opus in an/// Ogg container and lands at `full.opus`; writing it at `full.m4a` and letting/// the object's content type carry the truth is what the cell did, and it made/// the key lie to every reader that has only the key — the vendor's input name,/// a person saving a copy, the export manifest.pub fn meeting_full_key_of(file_id: &FileId, meeting_id: &str, ext: &str) -> String {    format!(        "{file_id}/meetings/{meeting_id}/full{}",        ext_suffix(ext)    )}/// `{file_id}/meetings/{meeting_id}/tracks/{track}.<ext>` — one person's own audio of a call's notes (chat CONTRACT/// "Take notes"), under the meeting's prefix so a delete takes it with the rest. A track id keeps only letters,/// digits, `-` and `_`.pub fn meeting_track_key_of(file_id: &FileId, meeting_id: &str, track: &str, ext: &str) -> String {    let track: String = track.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();    format!("{file_id}/meetings/{meeting_id}/tracks/{track}{}", ext_suffix(ext))}/// `{file_id}/meetings/{meeting_id}/segments/{nnn}.m4a` — the recorder's/// durability copies. Derived from the sequence number, never stored, so a/// delete can find objects the manifest does not spell out.pub fn meeting_segment_key(file_id: &FileId, meeting_id: &str, seq: i64) -> String {    // `String(seq).padStart(3, "0")` — a sequence past 999 is simply longer,    // it is not truncated, and JS pads the MINUS SIGN like any other    // character (`String(-1).padStart(3,"0")` is `0-1`), so the padding is    // spelled out rather than left to Rust's sign-aware `{:03}`.    let digits = seq.to_string();    let padded = if digits.len() >= 3 {        digits    } else {        format!("{}{digits}", "0".repeat(3 - digits.len()))    };    format!("{file_id}/meetings/{meeting_id}/segments/{padded}.m4a")}/// Everything one meeting owns — for a prefix delete or a list.pub fn meeting_segment_prefix(file_id: &FileId, meeting_id: &str) -> String {    format!("{file_id}/meetings/{meeting_id}/")}/// `{file_id}/messages/{thread_id}/{sha256}.{ext}` — a file that arrived/// in a conversation.////// CONTENT-ADDRESSED: a WhatsApp export is re-imported routinely, and a key/// derived from the bytes means a re-import overwrites itself instead of/// orphaning a copy per run. The thread folder is housekeeping, not/// addressing: deleting a thread sweeps a prefix.pub fn message_media_key(file_id: &FileId, thread_id: &str, sha256: &str, ext: &str) -> String {    format!(        "{file_id}/messages/{thread_id}/{sha256}{}",        ext_suffix(ext)    )}/// Everything ONE conversation's attachments live under.////// Two readers, and the second is why it is a function rather than a `format!`/// at each call site: a delete sweeps this prefix, and `send_message` checks an/// attachment's key against it before it writes the row — an attachment naming/// another thread's folder (or another workspace's) is never innocent, and one/// spelling of "this thread's folder" is what keeps the sweep and the check/// agreeing about which objects belong to it.pub fn message_media_prefix(file_id: &FileId, thread_id: &str) -> String {    format!("{file_id}/messages/{thread_id}/")}/// `{file_id}/messages/{thread_id}/{sha256}.{ext}.t256.jpg` — the 256 px/// thumbnail of a picture that arrived in a conversation, for the key of that/// picture; `None` for any key that is not a conversation's file, or that is/// already a rendition.////// THE ORIGINAL'S WHOLE KEY, THEN THE SUFFIX. A chat's picture has no record/// of its own to find it by digest (a photo's thumbnail is named off its/// digest and `cotton_photos` says which original that is), so the thumbnail/// carries its original's key and [`message_picture_of_thumb`] reads it back/// with no lookup. The key is only a name: the personal object draws it from/// the original at 256 pixels, and no producer writes one ahead of it.////// Whether the file IS a picture is the row's to say (its content type), not/// the key's: a voice note's key answers a thumbnail nobody will ever write,/// which a reader finds absent and walks past.pub fn message_thumb_key_for(key: &str) -> Option<String> {    let segments: Vec<&str> = key.split('/').collect();    if segments.len() != 4 || segments[1] != "messages" || segments.iter().any(|segment| segment.is_empty()) {        return None;    }    if key.ends_with(THUMB_SUFFIX) || key.ends_with(DISPLAY_SUFFIX) {        return None;    }    Some(format!("{key}{THUMB_SUFFIX}"))}/// The conversation's picture a [`message_thumb_key_for`] thumbnail is drawn/// from, or `None` for any other key.pub fn message_picture_of_thumb(key: &str) -> Option<&str> {    let original = key.strip_suffix(THUMB_SUFFIX)?;    (message_thumb_key_for(original).as_deref() == Some(key)).then_some(original)}/// `{file_id}/session-messages/{message_id}/{sha256}.{ext}` — a picture/// on an instruction or an answer.pub fn session_message_media_key(    file_id: &FileId,    message_id: &str,    sha256: &str,    ext: &str,) -> String {    format!(        "{file_id}/session-messages/{message_id}/{sha256}{}",        ext_suffix(ext)    )}/// `{file_id}/people/{person_id}/{sha256}.{ext}` — a person's photo.////// Content-addressed for a different reason than a message's: a photo is/// REPLACED rather than accumulated, and an immutable key means the old object/// is still there to be swept deliberately rather than being overwritten under/// a reader that is mid-download.pub fn avatar_key(file_id: &FileId, person_id: &str, sha256: &str, ext: &str) -> String {    format!(        "{file_id}/people/{person_id}/{sha256}{}",        ext_suffix(ext)    )}/// The folder under a person's (or a group thread's) own folder that holds a/// profile picture WhatsApp gave. It IS the picture's provenance: every other/// writer of an avatar (the owner's pick, the People import, a face print)/// makes an [`avatar_key`] without it, so a picture the owner chose can never/// read as WhatsApp's, and replacing it ends WhatsApp's claim with no second/// column to forget to clear.pub const WHATSAPP_PICTURE_FOLDER: &str = "whatsapp";/// `{file_id}/people/{person_id}/whatsapp/{sha256}.{ext}` — a person's photo/// that came from their WhatsApp profile.pub fn whatsapp_avatar_key(file_id: &FileId, person_id: &str, sha256: &str, ext: &str) -> String {    format!(        "{file_id}/people/{person_id}/{WHATSAPP_PICTURE_FOLDER}/{sha256}{}",        ext_suffix(ext)    )}/// `{file_id}/messages/{thread_id}/whatsapp/{sha256}.{ext}` — a group's/// picture, inside its thread's folder so deleting the thread sweeps it.pub fn whatsapp_group_picture_key(file_id: &FileId, thread_id: &str, sha256: &str, ext: &str) -> String {    format!(        "{file_id}/messages/{thread_id}/{WHATSAPP_PICTURE_FOLDER}/{sha256}{}",        ext_suffix(ext)    )}/// Whether this avatar or group picture is still the one WhatsApp gave —/// the only kind a WhatsApp profile picture may replace.pub fn is_whatsapp_picture_key(key: &str) -> bool {    let segments: Vec<&str> = key.split('/').collect();    segments.len() == 5        && matches!(segments[1], "people" | "messages")        && segments[3] == WHATSAPP_PICTURE_FOLDER        && !segments[4].is_empty()}/// `{file_id}/walkthroughs/{sha256}.{ext}` — one captured screen.////// FLAT by design: a publish is immutable and versioned, and a screen row/// carries `image_sha256` + `image_ext` instead of a path, so an unchanged/// screen in v7 IS the v6 object. A per-walkthrough folder would copy every/// unchanged screen forward on every publish.pub fn walkthrough_image_key(file_id: &FileId, sha256: &str, ext: &str) -> String {    format!("{file_id}/walkthroughs/{sha256}{}", ext_suffix(ext))}/// `{file_id}/repos/{repo_id}/bundles/{sha256}.bundle` — one git bundle.////// CONTENT-ADDRESSED so a re-bundle converges: the mirror worker cuts a bundle/// from whatever the refs say, and two passes over a repository that has not/// moved produce the same bytes — a key derived from them means the second/// pass overwrites itself instead of leaving a copy per pass on every Mac.////// FOLDER-PER-REPOSITORY so forgetting a repository is a prefix sweep/// ([`repo_media_prefix`]), the documents-and-meetings argument: a repository/// can own thousands of objects and a flat folder would make a delete a walk/// of the whole store.////// The extension is FIXED rather than passed, because a bundle is one format/// and a caller that could choose could write `.bundle` two ways.pub fn repo_bundle_key(file_id: &FileId, repo_id: &str, sha256: &str) -> String {    format!("{file_id}/repos/{repo_id}/bundles/{sha256}.bundle")}/// `{file_id}/repos/{repo_id}/releases/{sha256}.{ext}` — one release/// asset.////// Content-addressed and folder-per-repository for [`repo_bundle_key`]'s/// reasons exactly, and the asset's own NAME is not in the key: two releases of/// one repository routinely ship a file with the same name and different bytes,/// and the name a person sees is the `name` field of the release row's/// `assets_json` entry, which points at this key.pub fn repo_release_asset_key(    file_id: &FileId,    repo_id: &str,    sha256: &str,    ext: &str,) -> String {    format!(        "{file_id}/repos/{repo_id}/releases/{sha256}{}",        ext_suffix(ext)    )}/// `{file_id}/repos/{repo_id}/attachments/{sha256}.{ext}` — a file an/// issue, a pull request or a comment carries.////// The host serves these as `/attachments/<uuid>` and a body links to them by/// that url; the mirror fetches each one once, files it here, and rewrites the/// stored body to `cotton-media://<key>` so the phone renders it through/// `read.mediaPath` rather than dialling a host it may not reach. Content/// addressing is what makes that rewrite idempotent: the same attachment/// referenced from three comments is one object.pub fn repo_attachment_key(file_id: &FileId, repo_id: &str, sha256: &str, ext: &str) -> String {    format!(        "{file_id}/repos/{repo_id}/attachments/{sha256}{}",        ext_suffix(ext)    )}/// `{file_id}/repos/{repo_id}/runs/{sha256}.log` — a finished CI job's/// log, filed so a standby Mac holds it too (schema v20).////// **The LIVE log is a file**, appended to at `~/CottonDB/runs/<run>/<job>.log`/// while the job runs; this key is what it becomes when the job ends. Logs/// never become rows: ten thousand lines of `cargo test` output is not/// something every device should hold as rows, and the `READ_LESS` page over/// it reads the file rather than a table.////// Content-addressed for [`repo_bundle_key`]'s reason, and it pays here more/// than anywhere: a re-run that produces byte-identical output — a cached/// no-op lane — is ONE object however many times it runs.pub fn repo_run_log_key(file_id: &FileId, repo_id: &str, sha256: &str) -> String {    format!("{file_id}/repos/{repo_id}/runs/{sha256}.log")}/// Whether a key is a repository bundle ([`repo_bundle_key`]'s shape:/// `<file>/repos/<repo>/bundles/<sha>.bundle`) — a full repository at a cut/// and once a day, a few kilobytes per push between — which the media mirror/// leaves out of the backup (`mirrors_key`).pub fn is_repo_bundle_key(key: &str) -> bool {    let mut parts = key.splitn(5, '/');    matches!(        (parts.next(), parts.next(), parts.next(), parts.next(), parts.next()),        (Some(file), Some("repos"), Some(repo), Some("bundles"), Some(name))            if !file.is_empty() && !repo.is_empty() && name.ends_with(".bundle")    )}/// Whether a key is a finished CI job's log ([`repo_run_log_key`]'s shape:/// `<file>/repos/<repo>/runs/<name>`) — disposable, and left out of the/// media mirror's backup with the bundles.pub fn is_repo_run_log_key(key: &str) -> bool {    let mut parts = key.splitn(5, '/');    matches!(        (parts.next(), parts.next(), parts.next(), parts.next(), parts.next()),        (Some(file), Some("repos"), Some(repo), Some("runs"), Some(name))            if !file.is_empty() && !repo.is_empty() && !name.is_empty()    )}/// Everything ONE repository owns — the prefix a delete sweeps.////// A function rather than a `format!` at each call site for/// [`message_media_prefix`]'s reason: forgetting a repository sweeps this/// prefix, and whatever checks that an object belongs to a repository before/// writing a row about it compares against the same one spelling.pub fn repo_media_prefix(file_id: &FileId, repo_id: &str) -> String {    format!("{file_id}/repos/{repo_id}/")}/// `{file_id}/photos/{sha256}.{ext}` — a picture the person added from/// the share sheet or the library picker (schema v31).pub fn photo_key(file_id: &FileId, sha256: &str, ext: &str) -> String {    format!("{file_id}/photos/{sha256}{}", ext_suffix(ext))}/// `{file_id}/videos/{sha256}.{ext}` — a video the person added, keyed by/// its own bytes for [`photo_key`]'s reasons exactly.pub fn video_key(file_id: &FileId, sha256: &str, ext: &str) -> String {    format!("{file_id}/videos/{sha256}{}", ext_suffix(ext))}/// `{file_id}/books/{sha256}.{ext}` — a book's file, EPUB or PDF, keyed by/// its own bytes for [`photo_key`]'s reasons: the same file shared twice is/// one object. Flat, one object per book: the reader streams or keeps it whole/// (`POST /v1/media/stream` signs one book key), and nothing derives from it.pub fn book_key(file_id: &FileId, sha256: &str, ext: &str) -> String {    format!("{file_id}/books/{sha256}{}", ext_suffix(ext))}/// `{file_id}/music/{sha256}.{ext}` — a song's audio file, keyed by its own/// bytes for [`photo_key`]'s reasons: the same file shared twice is one/// object. Flat, one object per song: the player streams or keeps it whole/// (`POST /v1/media/stream` signs one song key).pub fn song_key(file_id: &FileId, sha256: &str, ext: &str) -> String {    format!("{file_id}/music/{sha256}{}", ext_suffix(ext))}/// `{database_id}/films/{record_id}/whole.{ext}` — a film the phone plays as it/// is (an MP4, M4V or MOV holding H.264 or HEVC with AAC), kept whole in the/// film record's own folder, so erasing the record takes it with the folder./// The stream route signs the folder, and serves it by range.pub fn film_whole_key(database_id: &str, record_id: &str, ext: &str) -> String {    format!("{database_id}/films/{record_id}/whole{}", ext_suffix(ext))}/// `{database_id}/films/{record_id}/source.{ext}` — a film's upload in a/// container the phone does not play, waiting in the record's folder for the/// Mac to make its HLS stream beside it.pub fn film_source_key(database_id: &str, record_id: &str, ext: &str) -> String {    format!("{database_id}/films/{record_id}/source{}", ext_suffix(ext))}/// `{database_id}/films/{record_id}/master.m3u8` — the HLS master the Mac lays in/// the film record's folder, the key the record's `file` holds once it lands.pub fn film_master_key(database_id: &str, record_id: &str) -> String {    format!("{database_id}/films/{record_id}/master.m3u8")}/// `{file_id}/videos/{sha256}.poster.jpg` — the still frame that stands/// in for a video in a grid.////// DERIVED from the video's own hash rather than the poster's, so the phone/// can name it before it has encoded it. It sits beside the video under/// `videos/`, which means [`media_kind_for`] answers [`MediaKind::Video`] for/// it — see the `image/jpeg` entry in the video content types.pub fn video_poster_key(file_id: &FileId, sha256: &str) -> String {    format!("{file_id}/videos/{sha256}.poster.jpg")}/// The suffix every 256 px grid thumbnail carries. Spelled once because a/// delete has to recognise the key it never built.pub const THUMB_SUFFIX: &str = ".t256.jpg";/// The suffix every 1600 px display rendition carries.pub const DISPLAY_SUFFIX: &str = ".d1600.jpg";/// `{file_id}/photos/{sha256}.t256.jpg` — the 256 px grid thumbnail.////// Keyed off the ORIGINAL's hash, never the thumbnail's, for/// [`video_poster_key`]'s reason exactly: whoever wants the tile has to be/// able to name it before anyone has encoded it. It sits under `photos/`, so/// [`media_kind_for`] answers [`MediaKind::Photo`] with no new arm and/// `PHOTO_TYPES` already carries `image/jpeg`.pub fn photo_thumb_key(file_id: &FileId, sha256: &str) -> String {    format!("{file_id}/photos/{sha256}{THUMB_SUFFIX}")}/// `{file_id}/photos/{sha256}.d1600.jpg` — the 1600 px rendition a detail/// view opens.////// A picture already at or under two megapixels has none: the original IS the/// display tier, and a second copy of it would be pure cost. The producer/// decides that; this function only spells the key.pub fn photo_display_key(file_id: &FileId, sha256: &str) -> String {    format!("{file_id}/photos/{sha256}{DISPLAY_SUFFIX}")}/// `{file_id}/videos/{sha256}.t256.jpg` — a film's grid thumbnail,/// derived from its poster still rather than from the film, so a film costs/// one decode.pub fn video_thumb_key(file_id: &FileId, sha256: &str) -> String {    format!("{file_id}/videos/{sha256}{THUMB_SUFFIX}")}/// `{file_id}/videos/{sha256}.d1600.jpg` — a film's display still.pub fn video_display_key(file_id: &FileId, sha256: &str) -> String {    format!("{file_id}/videos/{sha256}{DISPLAY_SUFFIX}")}/// The thumbnail and display keys a photo or video key owns, whether or not/// anybody has written them yet.////// Derived from the key rather than carried in a column on purpose: the/// renditions are content-addressed off the original's hash, so the key IS the/// answer, and a column would be a second place for it to be wrong. Naming an/// object that was never written is harmless — a delete of a missing object is/// a no-op, and the alternative is a leak.////// Answers nothing for a key that is not a photo's or a video's own object:/// a poster and the two renditions have no renditions of their own.pub fn derived_tier_keys(key: &str) -> Vec<String> {    let segments: Vec<&str> = key.split('/').collect();    if segments.len() != 3 || !has_renditions(segments[1], segments[2]) {        return Vec::new();    }    let file = segments[2];    let Some((stem, rest)) = file.split_once('.') else {        return Vec::new();    };    if stem.is_empty() {        return Vec::new();    }    // Already a derivative: `.poster.jpg`, `.t256.jpg`, `.d1600.jpg`. A    // rendition of a rendition is not a thing this store has.    if matches!(rest, "poster.jpg" | "t256.jpg" | "d1600.jpg") {        return Vec::new();    }    let folder = format!("{}/{}/{}", segments[0], segments[1], stem);    vec![        format!("{folder}{THUMB_SUFFIX}"),        format!("{folder}{DISPLAY_SUFFIX}"),    ]}/// Whether a key's folder and file carry the tier ladder: every photo and/// video, and a document that is a picture (`put_document` of a JPEG or a/// PNG, a list's own picture set over Cotton MCP: 5 Nov 2026) — its/// thumbnail and display rendition are drawn off its own key the same way./// A document of any other kind (a PDF, a statement) has none.fn has_renditions(folder: &str, file: &str) -> bool {    match folder {        "photos" | "videos" => true,        "documents" => file.split_once('.').is_some_and(|(_, rest)| {            matches!(rest, "t256.jpg" | "d1600.jpg") || DOCUMENT_PICTURES.contains(&rest.to_ascii_lowercase().as_str())        }),        _ => false,    }}/// The extensions of a document that is a picture ([`has_renditions`]).pub const DOCUMENT_PICTURES: &[&str] = &["jpg", "jpeg", "png", "gif", "webp", "heic"];/// The FAMILY a photo or video key belongs to — `{file}/{photos|videos}/{stem}.`/// — which every key of the same content shares: the original, its poster,/// and the two renditions [`derived_tier_keys`] spells.////// The question an unlink asks before it takes a rendition: renditions are/// named off the digest, not off the original's whole key, so a second key/// with the same digest (`{sha}.heic` beside `{sha}.jpg`) owns the same/// thumbnail, and taking it for one would take it from the other. `None` for/// every key that has no renditions to share — a document, a meeting, an/// avatar.pub fn rendition_family(key: &str) -> Option<String> {    let segments: Vec<&str> = key.split('/').collect();    if segments.len() != 3 || !has_renditions(segments[1], segments[2]) {        return None;    }    let (stem, _) = segments[2].split_once('.')?;    if stem.is_empty() {        return None;    }    Some(format!("{}/{}/{stem}.", segments[0], segments[1]))}/// Whether `key` is a RENDITION — a thumbnail or display copy a producer/// derived from an original, which no record names by itself.pub fn is_derived_rendition(key: &str) -> bool {    rendition_family(key).is_some()        && (key.ends_with(THUMB_SUFFIX) || key.ends_with(DISPLAY_SUFFIX))}/// The refusal `code` an upload of DEAD bytes gets (slice 7) — spelled once/// for the server that refuses it and the device that keeps the entry and/// asks again after its next exchange rather than giving up on it.pub const DEAD_KEY_REFUSAL_CODE: &str = "media_erased";/// WHICH RENDITION a key names, read off the key itself.////// The ledger's `_media.tier` has to be filled in by whoever files the bytes,/// and every caller that files them already has the key — so the answer comes/// from HERE rather than from each of them spelling `.t256.jpg` again. Keys are/// this module's and nowhere else's (AGENTS.md), and a suffix compared in/// `cotton-ffi` would be a second spelling of one.////// `None` is a real state and the callers must keep it one: a document, a/// meeting's audio, an avatar and a film's POSTER have no tier ladder at all,/// and a row whose tier is `None` is one the budgeted cache may not reason/// about — never one it may read as [`Tier::Original`] (see/// `cotton_store::media_ledger::MediaRow::tier`).pub fn rendition_of(key: &str) -> Option<Tier> {    // A conversation's picture has a thumbnail and nothing else on the    // ladder; the picture itself stays `None`, a chat's file as it was.    if message_picture_of_thumb(key).is_some() {        return Some(Tier::Thumb);    }    let segments: Vec<&str> = key.split('/').collect();    if segments.len() != 3 || !has_renditions(segments[1], segments[2]) {        return None;    }    let (stem, rest) = segments[2].split_once('.')?;    if stem.is_empty() {        return None;    }    match rest {        "t256.jpg" => Some(Tier::Thumb),        "d1600.jpg" => Some(Tier::Display),        // A poster still is not a rung of the ladder: it is what a film's grid        // tile draws, it is tiny, and it is the thing the thumbnail is derived        // FROM. Naming it a tier would make it evictable.        "poster.jpg" => None,        // A document that is a picture keeps its renditions, but the file        // itself stays off the ladder, a document as it always was.        _ if segments[1] == "documents" => None,        _ => Some(Tier::Original),    }}/// The 256 px thumbnail a RENDERER should prefer for this key, if this key is/// one a thumbnail is ever made for.////// The read side of [`photo_thumb_key`] / [`video_thumb_key`], and it exists/// because a tile is handed ONE key and has to resolve the tier itself: a/// photograph's own object, or — for a film — its POSTER, which is what/// `cotton_videos.poster_key` puts in front of every grid tile. Both answer the/// same thumbnail, because both are named off the same digest. A picture that/// arrived in a conversation answers [`message_thumb_key_for`]'s.////// `None` for everything else, and each `None` is a real state rather than a/// gap: a document, a meeting's audio and an avatar have no thumbnail tier at/// all, and a thumbnail or a display rendition has no rendition of its own.////// Derived rather than carried in a column for [`derived_tier_keys`]'s reason:/// the renditions are content-addressed off the original's hash, so the key IS/// the answer.pub fn thumb_key_for(key: &str) -> Option<String> {    if let Some(thumb) = message_thumb_key_for(key) {        return Some(thumb);    }    let segments: Vec<&str> = key.split('/').collect();    if segments.len() != 3 || !has_renditions(segments[1], segments[2]) {        return None;    }    let (stem, rest) = segments[2].split_once('.')?;    if stem.is_empty() || matches!(rest, "t256.jpg" | "d1600.jpg") {        return None;    }    Some(format!(        "{}/{}/{stem}{THUMB_SUFFIX}",        segments[0], segments[1]    ))}/// The 1600 px display rendition a DETAIL VIEW should prefer for this key,/// if this key is one a display rendition is ever made for.////// [`thumb_key_for`]'s twin for the rung above it, and it exists for the/// hero's reason: a full-width print asked `read.mediaPath` with the tile's/// own order and was handed the 256 px thumbnail enlarged to the screen —/// the crate's `largest` tier walks original → display → thumb, and this is/// how it names the middle rung off the key alone. A film's poster answers its/// film's display still, for the same reason it answers the film's thumbnail.////// `None` for everything else, and each `None` is a real state: a document,/// a meeting's audio and an avatar have no display tier, and a rendition has/// no rendition of its own. Whether the object was ever WRITTEN is not this/// function's question — a picture under two megapixels has none, and the/// caller finds that out by asking the ledger.pub fn display_key_for(key: &str) -> Option<String> {    let segments: Vec<&str> = key.split('/').collect();    if segments.len() != 3 || !has_renditions(segments[1], segments[2]) {        return None;    }    let (stem, rest) = segments[2].split_once('.')?;    if stem.is_empty() || matches!(rest, "t256.jpg" | "d1600.jpg") {        return None;    }    Some(format!(        "{}/{}/{stem}{DISPLAY_SUFFIX}",        segments[0], segments[1]    ))}// ─────────────────────────────────────────────────────────────────────────────// The wall.// ─────────────────────────────────────────────────────────────────────────────/// A key is well-formed when every one of these holds. Split out from the/// assert so callers that want a boolean do not have to handle an error.pub fn is_key_in_workspace(key: Option<&str>, file_id: &FileId) -> bool {    is_key_under(js_trim(key.unwrap_or("")), file_id.as_str())}/// The same wall, against the folder a ROW's own `workspace_id` column names.////// A message or an email row carries the file it was written into, and its/// key is good only under THAT file's prefix — not the prefix of whichever/// file the reader holds open, which under several databases is the file the/// call resolved to and need not be the row's.pub fn is_key_in_row_file(key: Option<&str>, row_workspace_id: &str) -> bool {    is_key_under(js_trim(key.unwrap_or("")), row_workspace_id)}/// The wall's rules, against a folder given as a string — private, so the/// only public ways in are a `FileId` ([`is_key_in_workspace`]), a row's own/// stored file ([`is_key_in_row_file`]) or a key's own first segment/// ([`media_kind_of_verified_key`]).fn is_key_under(trimmed: &str, folder: &str) -> bool {    if trimmed.is_empty() || utf16_len(trimmed) > MAX_KEY_LENGTH {        return false;    }    if folder.is_empty() {        return false;    }    if !trimmed.starts_with(&format!("{folder}/")) {        return false;    }    if trimmed.contains("..") {        return false;    }    // Control characters, whitespace and backslashes never appear in a key    // this module builds; a key carrying one arrived from somewhere else.    for ch in trimmed.chars() {        if is_js_whitespace(ch) || ch == '\\' {            return false;        }    }    for unit in trimmed.encode_utf16() {        if unit < 32 || unit == 127 {            return false;        }    }    // The first segment is the workspace; a trailing or doubled slash leaves    // an empty one, which S3 accepts and no reader of this codebase expects.    trimmed.split('/').all(|segment| !segment.is_empty())}/// The one refusal every media route makes: a key that does not sit inside/// this workspace's own folder.////// `storage_path`, `decrypted_path`, `file_path` and `segments[].path` are/// SYNCED, DEVICE-WRITABLE columns: a poisoned op can point one at any object/// in the store, and the server signs with a credential that spans all of it./// This check is the only thing standing where bucket RLS used to.////// Traversal is refused, never normalised: a caller that meant `a/../b` can/// say `b`, and one that did not mean it is better off with an error.////// Returns the TRIMMED key — the TypeScript's `fail` callback becomes an/// `Err` carrying the same sentence, so the caller decides the status code.pub fn assert_key_in_workspace<'a>(    key: Option<&'a str>,    file_id: &FileId,) -> Result<&'a str, MediaKeyError> {    let trimmed = js_trim(key.unwrap_or(""));    if !is_key_in_workspace(Some(trimmed), file_id) {        return Err(MediaKeyError::OutsideWorkspace);    }    Ok(trimmed)}/// Why a key was refused. The messages are the TypeScript's, verbatim, because/// they reach a person through an error body.#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]pub enum MediaKeyError {    #[error("that file path does not sit inside your own workspace folder")]    OutsideWorkspace,    #[error("that file path names no object")]    NamesNoObject,}/// What kind of media a key names, read from its shape.////// Total over well-formed keys, and deliberately so: the server picks a size/// cap and a content-type list from this answer, so "I could not tell" has to/// be a refusal rather than a default. A key outside the workspace never/// reaches a kind at all.pub fn media_kind_for(key: &str, file_id: &FileId) -> Result<MediaKind, MediaKeyError> {    kind_of_shape(assert_key_in_workspace(Some(key), file_id)?)}/// What kind of media a key names, for a key whose file was proven some other/// way — a valid signature over the key itself, which the object routes check/// first. The key is held to every rule of the wall against its OWN first/// segment, so a malformed key is still refused; but nothing here says which/// file it belongs to, and no `FileId` is made from that segment.pub fn media_kind_of_verified_key(key: &str) -> Result<MediaKind, MediaKeyError> {    let trimmed = js_trim(key);    let folder = trimmed.split('/').next().unwrap_or_default();    if !is_key_under(trimmed, folder) {        return Err(MediaKeyError::OutsideWorkspace);    }    kind_of_shape(trimmed)}/// The kind a well-formed key's folders spell.fn kind_of_shape(trimmed: &str) -> Result<MediaKind, MediaKeyError> {    let segments: Vec<&str> = trimmed.split('/').collect();    if segments.len() < 2 {        return Err(MediaKeyError::NamesNoObject);    }    // Reserved folders, read before the shape rules below. Each carries a very    // different allowance from a document, so none may fall through to it. A    // document folder is a uuid, so no reserved name can collide with one.    Ok(match segments[1] {        "meetings" => MediaKind::Meeting,        "messages" => MediaKind::Message,        "people" => MediaKind::Avatar,        // The folder a non-owner can reach: a client opening a share uploads a        // feedback capture under it. 25 MB of image, never 100 MB of anything.        "walkthroughs" => MediaKind::Walkthrough,        "session-messages" => MediaKind::Session,        // Schema v31. A video's POSTER lives under `videos/` too and is        // deliberately read as kind video: it is that video's thumbnail.        "photos" => MediaKind::Photo,        "videos" => MediaKind::Video,        // Schema v17. Read HERE, before the shape rules, for the reason every        // reserved name is: a repository's objects are four levels deep        // (`repos/{repo_id}/bundles/{sha256}.bundle`), so the fall-through        // would read one as a DOCUMENT and the server would sign a 100 MB PUT        // for a 371 MB bundle and refuse a `application/x-git-bundle` it has        // no entry for.        "repos" => MediaKind::Repo,        // A book's file (`book_key`): flat under `books/`, read here before        // the fall-through, which would take `books/<sha>.epub` for a document        // and sign it a 100 MB ceiling and no EPUB type.        "books" => MediaKind::Book,        // A song's file (`song_key`): flat under `music/`, read here for the        // same reason — the fall-through would sign it a document's 100 MB        // and no audio type.        "music" => MediaKind::Song,        // A film's folder (`film_whole_key`, `film_source_key`, the Mac's        // HLS folder): read here for the same reason — the fall-through        // would sign a film a document's 100 MB and no video type.        "films" => MediaKind::Film,        // `{file_id}/{token}-{name}` — a statement is the only key with        // its object directly in the workspace folder.        _ if segments.len() == 2 => MediaKind::Statement,        _ => MediaKind::Document,    })}/// A photo or video row, as much of it as the object accounting needs.////// The TypeScript interface carries the poster under both spellings/// (`posterKey ?? poster_key`) because either half of the codebase may hand/// one over; a Rust caller resolves that at its own boundary and passes one/// `Option`.#[derive(Debug, Clone, Default)]pub struct MediaObjectRow {    pub key: String,    /// A video's still frame. A photo has none.    pub poster_key: Option<String>,}/// EVERY object one photo or video row owns — its own, its poster, and every/// other copy of the same bytes its sightings point at.////// The one answer to "what does deleting this row have to reclaim", and to/// "what is this row actually costing in the store". Two readers computing/// that separately is how a delete frees a quarter of the space it promised./// Since schema v39 the other copies are the `key` of each/// `cotton_media_sightings` row — the caller reads those and hands them over./// Deduplicated and order-stable: `key` first, because it is the one every/// other surface shows, and the derived tiers ([`derived_tier_keys`]) last —/// a photo whose thumbnail outlived it is a leak nobody would ever find.pub fn media_object_keys(row: &MediaObjectRow, sighting_keys: &[String]) -> Vec<String> {    let mut seen: BTreeSet<&str> = BTreeSet::new();    let mut out: Vec<String> = Vec::new();    let poster = row.poster_key.as_deref();    // Every copy of the bytes owns its own renditions, so the derivatives are    // taken per candidate rather than off `key` alone — a forwarded sighting    // in another folder was tiered there too.    let named: Vec<String> = std::iter::once(row.key.as_str())        .chain(sighting_keys.iter().map(String::as_str))        .chain(poster)        .map(str::to_string)        .collect();    let derived: Vec<String> = named        .iter()        .flat_map(|candidate| derived_tier_keys(candidate))        .collect();    for candidate in named.iter().map(String::as_str).chain(derived.iter().map(String::as_str)) {        if candidate.is_empty() {            continue;        }        if seen.insert(candidate) {            out.push(candidate.to_string());        }    }    out}/// EVERY object one release row owns — the keys inside its `assets_json`.////// [`media_object_keys`]'s argument, for the one other row that points at more/// than one object: deleting a release has to reclaim its assets, and a second/// reader spelling out "walk the array and read `key`" is how a delete frees/// none of what it promised. Deduplicated and order-stable, like/// `media_object_keys`.////// Unparsable JSON, a non-array, an entry that is not an object and an entry/// whose `key` is absent or blank all answer NOTHING for that entry rather/// than an error: this is asked on the delete path, and a release whose assets/// column somebody hand-edited is still a release whose OTHER assets must be/// reclaimed. There are no derived tiers — [`derived_tier_keys`] gates on/// `photos|videos`, so a repository's objects have no rendition ladder at all.////// **AND ONLY THIS REPOSITORY'S OWN OBJECTS COME BACK.** `assets_json` is a/// SYNCED column any paired device can write, and the answer is a delete list:/// a key under another workspace or another repository would be a delete that/// reclaimed somebody else's bytes. So the answer is filtered against/// [`repo_media_prefix`] — the one spelling of "this belongs to that/// repository", which is what that function's own note promises.pub fn repo_release_asset_keys(    file_id: &FileId,    repo_id: &str,    assets_json: &str,) -> Vec<String> {    let prefix = repo_media_prefix(file_id, repo_id);    let Ok(parsed) = serde_json::from_str::<serde_json::Value>(assets_json) else {        return Vec::new();    };    let Some(assets) = parsed.as_array() else {        return Vec::new();    };    let mut seen: BTreeSet<String> = BTreeSet::new();    let mut out: Vec<String> = Vec::new();    for asset in assets {        let Some(key) = asset.get("key").and_then(serde_json::Value::as_str) else {            continue;        };        let key = js_trim(key);        if key.is_empty() || !key.starts_with(&prefix) {            continue;        }        if seen.insert(key.to_string()) {            out.push(key.to_string());        }    }    out}#[cfg(test)]#[path = "keys_tests.rs"]mod tests;