Cotton code
239 lines · 9.0 KB · RustRaw
//! This device's own holds, named by its DEVICE KEY.//!//! A holding names a machine by the id every reader of the ledger joins on —//! `cotton_devices.device_id`, the key the server admits this device by — and//! never by the replica's author id (`_meta.device_id`, `device:<ulid>`), which//! is no device row at all (`cotton_store::media_holdings`' module header).//! The key comes from ONE place per process ([`crate::identity::DeviceKey`],//! filled by the shell at open), and both passes that write this device's//! holds — the hydrator and the budget — ask it here.use std::path::Path;use cotton_store::driver::Driver;use cotton_store::mint::Held;use cotton_store::outbox::IdSource;use cotton_store::media_holdings::{    device_standing, drop_holding, is_live_hold, restate_holding, retire_author_holdings,    DeviceStanding, Tier,};use crate::Replica;use rusqlite::types::Value as SqlValue;/// A reader may keep bytes locally but must never publish a replicated holding:/// a holding is a receipt that changes the household's media redundancy state.////// The persisted connection role catches a reader before its first snapshot;/// the signing key and the caller's device key catch an approval that changed/// after the connection was written. An unreadable scope fails closed.pub fn may_announce_holds(db: &Driver, key: Option<&str>) -> bool {    if db.device_scope() == Some(cotton_store::device_scope::DeviceScope::Reader) {        return false;    }    let signer = db.signer().map(|signer| signer.device_key());    signer        .as_deref()        .into_iter()        .chain(key.filter(|key| !key.is_empty()))        .all(|key| cotton_store::device_scope::require_write(db, key).is_ok())}/// The key this device may write a hold under in this replica, or the/// sentence for why it may not yet — no key (it has not paired), or a key whose/// device row has not folded here (or is revoked). A state, never an error:/// the pass skips and the next one tries again.pub fn holder_in(    db: &Driver,    workspace_id: &str,    key: Option<&str>,) -> Result<Result<String, String>, String> {    let Some(key) = key.filter(|key| !key.is_empty()) else {        return Ok(Err(            "this device has no device key yet, so a hold recorded here would name no machine"                .to_string(),        ));    };    if !may_announce_holds(db, Some(key)) {        return Ok(Err(            "this device can only read, so it does not announce media holdings".to_string(),        ));    }    Ok(        match device_standing(db, workspace_id, key).map_err(|error| error.to_string())? {            DeviceStanding::Live => Ok(key.to_string()),            DeviceStanding::Revoked => Err(                "this device is revoked in this database, so a hold it recorded is one nobody \                 counts"                    .to_string(),            ),            DeviceStanding::Absent => Err(                "this device's row has not reached this copy yet, so a hold recorded now is one \                 no reader could see"                    .to_string(),            ),        },    )}/// Rows [`restate_author_holds`] retires per call — the next pass takes the/// next batch, so no call holds the replica for thousands of writes.pub const RESTATE_BATCH: usize = 500;/// What one [`restate_author_holds`] call did.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct Restated {    /// Author-id holds retired by this call — fewer than [`RESTATE_BATCH`]    /// means none are left.    pub retired: usize,    /// Of those, the ones recorded again under the device key.    pub restated: usize,}/// Retire up to [`RESTATE_BATCH`] of the holds this replica wrote under its/// AUTHOR id and record each one whose bytes this device still has (its/// `_media` row names a file that is there) again under the device KEY, with/// the instant it was first held — one transaction, and nothing at all while/// the key may not hold here yet.pub fn restate_author_holds(    db: &Driver,    workspace_id: &str,    key: Option<&str>,    now_ms: i64,    ids: &mut dyn IdSource,) -> Result<Restated, String> {    let Ok(device_id) = holder_in(db, workspace_id, key)? else {        return Ok(Restated::default());    };    db.transaction(|db| {        let retired = retire_author_holdings(db, workspace_id, RESTATE_BATCH, now_ms, ids, Held::Replica)?;        let mut answer = Restated {            retired: retired.len(),            restated: 0,        };        for hold in retired {            if !still_here(db, &hold.object_key)?                || is_live_hold(db, &device_id, &hold.object_key, hold.tier)?            {                continue;            }            restate_holding(                db,                workspace_id,                &device_id,                &hold.object_key,                hold.tier,                hold.bytes,                &hold.created_at,                now_ms,                ids,                Held::Replica,            )?;            answer.restated += 1;        }        Ok(answer)    })    .map_err(|error| error.to_string())}/// Drop every live hold this device has under its KEY whose object has no/// file on this device in its ledger — no `_media` row, or one naming no/// path. That is a hold that came back with a restored copy of the database/// (`claim_snapshot` clears `_media`, the holdings travel with the snapshot)./// A hold is this device saying "these are on my disk"; left standing, it/// would be counted as a second copy by another machine's leave and eviction/// fence, and the hydrator would never pull the bytes back. `dropped_at`,/// never a delete. Answers how many were dropped; nothing while the key may/// not hold here.////// ONE indexed query, no `stat`: it runs every pass, under the replica's/// lock, and a ledger row whose file went missing some other way is the/// eviction pass's to settle, not this one's.pub fn drop_missing_holds(    db: &Driver,    workspace_id: &str,    key: Option<&str>,    now_ms: i64,    ids: &mut dyn IdSource,) -> Result<usize, String> {    let Ok(device_id) = holder_in(db, workspace_id, key)? else {        return Ok(0);    };    db.transaction(|db| {        let missing = db.all(            "SELECT h.object_key AS object_key, h.tier AS tier FROM cotton_media_holdings h \             WHERE h.workspace_id = ? AND h.device_id = ? AND h.dropped_at IS NULL \             AND NOT EXISTS (SELECT 1 FROM _media m WHERE m.key = h.object_key \                             AND coalesce(m.local_path, '') <> '')",            &[                SqlValue::Text(workspace_id.to_string()),                SqlValue::Text(device_id.clone()),            ],        )?;        let mut dropped = 0usize;        for row in &missing {            let (Some(object_key), Some(tier)) = (                row.text("object_key"),                row.text("tier").and_then(Tier::parse),            ) else {                continue;            };            if drop_holding(db, workspace_id, &device_id, object_key, tier, now_ms, ids, Held::Replica)? {                dropped += 1;            }        }        Ok(dropped)    })    .map_err(|error| error.to_string())}/// Every pass's upkeep of this device's own holds, for the hydrator and the/// budget alike: the author-id holds are restated under the key until none/// are left (then [`Replica::author_holds_level`] stops the asking), and a/// hold on an object this device has no file for is dropped. Nothing while/// the key may not hold here. Answers the sentence for what went wrong, if/// anything did.pub fn keep_holds_level(    held: &mut Replica,    key: Option<&str>,    now_ms: i64,    ids: &mut dyn IdSource,) -> Option<String> {    let mut error = None;    if !held.author_holds_level {        match restate_author_holds(&held.driver, &held.workspace_id, key, now_ms, ids) {            Ok(done) => {                let may_hold = matches!(holder_in(&held.driver, &held.workspace_id, key), Ok(Ok(_)));                if may_hold && done.retired < RESTATE_BATCH {                    held.author_holds_level = true;                }            }            Err(reason) => {                error = Some(format!(                    "this device's older holds could not be restated under its key: {reason}"                ));            }        }    }    if let Err(reason) = drop_missing_holds(&held.driver, &held.workspace_id, key, now_ms, ids) {        error = Some(format!(            "this device's holds on missing files could not be dropped: {reason}"        ));    }    error}/// Whether this device's ledger names a file for `key` that is really there.fn still_here(db: &Driver, key: &str) -> cotton_store::Result<bool> {    Ok(db        .get(            "SELECT local_path FROM _media WHERE key = ?",            &[SqlValue::Text(key.to_string())],        )?        .and_then(|row| row.text("local_path").map(str::to_string))        .is_some_and(|path| !path.is_empty() && Path::new(&path).is_file()))}#[cfg(test)]#[path = "holds_tests.rs"]mod tests;