//! The budgeted phone cache, as two questions about the file. //! //! A phone holds four things and only one of them is negotiable: //! //! 1. **every blur** — it is a column on the row, so it arrives with the row //! and costs nothing to keep; //! 2. **every thumbnail** — never evicted, and **not counted against the //! budget**: the thumbnail cache is `Layout::thumbs_cache_dir` and the media //! store is `Layout::client_media_dir`, two directories, so "thumbs do not //! count" is true by construction rather than by a filter somebody has to //! remember. Its own ceiling is a WARNING and never a deletion; //! 3. **its own captures, for ever** — `captured_here = 1`, and nothing here //! can take one; //! 4. **viewed originals and display renditions, under a budget** — and those //! are what this module is about. //! //! ## What may be taken //! //! [`EVICTABLE`] is the predicate, spelled once, and every clause in it is a //! refusal: //! //! - `local_path IS NOT NULL` — there is a file to delete; //! - `pinned = 0` — the person did not say keep it; //! - `captured_here = 0` — this phone did not take it; //! - `tier IN ('original','display')` — and **`NULL` is NOT one of them.** A //! row with no tier is every row written before schema v12, plus every object //! that has no tier ladder at all: a document, a meeting's audio, an avatar, //! a film's poster. [`crate::media_ledger::MediaRow::tier`] says it outright //! — a reader that needs a tier must treat `None` as "not a rendition I may //! reason about", never as `Original`, *or the first eviction pass would //! start on the oldest rows in the file*. A tier word THIS BUILD CANNOT NAME //! is excluded by the same clause for the same reason: a row whose rendition //! a future version invented is one this version must not delete a file for. //! Whoever files the bytes fills the column in, off the key //! (`cotton_core::media::keys::rendition_of`). //! //! ## The fence that is not in this predicate //! //! A candidate may only actually go when a LIVE device other than this one //! holds the original — **a phone never drops the last copy of anything**, //! which is the sentence the Mac's leave refusal already makes one layer up. //! That question belongs to [`crate::media_holdings`] and is asked there: //! [`eviction_candidates`] answers the ORDER and the pass asks //! [`holders_of`](crate::media_holdings::holders_of) per key before it deletes, //! while [`evictable_bytes`] folds the same join in through //! [`held_elsewhere_exists`](crate::media_holdings::held_elsewhere_exists) so a //! settings screen gets the number in one statement. //! //! No clock and no filesystem, like the rest of this crate. use rusqlite::types::Value as SqlValue; use crate::driver::Driver; use crate::error::Result; use crate::media_holdings::{held_elsewhere_exists, Tier}; /// What a row must be for the budget to be allowed to take it. Spelled once; /// see the module header for why each clause is there. /// /// Written against an outer alias of `m`, because /// [`held_elsewhere_exists`](crate::media_holdings::held_elsewhere_exists) /// correlates on one. pub const EVICTABLE: &str = "m.workspace_id = ? \ AND m.local_path IS NOT NULL \ AND m.pinned = 0 \ AND m.captured_here = 0 \ AND m.tier IN ('original','display')"; /// What the BUDGET is measured against: every byte of media this device is /// holding, thumbnails excluded. /// /// **The LEDGER and not a directory walk.** Two reasons, and the second is the /// one that decides it. The honest one first: `_media` names every file Cotton /// put in the media store, so the sum IS what the budget is about, and the only /// things a walk would add are `.part` scratch files an eviction cannot help /// with anyway. The deciding one: the eviction pass runs on the media drain's /// own minute, and a phone whose household has no second machine is over budget /// FOR EVER with nothing it is allowed to take — so a walk here would be fifty /// thousand `stat` calls every sixty seconds, for the rest of that phone's /// life, to reach the same refusal. /// /// `/storage` still shows the DIRECTORY's size beside this, through /// its own disk seam. They answer different questions — what the filesystem /// holds, and what Cotton is accounting for — and the screen names both. /// /// **It counts exactly what [`EVICTABLE`] can reach** — the same two tiers — /// and that agreement is load-bearing in both directions. Counting thumbnails /// would put a floor under the budget no eviction could get below; counting /// rows with no tier (a document, a meeting's audio, a film's poster, /// everything written before schema v12) would put the same floor there, made /// of rows the pass may not reason about at all. What it DOES count and cannot /// take is a pinned file and a capture: those occupy the disk whether or not /// anything may take them, and a total that left them out would tell a person /// their phone is emptier than it is. pub fn budgeted_bytes(db: &Driver, workspace_id: &str) -> Result { Ok(db .get( "SELECT COALESCE(SUM(size_bytes), 0) AS n FROM _media WHERE workspace_id = ? AND local_path IS NOT NULL AND tier IN ('original','display')", &[SqlValue::Text(workspace_id.to_string())], )? .and_then(|row| row.int("n")) .unwrap_or(0)) } /// One file the budget may take, and what it costs. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EvictionCandidate { pub key: String, /// Where the file is. Never `None` — the predicate says so. pub local_path: String, /// What the ledger says the file weighs, which is what the pass subtracts /// from the measured total as it goes rather than re-walking the directory /// per deletion. pub size_bytes: i64, /// `None` is a file nobody has ever opened on this device, and it goes /// FIRST. pub last_viewed_at: Option, } /// What the budget may take, LEAST RECENTLY VIEWED FIRST. /// /// **Never-viewed comes before ever-viewed** (`NULLS FIRST`), which is the /// honest reading of least-recently-viewed: a file this device downloaded for a /// grid and nobody ever opened is further from being wanted than one somebody /// opened a year ago. `key` is the tie-break so a pass cut short and resumed /// takes the same rows in the same order. /// /// Capped by `limit` because a pass is a step, not a sweep: the budget is /// checked between deletions and the moment it is met the pass stops, so asking /// for fifty thousand rows to delete four of them is the wrong shape. pub fn eviction_candidates( db: &Driver, workspace_id: &str, limit: i64, ) -> Result> { let sql = format!( "SELECT m.key AS key, m.local_path AS local_path, m.size_bytes AS size_bytes, \ m.last_viewed_at AS last_viewed_at \ FROM _media m \ WHERE {EVICTABLE} \ ORDER BY m.last_viewed_at IS NOT NULL, m.last_viewed_at, m.key \ LIMIT ?" ); Ok(db .all( &sql, &[ SqlValue::Text(workspace_id.to_string()), SqlValue::Integer(limit), ], )? .iter() .map(|row| EvictionCandidate { key: row.text("key").unwrap_or_default().to_string(), local_path: row.text("local_path").unwrap_or_default().to_string(), size_bytes: row.int("size_bytes").unwrap_or(0), last_viewed_at: row.text("last_viewed_at").map(str::to_string), }) .collect()) } /// How many bytes the budget could take right now — the number `/storage` /// prints, and the honest one: it counts only files a live device OTHER than /// this one also holds, so it is what would really go rather than what the /// filter alone would match. pub fn evictable_bytes(db: &Driver, workspace_id: &str, device_id: &str) -> Result { let elsewhere = held_elsewhere_exists(); let sql = format!( "SELECT COALESCE(SUM(m.size_bytes), 0) AS n FROM _media m \ WHERE {EVICTABLE} AND {elsewhere}" ); Ok(db .get( &sql, &[ SqlValue::Text(workspace_id.to_string()), SqlValue::Text(Tier::Original.as_str().to_string()), SqlValue::Text(device_id.to_string()), ], )? .and_then(|row| row.int("n")) .unwrap_or(0)) } /// The file left this device; the row stays, and remembers nothing about where /// it was. /// /// `local_path = NULL` and NOT a delete: the bytes are still in the bucket and /// still held elsewhere — that is the only reason this was allowed — so the row /// is the phone's memory of an object it can fetch again. It also keeps /// `last_viewed_at`, so a file evicted and re-fetched does not jump to the /// front of the queue for having been taken. /// /// `state` is untouched on purpose. A `synced` row whose file is gone is /// exactly what it says: the bytes are up, and they are not here. pub fn mark_evicted(db: &Driver, key: &str, now: &str) -> Result<()> { db.run( "UPDATE _media SET local_path = NULL, updated_at = ? WHERE key = ?", &[ SqlValue::Text(now.to_string()), SqlValue::Text(key.to_string()), ], )?; Ok(()) } #[cfg(test)] #[path = "media_evict_tests.rs"] mod tests;