Cotton code
233 lines · 11.1 KB · RustRaw
//! The device's own thumbnail cache, as two questions about the file.//!//! A grid tile does not draw the original: a phone that does not hold a 4 MB//! HEIC draws a glyph, and decoding one at 120 points to find that out is the//! wrong trade twice over. So every device eagerly collects a 256 px thumbnail//! for every photo and every film, and the two questions that walk is built on//! live here://!//! - [`thumbs_wanted`] — which thumbnails this device does NOT have, newest//!   first. The work list, and the reason the sweep needs no stored cursor://!   a thumbnail that arrived stops being wanted, so a pass that was cut short//!   resumes by asking the same question again.//! - [`record_thumb`] — one arrived. A `_media` row at `tier = 'thumb'` with a//!   `local_path`, which is the "have it" mark [`thumbs_wanted`] reads back.//!//! **A thumbnail is NEVER a `_media` job.** The row is born `synced`, because//! it is: these bytes came DOWN from the server's own store and the drain's//! queue is for bytes going up. A row left `pending` would queue an upload of//! an object the server minted the copy from.//!//! **The key's SHAPE comes from the caller, never from this SQL.** Keys are//! `cotton_core::media::keys`'s and nowhere else's, and this crate does not//! depend on `cotton-core`; so the two halves of the key around the sha256 are//! passed in as a [`KeyShape`] the caller derived FROM the builder itself. A//! `'/photos/' || sha256 || '.t256.jpg'` written here would be a second//! spelling of a key, which is the one thing the keys module exists to prevent.//!//! No clock and no filesystem, like the rest of this crate: `now` arrives as an//! ISO-8601 string from the caller.use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::Result;/// What [`MediaRow::tier`](crate::media_ledger::MediaRow) carries for a/// thumbnail. Spelled once; the sweep, the eviction pass and the reader all/// compare against this.pub const THUMB_TIER: &str = "thumb";/// Every thumbnail this store writes is a JPEG.const THUMB_CONTENT_TYPE: &str = "image/jpeg";/// One kind's thumbnail key, split around the sha256 it is built from.////// Derived by the caller from the key BUILDER — build the key for a sentinel/// digest and split on it — so a change in `cotton_core::media::keys` reaches/// this query rather than leaving it quietly asking about keys nobody writes.#[derive(Debug, Clone, PartialEq, Eq)]pub struct KeyShape {    pub prefix: String,    pub suffix: String,}impl KeyShape {    pub fn new(prefix: impl Into<String>, suffix: impl Into<String>) -> KeyShape {        KeyShape {            prefix: prefix.into(),            suffix: suffix.into(),        }    }    /// The key for one digest — what the caller compares the query's answer    /// against, and what a test builds an expectation out of.    pub fn key(&self, sha256: &str) -> String {        format!("{}{sha256}{}", self.prefix, self.suffix)    }}/// One thumbnail the sweep still wants, and where it sits in the walk.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ThumbWanted {    pub key: String,    /// The SOURCE row's `taken_at` — the order the walk is in, and half of the    /// cursor that pages it.    pub taken_at: String,}/// The photos and films whose thumbnail is not on this device, NEWEST FIRST.////// Newest first because that is what a person opens: a library arriving on a/// second phone is scrolled from the top, and a sweep that filled the oldest/// first would spend an hour on pictures nobody is looking at.////// `after` pages WITHIN one pass. Across passes there is no cursor and none is/// wanted: a thumbnail that arrived is no longer wanted, so asking again from/// the top skips everything already fetched and picks up exactly where the last/// pass was cut off — while also catching a picture taken since.////// **A STATUS IS NEVER ON A PHONE'S LIST** (architect, 12 Oct 2026: "statuses/// are excluded from the sweep entirely — never a thumbnail, never an/// original"). `statuses` is the folder a status's bytes are kept under, given/// by a PHONE and by nobody else; `None` is a Mac, whose list is every picture/// it knows. With it, a photo or a film is left out when a status is the only/// place it was ever seen: its own key, or one of its sightings, sits under/// that folder, and NO sighting sits anywhere else. The second half is the/// whole point of the ruling's other sentence — "a people-media sighting does,/// whatever its age": a picture somebody also sent in a chat is a chat/// picture, and one sighting outside the folder keeps it, however old.////// The folder is a KEY PREFIX and, like the two shapes, the caller's to spell/// (`cotton_core::media::keys::message_media_prefix`); it is compared with/// `substr`, never `LIKE`, so nothing in a file's id is read as a wildcard.pub fn thumbs_wanted(    db: &Driver,    workspace_id: &str,    photo: &KeyShape,    video: &KeyShape,    statuses: Option<&str>,    after: Option<&ThumbWanted>,    limit: i64,) -> Result<Vec<ThumbWanted>> {    let (cursor_at, cursor_key) = match after {        Some(cursor) => (            SqlValue::Text(cursor.taken_at.clone()),            SqlValue::Text(cursor.key.clone()),        ),        None => (SqlValue::Null, SqlValue::Null),    };    // `?1`/`?2` are the photo key's halves, `?3`/`?4` the film's, `?5` the    // workspace, `?6`/`?7` the cursor, `?8` the page and `?9` the statuses    // folder (NULL on a Mac, which switches the last clause of each arm off).    // Numbered rather than repeated so the two arms of the UNION cannot drift    // apart.    let sql = "\        SELECT ?1 || sha256 || ?2 AS key, taken_at FROM cotton_photos\n\          WHERE workspace_id = ?5\n\            AND (?6 IS NULL OR taken_at < ?6 OR (taken_at = ?6 AND (?1 || sha256 || ?2) < ?7))\n\            AND NOT EXISTS (SELECT 1 FROM _media m\n\                             WHERE m.key = ?1 || cotton_photos.sha256 || ?2\n\                               AND m.tier = 'thumb' AND m.local_path IS NOT NULL)\n\            AND (?9 IS NULL OR NOT (\n\                  (substr(cotton_photos.key, 1, length(?9)) = ?9\n\                   OR EXISTS (SELECT 1 FROM cotton_media_sightings s\n\                               WHERE s.workspace_id = ?5 AND s.record_id = cotton_photos.id\n\                                 AND substr(s.key, 1, length(?9)) = ?9))\n\                  AND NOT EXISTS (SELECT 1 FROM cotton_media_sightings s\n\                                   WHERE s.workspace_id = ?5 AND s.record_id = cotton_photos.id\n\                                     AND substr(s.key, 1, length(?9)) <> ?9)))\n\        UNION ALL\n\        SELECT ?3 || sha256 || ?4 AS key, taken_at FROM cotton_videos\n\          WHERE workspace_id = ?5\n\            AND (?6 IS NULL OR taken_at < ?6 OR (taken_at = ?6 AND (?3 || sha256 || ?4) < ?7))\n\            AND NOT EXISTS (SELECT 1 FROM _media m\n\                             WHERE m.key = ?3 || cotton_videos.sha256 || ?4\n\                               AND m.tier = 'thumb' AND m.local_path IS NOT NULL)\n\            AND (?9 IS NULL OR NOT (\n\                  (substr(cotton_videos.key, 1, length(?9)) = ?9\n\                   OR EXISTS (SELECT 1 FROM cotton_media_sightings s\n\                               WHERE s.workspace_id = ?5 AND s.record_id = cotton_videos.id\n\                                 AND substr(s.key, 1, length(?9)) = ?9))\n\                  AND NOT EXISTS (SELECT 1 FROM cotton_media_sightings s\n\                                   WHERE s.workspace_id = ?5 AND s.record_id = cotton_videos.id\n\                                     AND substr(s.key, 1, length(?9)) <> ?9)))\n\        ORDER BY taken_at DESC, key DESC\n\        LIMIT ?8";    Ok(db        .all(            sql,            &[                SqlValue::Text(photo.prefix.clone()),                SqlValue::Text(photo.suffix.clone()),                SqlValue::Text(video.prefix.clone()),                SqlValue::Text(video.suffix.clone()),                SqlValue::Text(workspace_id.to_string()),                cursor_at,                cursor_key,                SqlValue::Integer(limit),                statuses.map_or(SqlValue::Null, |folder| SqlValue::Text(folder.to_string())),            ],        )?        .iter()        .map(|row| ThumbWanted {            key: row.text("key").unwrap_or_default().to_string(),            taken_at: row.text("taken_at").unwrap_or_default().to_string(),        })        .collect())}/// A thumbnail that arrived and is now on this device's disk.////// `state` is `synced` and never `pending`: these bytes came DOWN out of the/// server's own store, and `pending` is the drain's queue for bytes going UP./// Re-recording the same key is a restatement — the file may have been written/// again after a cache wipe — so it keeps `created_at` and moves only what/// changed.pub struct ThumbArrived<'a> {    pub key: &'a str,    pub workspace_id: &'a str,    /// The THUMBNAIL's own digest, not the picture's. The key names the    /// picture's; `_media.sha256` is a content address of the file at    /// `local_path`, and answering the original's here would make    /// [`crate::media_ledger::media_by_sha256`] hand a capture the thumbnail.    pub sha256: &'a str,    pub size_bytes: i64,    pub local_path: &'a str,    pub now: &'a str,}pub fn record_thumb(db: &Driver, arrived: &ThumbArrived<'_>) -> Result<()> {    db.run(        "INSERT INTO _media\n           (key, workspace_id, sha256, content_type, size_bytes, local_path, state,\n            attempts, created_at, updated_at, tier)\n         VALUES (?, ?, ?, ?, ?, ?, 'synced', 0, ?, ?, ?)\n         ON CONFLICT(key) DO UPDATE SET\n           sha256 = excluded.sha256,\n           size_bytes = excluded.size_bytes,\n           local_path = excluded.local_path,\n           state = 'synced',\n           tier = excluded.tier,\n           last_error = NULL,\n           next_attempt_at = NULL,\n           updated_at = excluded.updated_at",        &[            SqlValue::Text(arrived.key.to_string()),            SqlValue::Text(arrived.workspace_id.to_string()),            SqlValue::Text(arrived.sha256.to_string()),            SqlValue::Text(THUMB_CONTENT_TYPE.to_string()),            SqlValue::Integer(arrived.size_bytes),            SqlValue::Text(arrived.local_path.to_string()),            SqlValue::Text(arrived.now.to_string()),            SqlValue::Text(arrived.now.to_string()),            SqlValue::Text(THUMB_TIER.to_string()),        ],    )?;    Ok(())}/// How many thumbnails this device holds — the one number a storage screen and/// a test both want, and the anti-vacuity check for a sweep that claims it did/// something.pub fn local_thumb_count(db: &Driver, workspace_id: &str) -> Result<i64> {    Ok(db        .get(            "SELECT COUNT(*) AS n FROM _media\n              WHERE workspace_id = ? AND tier = 'thumb' AND local_path IS NOT NULL",            &[SqlValue::Text(workspace_id.to_string())],        )?        .and_then(|row| row.int("n"))        .unwrap_or(0))}#[cfg(test)]#[path = "media_thumbs_tests.rs"]mod tests;