Cotton code
812 lines · 30.7 KB · RustRaw
//! Rule downloads share the upload timer, never a viewer's opened-byte budget.use super::hydrate::{HydratePass, MediaHydrateDeps};use crate::{    layout::Layout,    replica::Replica,    seams::{Clock, Random},};use cotton_store::{    driver::Driver,    media_holdings::{record_holding, Tier},    media_ledger::{enqueue_media, MediaEnqueueInput},    mint::Held,};use rusqlite::types::Value as Sql;use serde::Serialize;use std::{    collections::BTreeMap,    path::{Path, PathBuf},    sync::{Arc, Mutex},};/// Leave room for the phone's database and its WAL; the Mac replicator's/// twenty-gigabyte floor protects a serving machine and is not a phone rule.pub const KEEP_FETCH_DISK_RESERVE_BYTES: u64 = 256 * 1024 * 1024;pub struct KeepFetchSweep {    pub deps: Arc<dyn MediaHydrateDeps>,    pub layout: Layout,    pub device_key: crate::identity::DeviceKey,    pub random: Arc<dyn Random>,    /// The bytes each database's queue still wants, by database id, as the    /// sweep last worked them out ([`over`]) — what `read.sync_state` answers    /// as `bytes_wanted`. STORED by the worker as it decides what is wanted,    /// never computed on a read: working it out is [`wanted`], a walk of the    /// whole media catalogue that took 8 s on the owner's 3.8 GB Personal alone    /// and 30–43 s beside the fold, and the 20 s HomeSync read that computed it    /// held every read connection of the file (readpool, 16 Oct 2026).    pub wanted_bytes: WantedBytes,}/// Each database's still-wanted bytes, as the keep-fetch sweep last stored/// them — see [`KeepFetchSweep::wanted_bytes`]. Absent until a sweep this/// launch has judged that database: not known is not zero.#[derive(Default)]pub struct WantedBytes(Mutex<BTreeMap<String, (u64, u64, Option<Status>)>>);impl WantedBytes {    /// What the sweep last stored for `database`, if it has judged it.    pub fn of(&self, database: &str) -> Option<u64> {        self.0.lock().unwrap_or_else(|e| e.into_inner()).get(database).map(|(bytes, _, _)| *bytes)    }    /// How many files those bytes are — `sync.status`'s count to fetch.    pub fn count_of(&self, database: &str) -> Option<u64> {        self.0.lock().unwrap_or_else(|e| e.into_inner()).get(database).map(|(_, count, _)| *count)    }    pub fn status(&self, database: &str) -> Option<Status> {        self.0.lock().unwrap_or_else(|e| e.into_inner()).get(database).and_then(|(_, _, status)| status.clone())    }    fn store(&self, database: &str, bytes: u64, count: u64, status: Option<Status>) {        self.0.lock().unwrap_or_else(|e| e.into_inner()).insert(database.to_owned(), (bytes, count, status));    }}#[derive(Debug, Clone)]pub struct Wanted {    pub key: String,    pub bytes: u64,    pub held: bool,    pub at: String,    pub tool: String,    pub source: String,}#[derive(Debug, Clone, Default, Serialize)]#[serde(rename_all = "camelCase")]pub struct Coming {    pub id: String,    pub name: String,    pub held_count: usize,    pub total_count: usize,    pub held_bytes: u64,    pub total_bytes: u64,    pub line: String,}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct ByteRule {    pub tool: String,    pub name: String,    pub keep_rule: String,}pub fn byte_rules(    db: &Driver,    workspace: &str,    device: &str,) -> cotton_store::Result<Vec<ByteRule>> {    [        ("whatsapp", "WhatsApp media"),        ("instagram", "Instagram media"),        ("photo", "Photos"),        ("video", "Videos"),        ("document", "Documents"),    ]    .into_iter()    .map(|(tool, name)| {        cotton_store::storage_rules::byte_rule(db, workspace, device, tool).map(|rule| ByteRule {            tool: tool.into(),            name: name.into(),            keep_rule: rule.as_str().into(),        })    })    .collect()}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct Status {    pub kept_space_bytes: Option<u64>,    pub fetched_bytes: u64,    pub full: bool,    pub full_line: Option<String>,    pub coming: Vec<Coming>,    pub byte_rules: Vec<ByteRule>,    #[serde(skip)]    smallest_missing: Option<u64>,}fn text(s: &str) -> Sql {    Sql::Text(s.into())}pub fn cap(db: &Driver, workspace: &str, device: &str) -> cotton_store::Result<Option<u64>> {    let row = db.get("SELECT kept_space_bytes FROM cotton_devices WHERE workspace_id=? AND device_id=? AND revoked_at IS NULL", &[text(workspace),text(device)])?        .ok_or_else(|| cotton_store::StoreError::refused("Keep fetch needs a live device"))?;    Ok(row.int("kept_space_bytes").map(|v| v.max(0) as u64))}/// Count physical files once, and never bytes opened by the owner.pub fn charged(db: &Driver, workspace: &str) -> cotton_store::Result<u64> {    let rows=db.all("SELECT m.local_path,MAX(m.size_bytes) AS bytes FROM _media m WHERE m.workspace_id=? AND m.fetched_by_rule=1 AND m.last_viewed_at IS NULL AND m.local_path IS NOT NULL AND m.state='synced' AND NOT EXISTS (SELECT 1 FROM _media opened WHERE opened.local_path=m.local_path AND opened.last_viewed_at IS NOT NULL) GROUP BY m.local_path", &[text(workspace)])?;    Ok(rows        .iter()        .filter(|r| holds(r.text("local_path")))        .fold(0u64, |n, r| {            n.saturating_add(r.int("bytes").unwrap_or(0).max(0) as u64)        }))}fn holds(path: Option<&str>) -> bool {    path.is_some_and(|p| Path::new(p).is_file())}/// Originals named by live records, independent of how many Macs hold them./// Unknown sizes are held back: a cap cannot promise what it cannot measure.pub fn wanted(    db: &Driver,    workspace: &str,    device: &str,    now: i64,) -> cotton_store::Result<Vec<Wanted>> {    wanted_key(db, workspace, device, now, None)}fn wanted_key(    db: &Driver,    workspace: &str,    device: &str,    now: i64,    key: Option<&str>,) -> cotton_store::Result<Vec<Wanted>> {    let keep = cotton_store::keep::Keep::of_device(db, device)?;    let rows = db.all(r#"WITH sizes AS ( SELECT object_key AS key, MAX(bytes) AS bytes, MAX(created_at) AS at FROM cotton_media_holdings WHERE workspace_id=?1 AND tier='original' AND dropped_at IS NULL GROUP BY object_key UNION ALL SELECT key,size_bytes,COALESCE(taken_at,created_at) FROM cotton_photos WHERE workspace_id=?1 AND trashed_at IS NULL UNION ALL SELECT key,size_bytes,COALESCE(taken_at,created_at) FROM cotton_videos WHERE workspace_id=?1 AND trashed_at IS NULL UNION ALL SELECT storage_path,byte_size,created_at FROM cotton_documents WHERE workspace_id=?1 AND trashed_at IS NULL), catalogue AS (SELECT key,MAX(bytes) AS bytes,MAX(at) AS at FROM sizes GROUP BY key)SELECT c.key,c.bytes,c.at,m.local_path, (SELECT x.channel FROM _media_key_names n JOIN cotton_msg_messages x ON x.id=n.row_id WHERE n.key=c.key AND n.tbl='cotton_msg_messages' LIMIT 1) AS source, COALESCE((SELECT MAX(x.sent_at) FROM _media_key_names n JOIN cotton_msg_messages x ON x.id=n.row_id WHERE n.key=c.key AND n.tbl='cotton_msg_messages' AND x.deleted_at IS NULL), (SELECT created_at FROM cotton_documents WHERE storage_path=c.key AND workspace_id=?1 AND trashed_at IS NULL LIMIT 1), (SELECT COALESCE(taken_at,created_at) FROM cotton_photos WHERE key=c.key AND workspace_id=?1 AND trashed_at IS NULL LIMIT 1), (SELECT COALESCE(taken_at,created_at) FROM cotton_videos WHERE key=c.key AND workspace_id=?1 AND trashed_at IS NULL LIMIT 1),c.at) AS dated, EXISTS(SELECT 1 FROM cotton_documents d WHERE d.storage_path=c.key AND d.workspace_id=?1 AND d.trashed_at IS NULL) AS document, EXISTS(SELECT 1 FROM cotton_videos v WHERE v.key=c.key AND v.workspace_id=?1 AND v.trashed_at IS NULL) AS videoFROM catalogue c LEFT JOIN _media m ON m.key=c.keyWHERE c.key IS NOT NULL AND (?2 IS NULL OR c.key=?2) AND EXISTS(SELECT 1 FROM _media_key_names n WHERE n.key=c.key)ORDER BY dated DESC,c.key"#, &[text(workspace),key.map_or(Sql::Null,text)])?;    let mut rules = BTreeMap::new();    for r in db.all(        "SELECT tool,keep_rule FROM cotton_storage_rules WHERE workspace_id=? AND device_id=?",        &[text(workspace), text(device)],    )? {        if let (Some(tool), Some(rule)) = (r.text("tool"), r.text("keep_rule")) {            rules.insert(                tool.to_owned(),                cotton_store::storage_rules::KeepRule::parse(rule)?,            );        }    }    // Avatars, posters and thread photos are the thumbnail sweep's: read once    // for the pass, never a lookup per catalogue row — three unindexed scans    // per key made this list quadratic in the size of the file.    let renditions: std::collections::HashSet<String> = db        .all(            "SELECT avatar_key AS key FROM cotton_people WHERE avatar_key IS NOT NULL \             UNION SELECT photo_key FROM cotton_msg_threads WHERE photo_key IS NOT NULL \             UNION SELECT poster_key FROM cotton_videos WHERE poster_key IS NOT NULL",            &[],        )?        .iter()        .filter_map(|r| r.text("key").map(str::to_owned))        .collect();    let mut answer = Vec::new();    for row in rows {        let key = row.text("key").unwrap_or_default();        if cotton_store::keep::is_status_media(key)            || super::unlink::index_says_bytes_dead(db, key)?        {            continue;        }        // Avatars, posters and display renditions are the thumbnail sweep's.        let original = !renditions.contains(key)            && !key.contains("/thumbs/") && !key.contains("/renditions/");        if !original {            continue;        }        // Repository bundles remain Mac bytes; avatars ride the always-on        // portrait sweep. Explicit pins may fetch other kinds of originals.        if key.contains("/repos/") || key.contains("/people/") {            continue;        }        let pinned = keep.pins_key(db, key)?;        let tool = if key.contains("/messages/") {            "thread"        } else if row.int("document") == Some(1) {            "document"        } else if row.int("video") == Some(1) {            "video"        } else if key.contains("/photos/") {            "photo"        } else if pinned {            "other"        } else {            continue;        };        let source = row.text("source").unwrap_or_default();        let rule = if tool == "thread" {            rules.get(source).or_else(|| rules.get(tool))        } else {            rules.get(tool)        }        .copied()        .unwrap_or(cotton_store::storage_rules::default_rule(true, tool));        if !pinned && !rule.keeps(row.text("dated"), now) {            continue;        }        let Some(bytes) = row.int("bytes").filter(|b| *b >= 0) else {            continue;        };        answer.push(Wanted {            key: key.into(),            bytes: bytes as u64,            held: holds(row.text("local_path")),            at: row.text("dated").unwrap_or_default().into(),            tool: tool.into(),            source: row.text("source").unwrap_or_default().into(),        });    }    Ok(answer)}#[cfg(test)]fn status(    db: &Driver,    workspace: &str,    device: &str,    now: i64,) -> cotton_store::Result<Status> {    let kept_space_bytes = cap(db, workspace, device)?;    let fetched_bytes = charged(db, workspace)?;    // Keep fetch is a phone rule: a Mac holds every original through its    // replicator, so it has no queue to work out — and working it out is a    // scan of the whole file.    let wanted = if cotton_store::keep::is_phone(db, device)? {        wanted(db, workspace, device, now)?    } else {        Vec::new()    };    status_from_wanted(db, workspace, device, kept_space_bytes, fetched_bytes, &wanted)}fn status_from_wanted(    db: &Driver, workspace: &str, device: &str,    kept_space_bytes: Option<u64>, fetched_bytes: u64, wanted: &[Wanted],) -> cotton_store::Result<Status> {    let remaining = kept_space_bytes.map(|c| c.saturating_sub(fetched_bytes));    let full = remaining.is_some_and(|left| {        left == 0            || (wanted.iter().any(|w| !w.held)                && !wanted.iter().any(|w| !w.held && w.bytes <= left))    });    let mut lines: BTreeMap<String, Coming> = BTreeMap::new();    let scopes = cotton_store::keep::Keep::byte_pin_scopes(db, device)?;    for w in wanted {        let mut owners = Vec::new();        for (id, name, scope) in &scopes {            if scope.pins_key(db, &w.key)? {                owners.push((id.clone(), name.clone(), true));            }        }        if owners.is_empty() {            owners.push((                if w.tool == "thread" {                    format!("thread:{}", w.source)                } else {                    w.tool.clone()                },                match w.tool.as_str() {                    "thread" => match w.source.as_str() {                        "whatsapp" => "WhatsApp media",                        "instagram" => "Instagram media",                        _ => "Messages media",                    },                    "photo" => "Photos",                    "video" => "Videos",                    _ => "Documents",                }                .into(),                false,            ));        }        for (id, name, counts) in owners {            let line = lines.entry(id.clone()).or_insert_with(|| Coming {                id,                name,                ..Coming::default()            });            line.total_count += 1;            line.total_bytes = line.total_bytes.saturating_add(w.bytes);            if w.held {                line.held_count += 1;                line.held_bytes = line.held_bytes.saturating_add(w.bytes);            }            line.line = if counts {                format!(                    "{} · {} of {}",                    line.name, line.held_count, line.total_count                )            } else {                format!(                    "{} · {} of {} GB",                    line.name,                    gb(line.held_bytes),                    gb(line.total_bytes)                )            };        }    }    Ok(Status {        kept_space_bytes,        fetched_bytes,        full,        full_line: full.then(|| {            format!(                "kept things are full · {} GB",                gb(kept_space_bytes.unwrap_or_default())            )        }),        coming: lines            .into_values()            .filter(|l| l.held_count < l.total_count)            .collect(),        byte_rules: byte_rules(db, workspace, device)?,        smallest_missing: wanted.iter().filter(|w| !w.held).map(|w| w.bytes).min(),    })}/// Compose device-local readings across files; never give each database a/// second allowance, or omit a project's pending album from What is coming.pub fn combine(mut primary: Status, others: impl IntoIterator<Item = (String, Status)>) -> Status {    for (database, status) in others {        primary.fetched_bytes = primary.fetched_bytes.saturating_add(status.fetched_bytes);        primary.smallest_missing = match (primary.smallest_missing, status.smallest_missing) {            (Some(a), Some(b)) => Some(a.min(b)),            (a, b) => a.or(b),        };        primary            .coming            .extend(status.coming.into_iter().map(|mut line| {                line.id = format!("{database}:{}", line.id);                line            }));    }    primary.full = primary.kept_space_bytes.is_some_and(|cap| {        let left = cap.saturating_sub(primary.fetched_bytes);        left == 0 || primary.smallest_missing.is_some_and(|size| size > left)    });    primary.full_line = primary.full.then(|| {        format!(            "kept things are full · {} GB",            gb(primary.kept_space_bytes.unwrap_or_default())        )    });    primary}fn gb(bytes: u64) -> String {    let n = bytes as f64 / 1_000_000_000.;    if n.fract() == 0. {        format!("{n:.0}")    } else {        format!("{n:.1}")    }}/// Whether one more object fits the phone's cap. The only gate: the kind of/// network is never asked (owner, 12 Oct 2026 — downloads run the same on/// Wi-Fi and cellular).fn allowed(cap: Option<u64>, used: u64, size: u64) -> bool {    cap.is_none_or(|c| used.checked_add(size).is_some_and(|n| n <= c))}pub fn pass(    replica: &Arc<Mutex<Replica>>,    sweep: &KeepFetchSweep,    clock: &dyn Clock,    other_charged: u64,) -> HydratePass {    pass_with_budget(replica, sweep, clock, None, &|| {        let r = replica.lock().unwrap_or_else(|e| e.into_inner());        let device = sweep            .device_key            .get()            .ok_or("This device has not joined yet")?;        let limit = cap(&r.driver, &r.workspace_id, &device).map_err(|e| e.to_string())?;        let used = charged(&r.driver, &r.workspace_id).map_err(|e| e.to_string())?;        Ok((limit, used.saturating_add(other_charged)))    })}pub(super) fn pass_with_budget(    replica: &Arc<Mutex<Replica>>,    sweep: &KeepFetchSweep,    clock: &dyn Clock,    only_key: Option<&str>,    budget: &dyn Fn() -> Result<(Option<u64>, u64), String>,) -> HydratePass {    let mut pass = HydratePass::default();    let Some(device) = sweep.device_key.get() else {        pass.off = true;        return pass;    };    let (workspace, owed) = {        let r = replica.lock().unwrap_or_else(|e| e.into_inner());        if !cotton_store::keep::is_phone(&r.driver, &device).unwrap_or(false) {            pass.off = true;            return pass;        }        (            r.workspace_id.clone(),            wanted_key(                &r.driver,                &r.workspace_id,                &device,                clock.now().timestamp_millis(),                only_key,            ),        )    };    let owed = match owed {        Ok(w) => w,        Err(e) => {            pass.last_error = Some(e.to_string());            return pass;        }    };    pass.pending = owed.iter().filter(|w| !w.held).count();    let folder = sweep.layout.client_media_dir().join(&workspace);    if let Err(e) = std::fs::create_dir_all(&folder) {        pass.last_error = Some(e.to_string());        return pass;    }    for w in owed        .into_iter()        .filter(|w| !w.held)        .take(super::hydrate::HYDRATE_BATCH)    {        // ONE FETCH OF A KEY AT A TIME (a person's open may be fetching it        // now); the check below then sees what that fetch left.        let _turn = super::fetching::turn(&w.key);        // Re-read every turn: unkeep, a cap edit and an opening may all have        // happened while the preceding original travelled over the network.        let check = {            let r = replica.lock().unwrap_or_else(|e| e.into_inner());            wanted_key(                &r.driver,                &workspace,                &device,                clock.now().timestamp_millis(),                Some(&w.key),            )        };        let Ok(current) = check else {            break;        };        let (limit, used) = match budget() {            Ok(b) => b,            Err(e) => {                pass.last_error = Some(e);                break;            }        };        if !current.iter().any(|n| n.key == w.key && !n.held) {            continue;        }        if !allowed(limit, used, w.bytes) {            continue;        }        let room = sweep            .deps            .free_bytes(&folder)            .and_then(|free| free.checked_sub(KEEP_FETCH_DISK_RESERVE_BYTES));        let Some(room) = room.filter(|room| *room >= w.bytes) else {            pass.floor = true;            break;        };        let stream_limit = Some(            limit                .map(|cap| cap.saturating_sub(used).min(room))                .unwrap_or(room),        );        let scratch: PathBuf = super::fetching::partial_path(&folder, &w.key);        if let Err(e) =            sweep                .deps                .fetch_object_to_bounded(&workspace, &w.key, &scratch, stream_limit)        {            // A cut keeps what arrived: the next pass resumes from its last            // byte rather than fetching the whole original again.            if !super::fetching::keeps_partial(&e) {                let _ = std::fs::remove_file(&scratch);            }            pass.failed += 1;            pass.last_error = Some(e.message);            continue;        }        let actual = std::fs::metadata(&scratch)            .map(|m| m.len())            .unwrap_or(u64::MAX);        // The server's declared size is advisory; cap the actual arrival too.        let valid = budget()            .ok()            .is_some_and(|(limit, used)| allowed(limit, used, actual));        let r = replica.lock().unwrap_or_else(|e| e.into_inner());        let still_wanted = wanted_key(            &r.driver,            &workspace,            &device,            clock.now().timestamp_millis(),            Some(&w.key),        )        .ok()        .is_some_and(|list| list.iter().any(|n| n.key == w.key && !n.held));        if !valid || !still_wanted {            let _ = std::fs::remove_file(&scratch);            continue;        }        let (sha, size) = match super::store::sha256_file(&scratch) {            Ok(measured) => measured,            Err(error) => {                let _ = std::fs::remove_file(&scratch);                pass.last_error = Some(error.to_string());                continue;            }        };        let extension = w            .key            .rsplit('/')            .next()            .and_then(|name| name.rsplit_once('.'))            .map_or("", |(_, extension)| extension);        let path = super::store::media_file_path(&sweep.layout, &workspace, &sha, extension);        let at = crate::seams::iso(clock.now());        let mut ids = crate::seams::op_ids(Arc::clone(&sweep.random));        let saved = r.driver.transaction(|db| {            enqueue_media(                db,                &MediaEnqueueInput {                    key: w.key.clone(),                    workspace_id: workspace.clone(),                    sha256: sha.clone(),                    content_type: "application/octet-stream".into(),                    size_bytes: size as i64,                    local_path: Some(path.to_string_lossy().into()),                    state: Some("synced".into()),                    after: None,                    after_row_id: None,                    tier: Some(Tier::Original),                    captured_here: false,                    now: at.clone(),                },            )?;            db.run(                "UPDATE _media SET fetched_by_rule=1 WHERE key=?",                &[text(&w.key)],            )?;            Ok(())        });        // Commit accounting before the scratch becomes a retained original.        // A catalogue failure can then only discard a scratch this pass owns,        // never an existing content-addressed file or a capture racing it.        if let Err(error) = saved {            let _ = std::fs::remove_file(&scratch);            pass.failed += 1;            pass.last_error = Some(error.to_string());            continue;        }        if let Err(error) =            super::hydrate::land_measured(&sweep.layout, &workspace, &w.key, &scratch, sha, size)        {            let _ = std::fs::remove_file(&scratch);            pass.failed += 1;            pass.last_error = Some(error.to_string());            continue;        }        if !super::holds::may_announce_holds(&r.driver, Some(&device)) {            pass.pulled += 1;            pass.bytes = pass.bytes.saturating_add(size);            pass.pending = pass.pending.saturating_sub(1);            continue;        }        if let Err(error) = record_holding(            &r.driver,            &workspace,            &device,            &w.key,            Tier::Original,            size as i64,            clock.now().timestamp_millis(),            &mut ids,            Held::Replica,        ) {            // The file is here and accounted for even if its synced holding            // could not be published; the phone is never a replication keeper.            pass.last_error = Some(error.to_string());        }        pass.pulled += 1;        pass.bytes = pass.bytes.saturating_add(size);        pass.pending = pass.pending.saturating_sub(1);    }    pass}/// What one keep-fetch tick did for one database.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct Kept {    /// Originals that landed on this device.    pub landed: usize,    /// Its queue still names an original this device keeps and does not hold    /// — past the batch, over the cap, refused, or a queue that would not    /// read. It is what keeps the drain opening the file    /// (`HeldNote::owes_bytes`).    pub owes: bool,}/// One phone's cap and newest-first queue across all its database files.////// Answers each database the tick could judge. One absent from the answer/// owes nothing to keep-fetch: on a Mac and on a device not yet joined there/// is no queue at all.pub fn over(    replicas: &[Arc<Mutex<Replica>>],    sweep: &KeepFetchSweep,    clock: &dyn Clock,) -> BTreeMap<String, Kept> {    let Some(device) = sweep.device_key.get() else {        return BTreeMap::new();    };    let Some(primary) = replicas.first() else {        return BTreeMap::new();    };    let names: Vec<String> = replicas        .iter()        .map(|r| r.lock().unwrap_or_else(|e| e.into_inner()).workspace_id.clone())        .collect();    // ONE SWEEP PER MEDIA STORE. A drain that is stopped (a detach, a copy    // removed, a re-attach) aborts its task but not the blocking sweep it    // started, and the next drain's first tick started a second sweep over    // the same queue — two walks fetching the same originals. A tick that    // finds one running skips; the running one carries the queue.    static SWEEPING: Mutex<std::collections::BTreeSet<PathBuf>> = Mutex::new(std::collections::BTreeSet::new());    struct Sweeping(PathBuf);    impl Drop for Sweeping {        fn drop(&mut self) {            SWEEPING.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);        }    }    let store = sweep.layout.client_media_dir();    if !SWEEPING.lock().unwrap_or_else(|e| e.into_inner()).insert(store.clone()) {        // The running sweep carries the queue; this tick learned nothing, so        // nothing it was asked about is known to be level.        return names            .into_iter()            .map(|name| (name, Kept { landed: 0, owes: true }))            .collect();    }    let _sweeping = Sweeping(store);    // A phone rule, as `pass_with_budget` says: on a Mac the queue is never    // built, because building it scans every database file under its writer.    {        let r = primary.lock().unwrap_or_else(|e| e.into_inner());        if !cotton_store::keep::is_phone(&r.driver, &device).unwrap_or(false) {            return BTreeMap::new();        }    }    let budget = || {        let limit = {            let r = primary.lock().unwrap_or_else(|e| e.into_inner());            cap(&r.driver, &r.workspace_id, &device).map_err(|e| e.to_string())?        };        let used = replicas.iter().try_fold(0u64, |n, r| {            let r = r.lock().unwrap_or_else(|e| e.into_inner());            charged(&r.driver, &r.workspace_id)                .map(|b| n.saturating_add(b))                .map_err(|e| e.to_string())        })?;        Ok((limit, used))    };    let mut queue = Vec::new();    // Per database, what this tick did and how much of its queue is left.    let mut kept = vec![Kept::default(); replicas.len()];    let mut left = vec![0usize; replicas.len()];    // Per database, the bytes its queue wants and this tick has not landed —    // stored on the sweep at the end for `read.sync_state` to answer.    let mut wanted_left: Vec<Option<u64>> = vec![None; replicas.len()];    let mut catalogues: Vec<Option<Vec<Wanted>>> = vec![None; replicas.len()];    for (index, replica) in replicas.iter().enumerate() {        let r = replica.lock().unwrap_or_else(|e| e.into_inner());        match wanted(            &r.driver,            &r.workspace_id,            &device,            clock.now().timestamp_millis(),        ) {            Ok(list) => {                let before = queue.len();                queue.extend(                    list.iter()                        .filter(|w| !w.held)                        .map(|w| (w.at.clone(), index, w.key.clone(), w.bytes)),                );                left[index] = queue.len() - before;                wanted_left[index] = Some(                    queue[before..]                        .iter()                        .fold(0u64, |sum: u64, wanted: &(String, usize, String, u64)| sum.saturating_add(wanted.3)),                );                catalogues[index] = Some(list);            }            // A queue that would not read is not known to be empty.            Err(_) => kept[index].owes = true,        }    }    queue.sort_by(|a, b| b.0.cmp(&a.0).then(a.2.cmp(&b.2)));    let mut attempted = 0usize;    for (_, index, key, bytes) in queue {        let Ok((limit, used)) = budget() else { break };        if !allowed(limit, used, bytes) {            continue;        }        if attempted >= super::hydrate::HYDRATE_BATCH {            break;        }        attempted += 1;        let replica = &replicas[index];        let pass = pass_with_budget(replica, sweep, clock, Some(&key), &budget);        kept[index].landed += pass.pulled;        if pass.pulled > 0 {            if let Some(list) = &mut catalogues[index] {                for item in list.iter_mut().filter(|w| w.key == key) { item.held = true; }            }            left[index] = left[index].saturating_sub(1);            if let Some(wanted) = wanted_left[index].as_mut() {                *wanted = wanted.saturating_sub(bytes);            }        }        if pass.floor || pass.off {            break;        }    }    // Only the worker measures media. Reads take this stored snapshot even    // while the next pass is walking a large catalogue.    for (index, (replica, list)) in replicas.iter().zip(&catalogues).enumerate() {        let Some(list) = list else { continue };        let r = replica.lock().unwrap_or_else(|e| e.into_inner());        let status = cap(&r.driver, &r.workspace_id, &device).and_then(|limit| {            charged(&r.driver, &r.workspace_id).and_then(|used| {                status_from_wanted(&r.driver, &r.workspace_id, &device, limit, used, list)            })        });        if let Some(bytes) = wanted_left[index] {            sweep.wanted_bytes.store(&r.workspace_id, bytes, left[index] as u64, status.ok());        }    }    names        .into_iter()        .zip(kept.into_iter().zip(left))        .map(|(name, (mut kept, left))| {            kept.owes |= left > 0;            (name, kept)        })        .collect()}#[cfg(test)]#[path = "keep_fetch_tests.rs"]mod tests;