Cotton code
451 lines · 19.2 KB · RustRaw
//! The budget: bytes LEAVING this device to make room, and the one thing that//! can stop it.//!//! It is the third pass on the drain's tick, after the uploads and after the//! thumbnails, and it is the only one of the three that deletes anything. The//! shape is the drain's and the hydrator's://!//! **THE LEDGER IS THE QUEUE.** There is no remembered work list — `_media`//! says what is here and `cotton_media_holdings` says who else has it — so a//! pass computes its own list from the file and quitting mid-pass loses//! nothing.//!//! **A FAILURE IS A PASS THAT DID LESS.** A file the OS would not delete is//! simply not deleted; there is no attempt counter, because nothing is lost by//! trying again next tick and a row remembering a number would be a second//! thing to be wrong.//!//! ## The fence, and it is absolute//!//! **A phone never drops the last copy of anything.** Before a file goes, the//! pass asks [`holders_of`] for the object's live holders and refuses unless//! one of them is some OTHER device. That is the same sentence the Mac's leave//! refusal makes one layer up, and it is why this pass is safe to run on a//! phone that is the only machine a household has: it will find nothing it is//! allowed to take and will say so.//!//! On top of it, three refusals are in the candidate query itself//! ([`cotton_store::media_evict`]): a PINNED row, a row this device CAPTURED,//! and anything that is not an original or a display rendition — so a//! thumbnail is never a candidate, and neither is a rendition a future build//! invented.//!//! ## What the budget is measured against//!//! The LEDGER's own sum ([`budgeted_bytes`]), not a directory walk — see that//! function for why a walk on this tick would be fifty thousand `stat` calls a//! minute for the rest of a single-device phone's life. **Thumbnails are//! excluded from it**, the same rule the candidate query states one row at a//! time: they are never evicted, so counting them would put a floor under the//! budget that no eviction could get below. Their own ceiling//! ([`THUMB_CEILING_BYTES`]) is a WARNING on the storage pane and never a//! deletion — six hundred megabytes at fifty thousand pictures is the honest//! figure, and deleting thumbnails would put grey squares in a grid to save a//! fraction of what one film costs.//!//! ## Where the number lives//!//! A JSON file beside `connection.json` ([`Layout::media_budget_json`]), read//! fresh every pass so moving the stepper takes effect on the next tick. Not a//! column: the budget is about THIS device's disk, and a replicated setting//! would make the phone and the Mac wrong about each other.use std::path::Path;use std::sync::{Arc, Mutex};use cotton_store::media_evict::{budgeted_bytes, eviction_candidates, mark_evicted};use cotton_store::mint::Held;use cotton_store::media_holdings::{drop_holding, holders_of, Tier};use crate::layout::Layout;use crate::replica::Replica;use crate::seams::Clock;const GIB: u64 = 1024 * 1024 * 1024;/// What a phone keeps of viewed originals and display renditions until somebody/// says otherwise.////// FOUR gigabytes. It is roughly a thousand photographs opened and kept, which/// is more than anybody scrolls back through between two visits to a Mac, and/// it leaves a 64 GB phone the room its own camera needs. The person moves it/// on `/storage`; nothing else does.pub const MEDIA_BUDGET_DEFAULT_BYTES: u64 = 4 * GIB;/// The budgets the settings pane offers, smallest first.////// FOUR CHOICES rather than a free number: a slider over a disk is a control/// nobody can aim, and a typed byte count is a way to set the budget to zero by/// accident. `settings.mediaBudget` refuses anything that is not one of these,/// so the screen and the core cannot disagree about what is allowed.pub const MEDIA_BUDGET_CHOICES: [u64; 4] = [2 * GIB, 4 * GIB, 8 * GIB, 16 * GIB];/// When the thumbnail cache is worth telling somebody about. A WARNING and/// never a deletion — see the module header.pub const THUMB_CEILING_BYTES: u64 = 2 * GIB;/// The sentence that goes with it. Plain terms, and it names the number rather/// than implying something is wrong.pub const THUMB_CEILING_WARNING: &str =    "Thumbnails on this device are over 2 GB. They are small pictures for the grid and \     Cotton never deletes them, so this only grows with the size of your library.";/// How many candidates one query takes. A step size: the budget is re-checked/// between deletions and the pass stops the moment it is met, so asking for the/// whole library to delete three files is the wrong shape.pub const EVICT_BATCH: i64 = 64;/// The one thing the pass touches that is not the file. A port, so the ordering/// and the fence are testable without a disk full of pictures.////// **There is no `dir_bytes` here**, and that is the point of/// [`budgeted_bytes`]: what this device is holding comes out of the ledger in/// one statement rather than out of fifty thousand `stat` calls every minute.pub trait MediaEvictDeps: Send + Sync + std::fmt::Debug {    /// Take one file off this device.    fn remove_file(&self, path: &Path) -> std::io::Result<()>;}/// The budget as it is stored on this device.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct StoredBudget {    pub bytes: u64,}/// What this device keeps, or [`MEDIA_BUDGET_DEFAULT_BYTES`].////// A missing file is the ordinary case — nobody has opened the setting — and a/// file this build cannot read is treated the same way ON PURPOSE: the default/// is a safe number, and refusing to run the pass because a settings file is/// malformed would be a phone that silently fills up. A value that is not one/// of [`MEDIA_BUDGET_CHOICES`] is ignored for the same reason it is refused on/// the way in.pub fn read_budget(layout: &Layout) -> u64 {    std::fs::read_to_string(layout.media_budget_json())        .ok()        .and_then(|text| serde_json::from_str::<StoredBudget>(&text).ok())        .map(|stored| stored.bytes)        .filter(|bytes| MEDIA_BUDGET_CHOICES.contains(bytes))        .unwrap_or(MEDIA_BUDGET_DEFAULT_BYTES)}/// Move it. Refuses anything that is not one of [`MEDIA_BUDGET_CHOICES`].////// The refusal names the choices rather than clamping: a person who asked for a/// number and got a different one silently would have no way to tell, and a/// clamp to zero is a phone that deletes everything it is allowed to.pub fn set_budget(layout: &Layout, bytes: u64) -> Result<u64, String> {    if !MEDIA_BUDGET_CHOICES.contains(&bytes) {        return Err(format!(            "a media budget is one of {}, not {bytes}",            MEDIA_BUDGET_CHOICES                .iter()                .map(|choice| format!("{}", choice / GIB))                .collect::<Vec<String>>()                .join(", ")        ));    }    let path = layout.media_budget_json();    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;    }    let body = serde_json::to_string(&StoredBudget { bytes })        .map_err(|error| error.to_string())?;    std::fs::write(&path, body).map_err(|error| error.to_string())?;    Ok(bytes)}/// The replica of every OTHER database this device holds at its household's/// server, asked as each pass starts — a database admitted a minute ago is in/// the next pass, and one with no media on this device need not be opened.pub type OtherReplicas = Arc<dyn Fn() -> Vec<Arc<Mutex<Replica>>> + Send + Sync>;/// The pass, as a thing the drain holds.pub struct EvictSweep {    pub deps: Arc<dyn MediaEvictDeps>,    pub layout: Layout,    /// This device's KEY, read when the pass runs — the id its own holds name    /// it by and the one the fence leaves out (`super::holds`).    pub device_key: crate::identity::DeviceKey,    /// The op ids a pass's holding writes are minted with come from here.    pub random: Arc<dyn crate::seams::Random>,    /// THE BUDGET IS THE DEVICE'S, so the pass measures and takes across every    /// database's replica, not the attached one alone. `None` is a device    /// holding one database.    pub others: Option<OtherReplicas>,}impl std::fmt::Debug for EvictSweep {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("EvictSweep")            .field("root", &self.layout.root())            .finish_non_exhaustive()    }}/// What one pass did.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct EvictPass {    /// Files taken off this device.    pub removed: usize,    /// The same count by the database each file's row is in, for the word    /// each database's screens are sent.    pub removed_in: std::collections::BTreeMap<String, usize>,    /// What they weighed.    pub bytes: u64,    /// Candidates the fence refused: this device is the only live holder. NOT a    /// failure — it is the pass working — and the number is what tells a person    /// their phone has never met a second machine.    pub last_copy: usize,    /// What this device is holding that the budget counts, at the end of the    /// pass.    pub media_bytes: u64,    /// What it is measured against.    pub budget_bytes: u64,    /// Still over budget when the pass ran out of things it was allowed to    /// take. Ordinary on a household with one device.    pub over_budget: bool,    pub last_error: Option<String>,}/// One pass: delete viewed originals, least recently viewed first, until the/// media store is inside the budget.////// SYNCHRONOUS and blocking, like the hydrator: the replica's driver is SQLite/// and the deletions are filesystem calls, and neither belongs on the runtime's/// own threads.////// The replica's lock is taken PER STEP and released around every filesystem/// call — the drain's own rule, so a read on this device waits on an indexed/// statement rather than on an unlink.pub fn evict_pass(    replica: &Arc<Mutex<Replica>>,    sweep: &EvictSweep,    clock: &dyn Clock,) -> EvictPass {    let mut replicas = vec![Arc::clone(replica)];    if let Some(others) = &sweep.others {        replicas.extend(others());    }    evict_over(&replicas, sweep, clock)}/// One database's replica, as the pass holds it.struct Budgeted {    replica: Arc<Mutex<Replica>>,    workspace_id: String,    /// Whether this device's row has reached this file — a file it has not    /// reached has no visible hold of this device's to drop.    may_hold: bool,}/// [`evict_pass`] over every replica at once: ONE total against ONE budget,/// and ONE least-recently-viewed order across all of them. Each file's fence,/// ledger stamp and dropped hold are asked of and written to the replica the/// file's row is in.fn evict_over(replicas: &[Arc<Mutex<Replica>>], sweep: &EvictSweep, clock: &dyn Clock) -> EvictPass {    let budget = read_budget(&sweep.layout);    let mut ids = crate::seams::op_ids(Arc::clone(&sweep.random));    let mut pass = EvictPass {        budget_bytes: budget,        ..EvictPass::default()    };    let _backup = match cotton_store::media_backup_lock::mutating(&sweep.layout.client_media_dir()) {        Ok(guard) => guard,        Err(error) => { pass.last_error = Some(error.to_string()); return pass; }    };    // THIS DEVICE'S KEY, for the hydrator's reason: "the device I exclude    // from the holders" and "the device whose hold I drop" are the one id    // every reader of the ledger joins on — never the replica's author id.    let device_key = sweep.device_key.get();    let device_id = device_key.clone().unwrap_or_default();    let mut files: Vec<Budgeted> = Vec::with_capacity(replicas.len());    let mut total: u64 = 0;    for replica in replicas {        let mut held = replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        let may_hold = matches!(            crate::media::holds::holder_in(&held.driver, &held.workspace_id, device_key.as_deref()),            Ok(Ok(_))        );        if may_hold {            // Holds this replica wrote under its author id are restated under            // the key, and a hold on an object whose file is not here goes.            if let Some(reason) = crate::media::holds::keep_holds_level(                &mut held,                device_key.as_deref(),                clock.now().timestamp_millis(),                &mut ids,            ) {                pass.last_error = Some(reason);            }        }        match budgeted_bytes(&held.driver, &held.workspace_id) {            Ok(bytes) => total = total.saturating_add(u64::try_from(bytes).unwrap_or(0)),            Err(error) => {                // Nothing is deleted on a number nobody could read — in ANY                // database: a total missing one file's bytes is not the total.                // A pass that could not measure what this device holds and                // took somebody's photographs anyway is the silent fallback                // this repo does not allow.                pass.last_error = Some(error.to_string());                return pass;            }        }        files.push(Budgeted {            replica: Arc::clone(replica),            workspace_id: held.workspace_id.clone(),            may_hold,        });    }    pass.media_bytes = total;    if total <= budget {        return pass;    }    if device_id.is_empty() {        pass.last_error = Some(            "this device has no device key yet, so nothing here could say whose copy it was \             dropping"                .to_string(),        );        return pass;    }    loop {        // ONE ORDER ACROSS EVERY DATABASE. Each file answers its own first        // batch in the store's order; merged on that same order and cut to one        // batch, the result is the device's first batch — a file's later rows        // cannot belong ahead of what was cut.        let mut candidates: Vec<(usize, cotton_store::media_evict::EvictionCandidate)> = Vec::new();        for (index, file) in files.iter().enumerate() {            let listed = {                let held = file.replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner());                eviction_candidates(&held.driver, &file.workspace_id, EVICT_BATCH)            };            match listed {                Ok(rows) => candidates.extend(rows.into_iter().map(|row| (index, row))),                Err(error) => pass.last_error = Some(error.to_string()),            }        }        if candidates.is_empty() {            break;        }        candidates.sort_by(|(_, a), (_, b)| {            (a.last_viewed_at.is_some(), &a.last_viewed_at, &a.key).cmp(&(                b.last_viewed_at.is_some(),                &b.last_viewed_at,                &b.key,            ))        });        candidates.truncate(usize::try_from(EVICT_BATCH).unwrap_or(usize::MAX));        // A batch that took nothing would ask the same question and get the        // same answer for ever — every row in it was refused by the fence or by        // the filesystem. One more query is the cost of noticing.        let mut moved = false;        for (index, candidate) in &candidates {            if total <= budget {                break;            }            let file = &files[*index];            let holders = {                let held = file.replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner());                holders_of(&held.driver, &file.workspace_id, &candidate.key, Tier::Original)            };            let holders = match holders {                Ok(holders) => holders,                Err(error) => {                    pass.last_error = Some(error.to_string());                    continue;                }            };            // THE FENCE. An object no live KEEPER other than this device            // holds — a Mac that keeps everything; a phone's or a rows-only            // Mac's copy may go tomorrow too — stays, and so does one nobody            // has ever recorded a hold for (an empty list). A device never            // drops the last copy of anything.            if !holders                .iter()                .any(|holder| holder.device_id != device_id && holder.keeps_everything)            {                pass.last_copy += 1;                continue;            }            if let Err(error) = sweep.deps.remove_file(Path::new(&candidate.local_path)) {                // A file the OS would not take. The row keeps its path, because                // the file is still there, and the next pass tries again.                pass.last_error = Some(format!(                    "`{}` could not be deleted: {error}",                    candidate.key                ));                continue;            }            let now = clock.now();            let recorded = {                let held = file.replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner());                mark_evicted(&held.driver, &candidate.key, &crate::seams::iso(now))                    .map_err(|error| error.to_string())                    .and_then(|()| {                        // AND THE HOLD. The other devices have to learn this                        // copy is gone, or the household would go on believing                        // two machines hold an object one of them does. A                        // device whose row has not reached this copy has no                        // visible hold to drop (the store would refuse one).                        if !file.may_hold {                            return Ok(());                        }                        drop_holding(                            &held.driver,                            &file.workspace_id,                            &device_id,                            &candidate.key,                            Tier::Original,                            now.timestamp_millis(),                            &mut ids,                            Held::Replica,                        )                        .map(|_| ())                        .map_err(|error| error.to_string())                    })            };            if let Err(reason) = recorded {                // The file is gone and the ledger still names it. Loud, because                // the next `read.mediaPath` would answer a path to nothing.                pass.last_error = Some(format!(                    "`{}` was deleted and the ledger could not be told: {reason}",                    candidate.key                ));            }            moved = true;            pass.removed += 1;            *pass.removed_in.entry(file.workspace_id.clone()).or_default() += 1;            pass.bytes = pass                .bytes                .saturating_add(u64::try_from(candidate.size_bytes).unwrap_or(0));            total = total.saturating_sub(u64::try_from(candidate.size_bytes).unwrap_or(0));        }        if total <= budget || !moved {            break;        }    }    pass.media_bytes = total;    pass.over_budget = total > budget;    pass}/// The real filesystem, for a device that is not a test.#[derive(Debug, Clone, Copy, Default)]pub struct SystemEvictDisk;impl MediaEvictDeps for SystemEvictDisk {    fn remove_file(&self, path: &Path) -> std::io::Result<()> {        std::fs::remove_file(path)    }}#[cfg(test)]#[path = "evict_tests.rs"]mod tests;