//! What else this device holds on disk: every replica, read off the //! directory ([`held_workspaces`]). use std::path::{Path, PathBuf}; use cotton_store::driver::Driver; use cotton_store::schema::table_specs::TABLE_SPECS; use crate::layout::Layout; /// A workspace this device is already holding a file for. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HeldWorkspace { pub workspace_id: String, pub replica: PathBuf, /// Records in it ([`data_rows`]). pub rows: usize, } /// Every workspace this device holds a replica for, other than `except`. /// /// Read off the DIRECTORY, because that is where the address lives: a replica /// is `client//replica.db` and nothing else records which files this /// device has. A directory that will not open, or a file that will not, is /// skipped — this answers "what is definitely here", and a broken file is not a /// life anything can be put over. pub fn held_workspaces(layout: &Layout, except: &str) -> Vec { let Ok(entries) = std::fs::read_dir(layout.client_dir()) else { return Vec::new(); }; let mut held = Vec::new(); for entry in entries.filter_map(Result::ok) { let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue; }; if name == except { continue; } let replica = layout.replica(&name); if !replica.exists() { continue; } let Some(rows) = rows_in(&replica) else { continue; }; held.push(HeldWorkspace { workspace_id: name, replica, rows, }); } held.sort_by(|left, right| left.workspace_id.cmp(&right.workspace_id)); held } /// Records in a replica, or `None` if it will not open. fn rows_in(replica: &Path) -> Option { let db = Driver::open_reader(replica).ok()?; data_rows(&db).ok() } /// How much of a person's life a file is holding, in rows. /// /// Every replicated table, which is the only count that means anything here: /// `_outbox`, `_media` and the rest are device-local bookkeeping, and counting /// them would let a file with a long queue and no records look like a life. /// `cotton_authors` is left out too: an author's fact is a device's /// announcement, not a record of the person's life. fn data_rows(db: &Driver) -> cotton_store::Result { let mut total = 0usize; for spec in TABLE_SPECS .iter() .filter(|spec| spec.name != cotton_store::fold::AUTHORS_TABLE) { let count = db .get(&format!("SELECT COUNT(*) AS n FROM {}", spec.name), &[])? .and_then(|row| row.int("n")) .unwrap_or(0); total += usize::try_from(count).unwrap_or(0); } Ok(total) } #[cfg(test)] #[path = "held_tests.rs"] mod tests;