Cotton code
738 lines · 32.9 KB · RustRaw
//! The `_media` ledger — the bookkeeping half of offline-first bytes.//!//! The rule: bytes are part of the life, so the phone holds them permanently//! and R2 is the backup. A capture copies its bytes into the media store,//! writes its domain row locally, and leaves a `pending` row here. Nothing on a//! capture path waits for the network; this table is what remembers what still//! has to go.//!//! Everything here is PURE bookkeeping over the file: no filesystem, no//! network, and — deliberately — no clock. Every function that stamps a row//! takes `now` as an ISO-8601 string from its caller, because the app, the//! tests and a replay all need to agree on when something happened, and a//! `new Date()` buried in a helper makes that impossible to control.use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::media_holdings::Tier;use crate::protocol::js;/// Where a file is in its trip to R2.////// - `pending` — bytes are local and not yet in R2. The uploader's queue./// - `synced` — bytes are in R2 (and on this device too if `local_path` is set)./// - `failed` — the server refused FINALLY (413 too large, 415 wrong type, a///   forbidden key). Surfaced to the person, never retried on its own: a retry///   of something the server will always refuse is a loop, not a recovery./// - `delete_pending` — the owner deleted the row, the local file is already///   gone, and the R2 object is swept on the next drain.////// A STRING rather than an enum, deliberately: `_media.state` has no CHECK, the/// app writes it, and a value this build has never heard of must round-trip/// rather than refuse to be read.pub type MediaState = String;/// One row of `_media`, in the app's shape.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MediaRow {    /// The R2 object key, `{workspace_id}/…`.    pub key: String,    pub workspace_id: String,    pub sha256: String,    pub content_type: String,    pub size_bytes: i64,    /// Absolute path in the media store; `None` = these bytes are not on this    /// device.    pub local_path: Option<String>,    pub state: MediaState,    /// The trigger to run once the bytes land. The server's workers sweep    /// anyway, so a trigger only shortens the wait — it is never the thing that    /// makes the work happen.    pub after: Option<String>,    /// The domain row the trigger names (a document id, a meeting id).    pub after_row_id: Option<String>,    pub attempts: i64,    pub last_error: Option<String>,    /// Backoff gate; `None` = due now.    pub next_attempt_at: Option<String>,    /// WHICH RENDITION these bytes are — the captured original, the 1600 px    /// display rendition or the 256 px thumbnail.    ///    /// `None` is a real state and not a gap: every row written before schema    /// v12 has one, and so does every object that HAS no tier ladder at all —    /// a document, a meeting's audio, an avatar. A reader that needs a tier    /// must treat `None` as "this is not a rendition I may reason about",    /// never as `Original`, or the first eviction pass would start on the    /// oldest rows in the file.    pub tier: Option<Tier>,    /// THIS DEVICE took these bytes — the camera, the share sheet, the picker.    ///    /// Never evictable, full stop (AGENTS.md: "Bytes are offline-first — the    /// phone holds them, permanently"). Written by    /// `cotton_ffi::phone::media::write_media` and by nothing else, and sticky    /// once true: a re-enqueue of the same key can set it, never clear it.    pub captured_here: bool,    /// THE PERSON said keep these bytes on this device. Never evicted.    ///    /// Its own column rather than a tier, because it is orthogonal to one: a    /// pinned row is still an original or a display rendition, and the budget    /// asks both questions separately.    pub pinned: bool,    /// When a DETAIL VIEW last opened these bytes — the order the budgeted    /// cache evicts in.    ///    /// `None` is a file nobody on this device has ever opened, and it goes    /// FIRST: it is further from being wanted than one opened a year ago.    /// Written by `media.viewed` and by `media.ensure`, and deliberately NOT by    /// `read.mediaPath` — a grid asks that two hundred times as a finger moves,    /// and a stamp from there would make "least recently viewed" mean "least    /// recently scrolled past".    pub last_viewed_at: Option<String>,    /// THE WORD the last refusal or wait was filed under ([`codes`]): what a    /// screen acts on, where `last_error` is the object's sentence. `None` is    /// a row nothing refused, or one only a passing failure touched.    pub last_code: Option<String>,    /// Under what rule these bytes may go up: `any` (the default, and what    /// every app's uploads have always done) or `wifi`. A word this build does    /// not know reads as stricter than `any`, never looser.    pub network: String,    /// Who asked for these bytes to go up — the app or the act (`albums.keep`)    /// that queued them; `None` is a file queued before anyone said.    pub asked_by: Option<String>,    /// Where else these bytes live on this device: `photos` is a copy of an    /// original the phone's Photos library keeps. `None` is a file Cotton    /// alone holds.    pub source: Option<String>,    pub created_at: String,    pub updated_at: String,}/// The words a refusal or a wait is filed under, in `_media.last_code`.////// A REFUSAL (`state = 'failed'`) is the person's to act on and never retried/// on its own: [`codes::TOO_BIG`], [`codes::COTTON_FULL`],/// [`codes::FILE_GONE`], [`codes::REFUSED`]. A WAIT stays `pending` and goes/// by itself once the reason is gone: [`codes::SPACE_FULL`] (room is made),/// [`codes::DEAD_KEY`] (the next exchange). A passing failure (no network, a/// 5xx) files no word: it is a retry, nothing more.pub mod codes {    /// The object takes no file this large (413 `too_big`).    pub const TOO_BIG: &str = "too_big";    /// The object's media is at its cap and will refuse again (413 `object_full`).    pub const COTTON_FULL: &str = "cotton_full";    /// The file is not on this device any more: nothing here can send it.    pub const FILE_GONE: &str = "file_gone";    /// Any other refusal the object or this device will repeat: a key or a    /// type it will not take.    pub const REFUSED: &str = "refused";    /// The person's space is full: waits for room, never given up on.    pub const SPACE_FULL: &str = "space_full";    /// The object holds an erase naming the key: waits for the next exchange.    pub const DEAD_KEY: &str = "dead_key";}/// What a caller hands [`enqueue_media`]: the file, not the bookkeeping.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MediaEnqueueInput {    pub key: String,    pub workspace_id: String,    pub sha256: String,    pub content_type: String,    pub size_bytes: i64,    pub local_path: Option<String>,    /// `None` defaults to `pending`. `synced` is for a row the hydrator just    /// downloaded.    pub state: Option<MediaState>,    pub after: Option<String>,    pub after_row_id: Option<String>,    /// Which rendition these bytes are; see [`MediaRow::tier`]. `None` leaves    /// an existing row's tier alone.    pub tier: Option<Tier>,    /// `true` only from a capture on THIS device; see    /// [`MediaRow::captured_here`]. `false` never clears a `true` already on    /// the row.    pub captured_here: bool,    /// ISO-8601 UTC, from the caller.    pub now: String,}/// The counts a surface shows: "N photos will back up in the background".#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct MediaCounts {    pub pending: i64,    /// The bytes the `pending` rows still have to send.    pub pending_bytes: i64,    pub synced: i64,    pub failed: i64,    pub delete_pending: i64,}const SELECT_COLUMNS: &str = "key, workspace_id, sha256, content_type, size_bytes, local_path, state, after, after_row_id, attempts, last_error, next_attempt_at, tier, captured_here, pinned, last_viewed_at, last_code, network, asked_by, source, created_at, updated_at";fn to_row(row: &crate::driver::Row) -> MediaRow {    MediaRow {        key: row.text("key").unwrap_or_default().to_string(),        workspace_id: row.text("workspace_id").unwrap_or_default().to_string(),        sha256: row.text("sha256").unwrap_or_default().to_string(),        content_type: row.text("content_type").unwrap_or_default().to_string(),        size_bytes: row.int("size_bytes").unwrap_or(0),        local_path: row.text("local_path").map(str::to_string),        state: row.text("state").unwrap_or_default().to_string(),        after: row.text("after").map(str::to_string),        after_row_id: row.text("after_row_id").map(str::to_string),        attempts: row.int("attempts").unwrap_or(0),        last_error: row.text("last_error").map(str::to_string),        next_attempt_at: row.text("next_attempt_at").map(str::to_string),        // `Tier::parse` answers `None` for a word this build does not know,        // which is the same `None` a pre-v12 row carries — deliberately. A row        // whose tier this build cannot name is a row it must not act on.        tier: row.text("tier").and_then(Tier::parse),        captured_here: row.int("captured_here").unwrap_or(0) != 0,        pinned: row.int("pinned").unwrap_or(0) != 0,        last_viewed_at: row.text("last_viewed_at").map(str::to_string),        last_code: row.text("last_code").map(str::to_string),        // A file an earlier build wrote has no column: what it did then, any network.        network: row.text("network").unwrap_or("any").to_string(),        asked_by: row.text("asked_by").map(str::to_string),        source: row.text("source").map(str::to_string),        created_at: row.text("created_at").unwrap_or_default().to_string(),        updated_at: row.text("updated_at").unwrap_or_default().to_string(),    }}fn nullable(value: Option<&String>) -> SqlValue {    value.map_or(SqlValue::Null, |text| SqlValue::Text(text.clone()))}fn tier_value(tier: Option<Tier>) -> SqlValue {    tier.map_or(SqlValue::Null, |tier| {        SqlValue::Text(tier.as_str().to_string())    })}/// The backoff ceiling, in seconds. Five minutes is long enough that a phone/// with no signal is not burning battery on the radio, and short enough that/// the moment it walks back into range the queue moves without the person/// having to reopen anything.pub const MEDIA_BACKOFF_CEILING_SECONDS: i64 = 300;/// `min(2^attempts, 300)` seconds after `now`, where `attempts` is the count/// INCLUDING the attempt just recorded — so the first failure waits 2s, the/// second 4s, and everything from the ninth on waits the 300s ceiling.pub fn media_backoff_at(now: &str, attempts: i64) -> Result<String> {    let base = js::parse_date_ms(now).ok_or_else(|| {        StoreError::encode(format!(            "mediaLedger: `now` must be an ISO-8601 timestamp, got {}",            js::json_stringify(&serde_json::Value::String(now.to_string()))        ))    })?;    // `attempts` is clamped before the exponent so a row that has been failing    // for a very long time cannot turn 2^attempts into infinity.    let seconds = (1i64 << attempts.clamp(0, 31) as u32).min(MEDIA_BACKOFF_CEILING_SECONDS);    js::to_iso_string(base + seconds * 1000).ok_or_else(|| {        StoreError::encode(format!(            "mediaLedger: `now` must be an ISO-8601 timestamp, got {}",            js::json_stringify(&serde_json::Value::String(now.to_string()))        ))    })}/// Record a file the phone now holds.////// Idempotent by construction: the key is a content address, so the same key/// always means the same bytes and a second enqueue is a re-statement, not a/// new job. On a key that already exists the row KEEPS its state and its/// `created_at` — a re-import must not drag a `synced` row back to `pending`/// and re-upload bytes R2 already has — and only learns what the caller can/// legitimately add: where the bytes are now, and the trigger to run.////// The one exception is `delete_pending`: those bytes were on their way OUT,/// and a caller enqueueing the key again means they are back. The row revives/// into the incoming state with its attempt history cleared.pub fn enqueue_media(db: &Driver, input: &MediaEnqueueInput) -> Result<MediaRow> {    let state = input.state.clone().unwrap_or_else(|| "pending".to_string());    db.transaction(|db| {        let existing = media_by_key(db, &input.key)?;        let Some(existing) = existing else {            db.run(                "INSERT INTO _media\n                   (key, workspace_id, sha256, content_type, size_bytes, local_path, state,\n                    after, after_row_id, attempts, last_error, next_attempt_at, tier, captured_here,\n                    created_at, updated_at)\n                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, NULL, ?, ?, ?, ?)",                &[                    SqlValue::Text(input.key.clone()),                    SqlValue::Text(input.workspace_id.clone()),                    SqlValue::Text(input.sha256.clone()),                    SqlValue::Text(input.content_type.clone()),                    SqlValue::Integer(input.size_bytes),                    nullable(input.local_path.as_ref()),                    SqlValue::Text(state.clone()),                    nullable(input.after.as_ref()),                    nullable(input.after_row_id.as_ref()),                    tier_value(input.tier),                    SqlValue::Integer(i64::from(input.captured_here)),                    SqlValue::Text(input.now.clone()),                    SqlValue::Text(input.now.clone()),                ],            )?;            return required(db, &input.key);        };        let revived = existing.state == "delete_pending";        // `tier` is COALESCE'd like `local_path` — a re-enqueue that says        // nothing about the tier must not blank one the file already knows —        // and `captured_here` is OR'd rather than assigned: once this phone        // took these bytes that is a fact about the past, and an import or a        // hydrate restating the same key must never turn a photograph this        // person shot into something the budget may delete.        db.run(            "UPDATE _media SET\n               local_path = COALESCE(?, local_path),\n               after = COALESCE(?, after),\n               after_row_id = COALESCE(?, after_row_id),\n               tier = COALESCE(?, tier),\n               captured_here = MAX(captured_here, ?),\n               state = ?,\n               attempts = ?,\n               last_error = ?,\n               next_attempt_at = ?,\n               updated_at = ?\n             WHERE key = ?",            &[                nullable(input.local_path.as_ref()),                nullable(input.after.as_ref()),                nullable(input.after_row_id.as_ref()),                tier_value(input.tier),                SqlValue::Integer(i64::from(input.captured_here)),                SqlValue::Text(if revived {                    state.clone()                } else {                    existing.state.clone()                }),                SqlValue::Integer(if revived { 0 } else { existing.attempts }),                if revived {                    SqlValue::Null                } else {                    nullable(existing.last_error.as_ref())                },                if revived {                    SqlValue::Null                } else {                    nullable(existing.next_attempt_at.as_ref())                },                SqlValue::Text(input.now.clone()),                SqlValue::Text(input.key.clone()),            ],        )?;        required(db, &input.key)    })}/// The next `pending` rows whose backoff has expired, oldest first.////// READ-ONLY, despite the name: it hands the queue what to work on and nothing/// else. Marking the attempt is [`record_media_attempt`], and it belongs to the/// app, which is the half that knows whether the upload actually failed.////// Ordered by `created_at` so the queue is FIFO, with `key` as the tiebreaker,/// because a whole import batch shares a timestamp and an order that varies/// between two calls makes a stuck row hard to see.pub fn claim_due_media(db: &Driver, limit: i64, now: &str) -> Result<Vec<MediaRow>> {    claim_due_media_on(db, limit, now, true)}/// [`claim_due_media`], under the network rule (MEDIA DRAIN 1 item 2): off Wi-Fi (`wifi` false) a file queued for/// Wi-Fi only is not due; one queued for any network always is.pub fn claim_due_media_on(db: &Driver, limit: i64, now: &str, wifi: bool) -> Result<Vec<MediaRow>> {    Ok(db        .all(            &format!(                "SELECT {SELECT_COLUMNS} FROM _media\n                  WHERE state = 'pending' AND (next_attempt_at IS NULL OR next_attempt_at <= ?)\n                    AND (? OR network <> 'wifi')\n                  ORDER BY created_at, key\n                  LIMIT ?"            ),            &[SqlValue::Text(now.to_string()), SqlValue::Integer(i64::from(wifi)), SqlValue::Integer(limit)],        )?        .iter()        .map(to_row)        .collect())}/// Every row of the ledger, oldest first, read by column name so a file an/// earlier build wrote (a `_media` without a column added since) reads too:/// a column it lacks reads as that column's absence (`None`, `false`, 0).pub fn every_media_row(db: &Driver) -> Result<Vec<MediaRow>> {    Ok(db.all("SELECT * FROM _media ORDER BY created_at, key", &[])?.iter().map(to_row).collect())}/// The rows whose R2 objects are waiting to be swept, oldest first.////// The local file is already gone by the time a row reaches this state, so/// nothing on screen depends on the sweep — it is housekeeping in the bucket.pub fn claim_delete_pending(db: &Driver, limit: i64) -> Result<Vec<MediaRow>> {    Ok(db        .all(            &format!(                "SELECT {SELECT_COLUMNS} FROM _media\n                  WHERE state = 'delete_pending'\n                  ORDER BY updated_at, key\n                  LIMIT ?"            ),            &[SqlValue::Integer(limit)],        )?        .iter()        .map(to_row)        .collect())}/// The bytes are in R2. Clears the backoff; `attempts` stays as the record it/// is.pub fn mark_media_synced(db: &Driver, key: &str, now: &str) -> Result<()> {    db.run(        "UPDATE _media SET state = 'synced', last_error = NULL, last_code = NULL, next_attempt_at = NULL, updated_at = ?\n          WHERE key = ?",        &[            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(())}/// The server refused, and will refuse again — too large, wrong type, a key it/// will not sign. Terminal on purpose: no `next_attempt_at`, so no sweep picks/// it up, and the message is kept because it is the only thing that can explain/// to the person why one photo never backed up.pub fn mark_media_failed(db: &Driver, key: &str, error: &str, now: &str) -> Result<()> {    mark_media_failed_as(db, key, codes::REFUSED, error, now)}/// [`mark_media_failed`], filed under `code` ([`codes`]): the word a screen/// says why one file could not be kept by.pub fn mark_media_failed_as(db: &Driver, key: &str, code: &str, error: &str, now: &str) -> Result<()> {    db.run(        "UPDATE _media SET state = 'failed', last_error = ?, last_code = ?, next_attempt_at = NULL, updated_at = ?\n          WHERE key = ?",        &[            SqlValue::Text(error.to_string()),            SqlValue::Text(code.to_string()),            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(())}/// A try that did not land. The row STAYS `pending`; only the backoff moves.////// There is no attempt ceiling and there must not be one: the bytes are on this/// phone and nowhere else, so a row given up on is a file that never reaches/// the backup. `attempts` is recorded for a human to read (and to space the/// retries), never read back to decide whether to stop.pub fn record_media_attempt(    db: &Driver,    key: &str,    error: &str,    now: &str,) -> Result<Option<MediaRow>> {    record_media_attempt_as(db, key, None, error, now)}/// [`record_media_attempt`], with the word a WAIT is filed under/// ([`codes::SPACE_FULL`]), or `None` for a passing failure, which clears the/// last one: the reason it waited is not the reason it failed now.pub fn record_media_attempt_as(    db: &Driver,    key: &str,    code: Option<&str>,    error: &str,    now: &str,) -> Result<Option<MediaRow>> {    db.transaction(|db| {        let Some(existing) = media_by_key(db, key)? else {            return Ok(None);        };        let attempts = existing.attempts + 1;        db.run(            "UPDATE _media SET attempts = ?, last_error = ?, last_code = ?, next_attempt_at = ?, updated_at = ?\n              WHERE key = ?",            &[                SqlValue::Integer(attempts),                SqlValue::Text(error.to_string()),                code.map_or(SqlValue::Null, |code| SqlValue::Text(code.to_string())),                SqlValue::Text(media_backoff_at(now, attempts)?),                SqlValue::Text(now.to_string()),                SqlValue::Text(key.to_string()),            ],        )?;        required(db, key).map(Some)    })}/// The `next_attempt_at` of a row waiting for the next EXCHANGE rather than/// for a time: no clock reaches it, so [`claim_due_media`] never hands the row/// out until [`release_after_exchange`] clears it.pub const AFTER_NEXT_EXCHANGE: &str = "9999-12-31T23:59:59.999Z";/// The server refused these bytes as DEAD (slice 7) — an erase it holds left/// no row naming the key. The row STAYS `pending` and waits for the next/// exchange, not for the backoff: the refusal is wrong for exactly as long as/// this device has not pushed the row that names the key again, and the push/// is what an exchange carries. Never `failed` — a dead-key refusal is retried,/// not dropped.pub fn park_until_exchange(db: &Driver, key: &str, error: &str, now: &str) -> Result<()> {    db.run(        "UPDATE _media SET attempts = attempts + 1, last_error = ?, last_code = 'dead_key', next_attempt_at = ?, updated_at = ?\n          WHERE key = ? AND state = 'pending'",        &[            SqlValue::Text(error.to_string()),            SqlValue::Text(AFTER_NEXT_EXCHANGE.to_string()),            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(())}/// An exchange landed: every row [`park_until_exchange`] parked is due again./// Answers how many.pub fn release_after_exchange(db: &Driver, now: &str) -> Result<usize> {    db.run(        "UPDATE _media SET next_attempt_at = NULL, updated_at = ?\n          WHERE state = 'pending' AND next_attempt_at = ?",        &[            SqlValue::Text(now.to_string()),            SqlValue::Text(AFTER_NEXT_EXCHANGE.to_string()),        ],    )}/// The person deleted the row that owned these bytes.////// The local file is removed by the caller before this is called, so the ledger/// drops `local_path` with it — a path to a file that is gone is worse than no/// path, because a renderer would hand it to the image loader. The R2 object is/// swept on the next drain, and the delete gets a clean attempt history: it is/// a new job, not a continuation of the upload's.pub fn mark_media_delete_pending(db: &Driver, key: &str, now: &str) -> Result<()> {    db.run(        "UPDATE _media SET state = 'delete_pending', local_path = NULL, attempts = 0,\n                            last_error = NULL, next_attempt_at = NULL, updated_at = ?\n          WHERE key = ?",        &[            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(())}/// The row for one key, or `None`. Every renderer's first question.pub fn media_by_key(db: &Driver, key: &str) -> Result<Option<MediaRow>> {    Ok(db        .get(            &format!("SELECT {SELECT_COLUMNS} FROM _media WHERE key = ?"),            &[SqlValue::Text(key.to_string())],        )?        .as_ref()        .map(to_row))}/// Say under what rule a file goes up, who asked, and where else its bytes/// live — in the same write as its enqueue (a capture's transaction), so the/// drain never sees the row without its rule.////// `fresh` is a row this write made. On a fresh row each word given is set./// On a row that was already queued the looser rule wins: `any` from anyone/// opens it, `wifi` never closes a row someone queued for any network./// `asked_by` names the first asker and is never overwritten. `source` is set/// only on a fresh row: bytes this device already held are not made a copy of/// something else by a second asker.pub fn rule_media(    db: &Driver,    key: &str,    network: Option<&str>,    asked_by: Option<&str>,    source: Option<&str>,    fresh: bool,    now: &str,) -> Result<()> {    let text = |value: Option<&str>| value.map_or(SqlValue::Null, |value| SqlValue::Text(value.to_string()));    let (now, key) = (SqlValue::Text(now.to_string()), SqlValue::Text(key.to_string()));    if fresh {        db.run(            "UPDATE _media SET network = COALESCE(?, network), asked_by = COALESCE(asked_by, ?), source = COALESCE(?, source), updated_at = ? WHERE key = ?",            &[text(network), text(asked_by), text(source), now, key],        )?;    } else {        db.run(            "UPDATE _media SET network = CASE WHEN ? = 'any' THEN 'any' ELSE network END, asked_by = COALESCE(asked_by, ?), updated_at = ? WHERE key = ?",            &[text(network), text(asked_by), now, key],        )?;    }    Ok(())}/// The rows for these keys, in the order asked; a key the ledger does not/// hold is left out. What a screen asks of the files it queued ("which of my/// 640 are in Cotton"), cut into statements SQLite takes whatever the count.pub fn media_by_keys(db: &Driver, keys: &[String]) -> Result<Vec<MediaRow>> {    let mut found: std::collections::HashMap<String, MediaRow> = std::collections::HashMap::with_capacity(keys.len());    for chunk in keys.chunks(500) {        let marks = vec!["?"; chunk.len()].join(", ");        let values: Vec<SqlValue> = chunk.iter().map(|key| SqlValue::Text(key.clone())).collect();        for row in db.all(&format!("SELECT {SELECT_COLUMNS} FROM _media WHERE key IN ({marks})"), &values)? {            let row = to_row(&row);            found.insert(row.key.clone(), row);        }    }    Ok(keys.iter().filter_map(|key| found.remove(key)).collect())}/// Every row holding these BYTES, for one workspace — the ledger read/// backwards.////// The media store is content-addressed, so the same file copied in twice is/// one object with one digest. That makes this the index a capture already has/// for "have I filed these bytes before", which is what makes a retry of a/// failed create answer with the row it already wrote instead of writing a/// second one.////// A LIST rather than an option: one file can be filed under more than one key/// (a picture and the same picture as a document), and it is the CALLER that/// knows which kind of key it is looking for.pub fn media_by_sha256(db: &Driver, workspace_id: &str, sha256: &str) -> Result<Vec<MediaRow>> {    Ok(db        .all(            &format!(                "SELECT {SELECT_COLUMNS} FROM _media\n          WHERE workspace_id = ? AND sha256 = ?\n          ORDER BY created_at"            ),            &[                SqlValue::Text(workspace_id.to_string()),                SqlValue::Text(sha256.to_string()),            ],        )?        .iter()        .map(to_row)        .collect())}/// Where these bytes now live on this device — set by the uploader for a file/// it copied in, and by the hydrator for one it just downloaded.////// `None` is a legitimate value: it says the bytes left this phone, and the/// hydrator will fetch them again on demand.pub fn set_media_local_path(    db: &Driver,    key: &str,    local_path: Option<&str>,    now: &str,) -> Result<()> {    db.run(        "UPDATE _media SET local_path = ?, updated_at = ? WHERE key = ?",        &[            local_path.map_or(SqlValue::Null, |path| SqlValue::Text(path.to_string())),            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(())}/// Forget the row entirely — the sweep succeeded, or the bytes were never/// anybody's. The bucket object and the local file are the caller's to remove.pub fn delete_media_row(db: &Driver, key: &str) -> Result<()> {    db.run(        // not a copy: a media row whose sweep succeeded, or whose bytes were never anybody's, as its caller decided.        "DELETE FROM _media WHERE key = ?",        &[SqlValue::Text(key.to_string())],    )?;    Ok(())}/// What a thread header or an import screen shows, for one workspace.pub fn media_counts(db: &Driver, workspace_id: &str) -> Result<MediaCounts> {    let mut counts = MediaCounts::default();    for row in db.all(        "SELECT state, COUNT(*) AS n, COALESCE(SUM(size_bytes), 0) AS bytes FROM _media WHERE workspace_id = ? GROUP BY state",        &[SqlValue::Text(workspace_id.to_string())],    )? {        let n = row.int("n").unwrap_or(0);        match row.text("state") {            Some("pending") => {                counts.pending = n;                counts.pending_bytes = row.int("bytes").unwrap_or(0);            }            Some("synced") => counts.synced = n,            Some("failed") => counts.failed = n,            Some("delete_pending") => counts.delete_pending = n,            _ => {}        }    }    Ok(counts)}// ── the budget's own two columns ────────────────────────────────────────────//// `tier` and `captured_here` are stated at ENQUEUE, because the caller filing// the bytes is the one that knows them. These two are not: a view happens long// after the file arrived, and a pin is the person changing their mind about a// row that has been there for months. So they have writers of their own: the// view's is `media.viewed`, the pin's a book's Keep on phone and Remove// download (`cotton_ffi::phone::books`)./// A detail view opened these bytes. The LRU stamp, and nothing else.////// Answers whether there was a row to stamp: a key nothing has filed is not an/// error — a screen may ask about bytes that arrived by a path with no ledger/// row yet — but it is also not a view anything can order by, and a caller that/// wants to know can.pub fn mark_viewed(db: &Driver, key: &str, now: &str) -> Result<bool> {    let changed = db.run(        "UPDATE _media SET last_viewed_at = ?, updated_at = ? WHERE key = ?",        &[            SqlValue::Text(now.to_string()),            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(changed > 0)}/// The person said keep this here, or stopped saying it.////// Neither the budget nor a Storage pass takes a pinned row; a book's Remove/// download unpins it as its file leaves.////// Both ways, unlike `captured_here`, which is sticky: a pin is a decision/// somebody made and may unmake, and who took a picture is not.pub fn set_media_pinned(db: &Driver, key: &str, pinned: bool, now: &str) -> Result<()> {    db.run(        "UPDATE _media SET pinned = ?, updated_at = ? WHERE key = ?",        &[            SqlValue::Integer(i64::from(pinned)),            SqlValue::Text(now.to_string()),            SqlValue::Text(key.to_string()),        ],    )?;    Ok(())}/// One file that could not be backed up, and the last word the server said/// about it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct FailedMedia {    pub key: String,    pub last_error: Option<String>,    pub updated_at: String,}/// The `failed` rows — the one state nothing retries, so the one a surface has/// to show. Newest first, capped: a list is for reading, not for scrolling.pub fn failed_media(db: &Driver, workspace_id: &str, limit: i64) -> Result<Vec<FailedMedia>> {    Ok(db        .all(            "SELECT key, last_error, updated_at FROM _media\n              WHERE workspace_id = ? AND state = 'failed'\n              ORDER BY updated_at DESC LIMIT ?",            &[                SqlValue::Text(workspace_id.to_string()),                SqlValue::Integer(limit),            ],        )?        .into_iter()        .map(|row| FailedMedia {            key: row.text("key").unwrap_or_default().to_string(),            last_error: row.text("last_error").map(str::to_string),            updated_at: row.text("updated_at").unwrap_or_default().to_string(),        })        .collect())}/// A read-back that must have found something, because we just wrote it.fn required(db: &Driver, key: &str) -> Result<MediaRow> {    media_by_key(db, key)?.ok_or_else(|| {        StoreError::refused(format!(            "mediaLedger: _media row {key} vanished mid-transaction"        ))    })}#[cfg(test)]#[path = "media_ledger_tests.rs"]mod tests;