Cotton code
612 lines · 27.5 KB · RustRaw
//! Which rows name which media object key (groundwork slice 7).//!//! A media object — a photo's bytes, a document's original, a chat//! attachment — lives in the store under a KEY, and a row names it in a//! column. [`MEDIA_KEY_HOLDERS`] is the one declared list of those columns;//! the guard `every_media_key_column_is_on_media_key_holders` holds every//! key-shaped column of every table spec to it (or to [`NOT_MEDIA_KEYS`],//! each with why), so a new column a media writer fills cannot be missed.//!//! A key BUILT FROM IDS and stored in no column — a meeting's `full.<ext>` in//! every container, a pathless segment's — is declared in [`DERIVED_MEDIA_KEYS`] beside the//! list, and is named exactly as a stored key is: while its record is present//! or dormant. A row whose [`MEDIA_KEY_RELEASES`] column is set (a meeting's//! `audio_deleted_at`) names no key: setting it is the row letting its bytes//! go while it stays, and writes the same erasure facts an Erase would.//!//! `_media_key_names (key, tbl, row_id)` is the device-local index the//! dead-key rule reads ([`crate::media_erasure`]). It is kept where the store//! takes a row — a local write and a peer's fold alike — through//! `fact_hooks::row_taken`, so `fold.rs` names no table. **A row names every//! key any receipt of it this file took wrote into a holder column, until it//! is ERASED** (`erase::apply` clears its names): a retract keeps them, a//! dormant row keeps them, a later value beside an earlier one keeps both. It//! only ever over-names, and over-naming keeps bytes; it never unlinks a key a//! present or dormant row names.use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::Value as SqlValue;use serde_json::Value as JsonValue;use crate::canonical::{Kind, Receipt};use crate::driver::Driver;use crate::error::Result;use crate::file_identity::FileId;use crate::schema::specs::spec_for;/// How a holder column carries its keys.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum KeyShape {    /// The column's text is one key.    Text,    /// The column is a JSON array of objects, each naming one key in `key`    /// and perhaps a rendition's in `playbackKey` (`MessageMedia`).    Items,    /// A meeting's segment manifest: a JSON array of entries, each naming its    /// key in `path`; a `lost` entry has no object and names none.    Segments,}/// Every column that holds a media object key: `(table, column, shape)`.pub const MEDIA_KEY_HOLDERS: &[(&str, &str, KeyShape)] = &[    ("cotton_photos", "key", KeyShape::Text),    ("cotton_videos", "key", KeyShape::Text),    ("cotton_videos", "poster_key", KeyShape::Text),    ("cotton_media_sightings", "key", KeyShape::Text),    ("cotton_msg_messages", "media", KeyShape::Items),    ("cotton_msg_threads", "photo_key", KeyShape::Text),    ("cotton_posts", "media", KeyShape::Items),    ("cotton_stories", "media_key", KeyShape::Text),    ("cotton_msg_contacts", "avatar_key", KeyShape::Text),    ("cotton_session_messages", "media", KeyShape::Items),    ("cotton_documents", "storage_path", KeyShape::Text),    ("cotton_documents", "decrypted_path", KeyShape::Text),    ("cotton_people", "avatar_key", KeyShape::Text),    ("cotton_repo_bundles", "object_key", KeyShape::Text),    ("cotton_repo_jobs", "log_key", KeyShape::Text),    ("cotton_meetings", "segments", KeyShape::Segments),];/// Builds the keys a row names WITHOUT storing them: `(file id, row id, the/// value of the declared input column)`. Every key it answers contains the row/// id, which is how the direct reader finds the row from the key alone.pub type DerivedKeys = fn(&FileId, &str, Option<&JsonValue>) -> BTreeSet<String>;/// Keys BUILT FROM IDS, beside [`MEDIA_KEY_HOLDERS`]: `(table, input column,/// rule)`. Such a key is named exactly while its record is present or dormant/// and not released ([`MEDIA_KEY_RELEASES`]) — the rule a stored key follows —/// so the same erasure, dead-key rule and unlink queue take it.pub const DERIVED_MEDIA_KEYS: &[(&str, &str, DerivedKeys)] = &[("cotton_meetings", "segments", meeting_derived_keys)];/// A column that, once set, says the row LET ITS BYTES GO while the row stays:/// a row whose release column holds a value names no key. Setting it writes an/// erasure fact per key the row named (`media_erasure::with_erasure_facts`).pub const MEDIA_KEY_RELEASES: &[(&str, &str)] =    &[("cotton_meetings", "audio_deleted_at"), ("cotton_stories", "media_dropped_at")];/// The container a meeting's audio is in when nothing says otherwise — the/// same constant as `cotton_core::media::keys::MEETING_AUDIO_DEFAULT_EXT`,/// which this crate cannot name (a cotton-core test holds the two spellings/// together). The recorder's segments are always in it.const MEETING_AUDIO_DEFAULT_EXT: &str = "m4a";/// Every container a meeting's recording may be filed under — the extensions/// of `cotton_core::media::meeting_audio::MEETING_AUDIO_FORMATS`, which this/// crate cannot name (the same cotton-core test holds the two lists together).////// **The key's extension follows the source**: a WhatsApp voice note lands at/// `full.opus`, a Voice Memo at `full.m4a`. Which one a meeting used is said/// only by its manifest, and a manifest can lose that entry (an older writer,/// an edit); naming `full.<ext>` for every container means no spelling's/// object outlives its meeting. Naming one that was never written is harmless:/// its erasure fact unlinks nothing, and the unlink pass treats a missing/// object as gone.const MEETING_AUDIO_EXTS: &[&str] = &["m4a", "mp4", "aac", "mp3", "wav", "opus", "ogg", "oga", "flac", "amr", "caf"];/// A meeting's id-built keys: `{file}/meetings/{id}/full.<ext>` for every/// container in [`MEETING_AUDIO_EXTS`] (`full.m4a` is what a row with no/// manifest means; the others are where an import in that container lands),/// and `{file}/meetings/{id}/segments/{nnn}.m4a` for each manifest entry with/// a numeric `seq`, no stored `path`, and not `lost` — the spellings of/// `cotton_core::media::keys::meeting_full_key_of` and `meeting_segment_key`.pub fn meeting_derived_keys(file: &FileId, meeting_id: &str, segments: Option<&JsonValue>) -> BTreeSet<String> {    let mut keys: BTreeSet<String> =        MEETING_AUDIO_EXTS.iter().map(|ext| format!("{file}/meetings/{meeting_id}/full.{ext}")).collect();    let parsed;    let entries = match segments {        Some(JsonValue::String(text)) => {            parsed = serde_json::from_str::<JsonValue>(text).unwrap_or(JsonValue::Null);            &parsed        }        Some(other) => other,        None => &JsonValue::Null,    };    for entry in entries.as_array().into_iter().flatten() {        let Some(seq) = entry.get("seq").and_then(JsonValue::as_i64) else {            continue;        };        let stored = entry.get("path").and_then(JsonValue::as_str).is_some_and(|path| !path.is_empty());        if stored || entry.get("lost") == Some(&JsonValue::Bool(true)) {            continue;        }        // JS's `String(seq).padStart(3, "0")`, minus sign padded like a digit.        let digits = seq.to_string();        let padded = if digits.len() >= 3 { digits } else { format!("{}{digits}", "0".repeat(3 - digits.len())) };        keys.insert(format!("{file}/meetings/{meeting_id}/segments/{padded}.{MEETING_AUDIO_DEFAULT_EXT}"));    }    keys}/// The release column of `table`, if it has one.pub fn release_column(table: &str) -> Option<&'static str> {    MEDIA_KEY_RELEASES.iter().find(|(name, _)| *name == table).map(|(_, column)| *column)}/// Whether a release column's value says the row let its bytes go.fn is_set(value: Option<&JsonValue>) -> bool {    match value {        None | Some(JsonValue::Null) => false,        Some(JsonValue::String(text)) => !text.trim().is_empty(),        Some(_) => true,    }}/// Whether a row with these fields has released its keys.pub fn is_released<'a>(table: &str, field: impl Fn(&str) -> Option<&'a JsonValue>) -> bool {    release_column(table).is_some_and(|column| is_set(field(column)))}/// Whether `table` names keys at all: a holder column or a derived rule.pub(crate) fn names_keys(table: &str) -> bool {    is_holder_table(table) || DERIVED_MEDIA_KEYS.iter().any(|(name, _, _)| *name == table)}/// Every key a row with these fields names: its holder columns and its/// id-built keys (when the file is known), or none once it is released.pub fn keys_of_row<'a>(    file: Option<&FileId>,    table: &str,    row_id: &str,    field: impl Fn(&str) -> Option<&'a JsonValue>,) -> BTreeSet<String> {    if is_released(table, &field) {        return BTreeSet::new();    }    let mut keys = keys_in_fields(table, &field);    if let Some(file) = file {        for (_, column, rule) in DERIVED_MEDIA_KEYS.iter().filter(|(name, _, _)| *name == table) {            keys.extend(rule(file, row_id, field(column)));        }    }    keys}/// The columns a row of `table` is read by for its keys: holders, derived/// inputs and the release column.fn key_columns(table: &str) -> Vec<&'static str> {    let mut columns: Vec<&'static str> = holders_of(table).map(|(column, _)| column).collect();    columns.extend(DERIVED_MEDIA_KEYS.iter().filter(|(name, _, _)| *name == table).map(|(_, column, _)| *column));    columns.extend(release_column(table));    columns.sort_unstable();    columns.dedup();    columns}/// The present row's key columns, as JSON text values, or `None` when the row/// is not present.fn present_fields(db: &Driver, table: &str, row_id: &str) -> Result<Option<BTreeMap<String, JsonValue>>> {    let Some(spec) = spec_for(table) else {        return Ok(None);    };    let columns = key_columns(table);    if columns.is_empty() {        return Ok(None);    }    let select: Vec<String> = columns.iter().map(|column| format!("\"{column}\"")).collect();    let Some(row) = db.get(        &format!("SELECT {} FROM {} WHERE \"{}\" = ?", select.join(", "), spec.name, spec.pk),        &[SqlValue::Text(row_id.to_string())],    )?    else {        return Ok(None);    };    Ok(Some(        columns            .iter()            .filter_map(|column| row.text(column).map(|text| (column.to_string(), JsonValue::String(text.to_string()))))            .collect(),    ))}/// The id of this file, which id-built keys start with.fn file_id(db: &Driver) -> Result<Option<FileId>> {    Ok(crate::file_identity::read_file_identity(db)?.map(|identity| identity.id().clone()))}/// The key-shaped columns that hold NO media object key, each with what it/// holds instead — the other half of what the guard reads.pub const NOT_MEDIA_KEYS: &[(&str, &str, &str)] = &[    ("cotton_collections", "sort_key", "an ordering string"),    ("cotton_email_threads", "external_key", "the mail provider's thread id"),    ("cotton_msg_threads", "external_key", "the chat source's thread id"),    ("cotton_news_seen", "key", "a story's dedupe key"),    ("cotton_vault_keys", "public_key", "a vault public key"),    ("cotton_secret_placements", "path", "a file path a secret is placed at"),    ("cotton_devices", "relay_identity_key", "a relay identity key"),    ("cotton_device_relay_keys", "relay_identity_key", "a relay identity key a Mac presented"),    ("cotton_devices", "person_key", "a person's public key"),    ("cotton_repos", "key", "host/owner/name of a repository"),    ("cotton_repo_comments", "path", "a path inside a repository"),    ("cotton_dev_jobs", "log_path", "a file on the Mac that ran the job, never an object"),    ("cotton_serving_machine", "relay_key", "a relay key"),    ("cotton_media_erasures", "key", "the erasure fact's own key: it records a key's end, it does not keep it"),    ("cotton_media_holdings", "object_key", "which device holds a copy: bookkeeping about a key, never a record naming it"),    ("cotton_media_backups", "object_key", "bucket verification evidence about a key, never a record retaining its bytes"),    ("cotton_person_keys", "public_key", "a person's public key"),    ("cotton_admissions", "person_key", "a person's public key"),    ("cotton_member_person_claims", "person_key", "the member's public signing key, not a media object"),    ("cotton_device_statements", "person_key", "a person's public key"),    ("cotton_device_statements", "device_key", "a device's public key"),    ("cotton_device_statements", "vault_public_key", "a vault public key"),];/// Is `column` shaped like one that could hold an object key: `key`,/// `…_key`, `path`, `…_path`, or a JSON `media`.pub fn is_key_shaped(column: &str, codec: crate::schema::decl::Codec) -> bool {    column == "key"        || column.ends_with("_key")        || column == "path"        || column.ends_with("_path")        || (column == "media" && codec == crate::schema::decl::Codec::Json)}/// The holder columns of `table`.pub fn holders_of(table: &str) -> impl Iterator<Item = (&'static str, KeyShape)> + '_ {    MEDIA_KEY_HOLDERS        .iter()        .filter(move |(name, _, _)| *name == table)        .map(|(_, column, shape)| (*column, *shape))}/// Whether `table` has a holder column.pub fn is_holder_table(table: &str) -> bool {    holders_of(table).next().is_some()}/// The keys one holder value carries. A JSON column may arrive as its text/// or as the value itself; anything that is not a key names nothing.pub fn keys_in_value(shape: KeyShape, value: &JsonValue) -> Vec<String> {    let mut out = Vec::new();    match shape {        KeyShape::Text => {            if let Some(key) = value.as_str().map(str::trim).filter(|key| !key.is_empty()) {                out.push(key.to_string());            }        }        KeyShape::Items => {            let parsed;            let items = match value {                JsonValue::String(text) => {                    parsed = serde_json::from_str::<JsonValue>(text).unwrap_or(JsonValue::Null);                    &parsed                }                other => other,            };            // `playbackKey` names a voice note's phone-playable rendition, a            // second object the row owns as much as its `key`.            for item in items.as_array().into_iter().flatten() {                for field in ["key", "playbackKey"] {                    if let Some(key) = item.get(field).and_then(JsonValue::as_str).map(str::trim) {                        if !key.is_empty() {                            out.push(key.to_string());                        }                    }                }            }        }        KeyShape::Segments => {            let parsed;            let entries = match value {                JsonValue::String(text) => {                    parsed = serde_json::from_str::<JsonValue>(text).unwrap_or(JsonValue::Null);                    &parsed                }                other => other,            };            for entry in entries.as_array().into_iter().flatten() {                if entry.get("lost") == Some(&JsonValue::Bool(true)) {                    continue;                }                if let Some(key) = entry.get("path").and_then(JsonValue::as_str).map(str::trim) {                    if !key.is_empty() {                        out.push(key.to_string());                    }                }            }        }    }    out}/// The keys a set of `table`'s fields names, by [`MEDIA_KEY_HOLDERS`].pub fn keys_in_fields<'a>(table: &str, field: impl Fn(&str) -> Option<&'a JsonValue>) -> BTreeSet<String> {    let mut keys = BTreeSet::new();    for (column, shape) in holders_of(table) {        if let Some(value) = field(column) {            keys.extend(keys_in_value(shape, value));        }    }    keys}/// The keys `table`'s `row_id` names right now: its present row's holder/// columns and id-built keys, or a dormant row's fields assembled from its/// receipts, and every key `_media_key_names` holds for it — none once the row/// is released ([`MEDIA_KEY_RELEASES`]).pub fn keys_named_by(db: &Driver, table: &str, row_id: &str) -> Result<BTreeSet<String>> {    let held = index_names(db, table, row_id)?;    keys_named_with(db, table, row_id, held)}/// The keys `_media_key_names` holds for `table`'s `row_id`. The index is/// keyed by the key, so this is a pass over all of it: an act that asks it of/// many rows reads it once for them all (`erase::Owned::key_names`).pub(crate) fn index_names(db: &Driver, table: &str, row_id: &str) -> Result<BTreeSet<String>> {    let mut keys = BTreeSet::new();    let key = [SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())];    for row in db.all("SELECT key FROM _media_key_names WHERE tbl = ? AND row_id = ?", &key)? {        if let Some(name) = row.text("key") {            keys.insert(name.to_string());        }    }    Ok(keys)}/// [`keys_named_by`], given what the index holds for the row (`held`).pub(crate) fn keys_named_with(db: &Driver, table: &str, row_id: &str, held: BTreeSet<String>) -> Result<BTreeSet<String>> {    let mut keys = held;    if spec_for(table).is_none() || !names_keys(table) {        return Ok(keys);    }    let file = file_id(db)?;    let fields = match present_fields(db, table, row_id)? {        Some(present) => present,        None => crate::receipts::dormant_fields(db, table, row_id)?,    };    if is_released(table, |column| fields.get(column)) {        return Ok(BTreeSet::new());    }    keys.extend(keys_of_row(file.as_ref(), table, row_id, |column| fields.get(column)));    Ok(keys)}/// The `row_taken` hook: a row of a holder table was taken, so each key its/// receipt writes — and each key built from its id — is named by it. A row/// that is RELEASED once the receipt is taken names nothing: its names leave/// the index, and a key an erasure already names and nothing names now is/// queued. Answers the keys named, for the unlink queue's re-reference rule.pub(crate) fn names_taken(db: &Driver, receipt: &Receipt) -> Result<BTreeSet<String>> {    if receipt.kind == Kind::Retract || !names_keys(&receipt.table) {        return Ok(BTreeSet::new());    }    let (table, row_id) = (receipt.table.as_str(), receipt.row_id.as_str());    let present = if release_column(table).is_some() || DERIVED_MEDIA_KEYS.iter().any(|(name, _, _)| *name == table) {        present_fields(db, table, row_id)?    } else {        None    };    if release_column(table).is_some() {        let released = match &present {            Some(fields) => is_released(table, |column| fields.get(column)),            None => {                let dormant = crate::receipts::dormant_fields(db, table, row_id)?;                is_released(table, |column| dormant.get(column))            }        };        if released {            let key = [SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())];            let dropped: BTreeSet<String> = db                .all("SELECT key FROM _media_key_names WHERE tbl = ? AND row_id = ?", &key)?                .iter()                .filter_map(|row| row.text("key").map(str::to_string))                .collect();            // not a copy: _media_key_names, which rows name which media key, derived.            db.run("DELETE FROM _media_key_names WHERE tbl = ? AND row_id = ?", &key)?;            crate::media_erasure::names_dropped(db, &dropped, &receipt.stamp)?;            return Ok(BTreeSet::new());        }    }    let file = file_id(db)?;    let mut keys = keys_of_row(file.as_ref(), table, row_id, |column| receipt.fields.get(column));    if let Some(fields) = &present {        keys.extend(keys_of_row(file.as_ref(), table, row_id, |column| fields.get(column)));    }    for key in &keys {        db.run(            "INSERT INTO _media_key_names (key, tbl, row_id) VALUES (?, ?, ?) ON CONFLICT DO NOTHING",            &[SqlValue::Text(key.clone()), SqlValue::Text(table.to_string()), SqlValue::Text(row_id.to_string())],        )?;    }    Ok(keys)}/// Whether any present or dormant row names `key`.pub fn is_named(db: &Driver, key: &str) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS named FROM _media_key_names WHERE key = ? LIMIT 1",            &[SqlValue::Text(key.to_string())],        )?        .is_some())}/// One name: `(key, table, row_id)`, as `_media_key_names` holds it.pub type Name = (String, String, String);/// Whether `needle` reads the same inside a receipt's canonical JSON as it/// does in a column, so a substring test cannot miss it there: no quote, no/// backslash, no control byte, nothing outside ASCII.fn survives_json_text(needle: &str) -> bool {    needle.bytes().all(|byte| byte.is_ascii_graphic() && byte != b'"' && byte != b'\\')}/// THE SECOND READER — every name the holder columns themselves say, never/// `_media_key_names`: each present row's [`MEDIA_KEY_HOLDERS`] columns and/// [`DERIVED_MEDIA_KEYS`], and each create or change receipt this file holds/// for such a table (the image of a dormant or retracted row is its receipts;/// an erase deletes them with it). A released row names nothing, its receipts/// included. `needle` narrows the read to values containing it — or, for a/// table with id-built keys, to rows whose id the needle contains — and/// `wanted` keeps only the keys asked about.fn read_names(db: &Driver, needle: Option<&str>, wanted: &dyn Fn(&str) -> bool) -> Result<BTreeSet<Name>> {    let mut sweep = NameSweep::default();    let mut names = BTreeSet::new();    while let Some(page) = sweep.next_matching(db, needle, wanted)? {        names.extend(page);    }    Ok(names)}mod name_sweep;pub use name_sweep::NameSweep;/// The rows that name `key`, read straight off the holder columns and the/// receipts ([`read_names`]) — the question asked before any bytes go,/// independent of the index the dead-key rule reads.pub fn rows_naming(db: &Driver, key: &str) -> Result<BTreeSet<Name>> {    let key = key.trim();    read_names(db, Some(key), &|found| found == key)}/// The rows that name any key of `family` (a prefix ending in `.`), read the/// same way as [`rows_naming`].pub fn rows_naming_family(db: &Driver, family: &str) -> Result<BTreeSet<Name>> {    read_names(db, Some(family), &|found| found.starts_with(family))}/// EVERY NAME THE ROWS GIVE, READ ONCE — the direct reader's answer for a/// whole unlink pass instead of one read per queued key.////// [`rows_naming`] is a scan of every holder table and every receipt of one,/// and a pass that asked it per key was that scan a few thousand times over/// when a prune had queued a few thousand keys — each inside a hold of the/// file. One read with no needle is the same rows read once, and it can be/// made on a READ connection ([`Driver::open_reader`]) with no hold at all.////// **WHAT A READ THAT IS A MOMENT OLD MAY SAY.** "No row names this key" is/// safe to act on with the index asked again under the lock: a row that came/// to name the key since was written through the hook, which names it in/// `_media_key_names` in the same transaction. "A row names this key" is NOT/// acted on from here — the row may have been erased since — so a caller that/// hears it asks [`rows_naming`] again, now, under its lock/// (`media_erasure::may_unlink_read`). That second read runs only for a key/// the index missed, which is a defect and never the ordinary path.#[derive(Debug, Default, Clone, PartialEq, Eq)]pub struct RowsRead {    keys: BTreeSet<String>,}impl RowsRead {    /// Read every name off the holder columns and the receipts, in one    /// snapshot of the file.    pub fn read(db: &Driver) -> Result<RowsRead> {        let names = read_names(db, None, &|_| true)?;        Ok(RowsRead { keys: names.into_iter().map(|(key, _, _)| key).collect() })    }    /// Whether a row named `key` when this was read.    pub fn names(&self, key: &str) -> bool {        self.keys.contains(key.trim())    }    /// Whether a row named any key of `family` (a prefix ending in `.`).    pub fn names_family(&self, family: &str) -> bool {        self.keys            .range::<str, _>((std::ops::Bound::Included(family), std::ops::Bound::Unbounded))            .next()            .is_some_and(|key| key.starts_with(family))    }}/// Write `names` into `_media_key_names` and take each named key out of the/// unlink queue, as the hook does. Answers how many names were new.pub(crate) fn insert_names(db: &Driver, names: &BTreeSet<Name>) -> Result<usize> {    let mut added = 0;    let mut keys = BTreeSet::new();    for (key, table, row_id) in names {        added += db.run(            "INSERT INTO _media_key_names (key, tbl, row_id) VALUES (?, ?, ?) ON CONFLICT DO NOTHING",            &[                SqlValue::Text(key.clone()),                SqlValue::Text(table.clone()),                SqlValue::Text(row_id.clone()),            ],        )?;        keys.insert(key.clone());    }    crate::media_erasure::named_again(db, &keys)?;    Ok(added)}/// REBUILD THE INDEX FROM THE ROWS: every key a present row's holder column/// names, and every key a held receipt of a holder table names (a dormant or/// retracted row's image), is named in `_media_key_names` — the names the/// `row_taken` hook writes for a file built through receipts, now for a file/// whose rows got there another way. Idempotent, and it only adds; a named/// key leaves the unlink queue. Answers how many names were new.////// What it cannot read back is a RETRACTED row's names: the fold drops the/// receipts below a retract, so the hook's names are their only record. A/// file that holds retracted rows keeps its index whole (snapshot, restore and/// take-over copy it with the file); a file built without one (the move)/// holds none.pub fn rebuild_names(db: &Driver) -> Result<usize> {    db.transaction(|db| {        let names = read_names(db, None, &|_| true)?;        insert_names(db, &names)    })}/// THE START STEP OF EVERY UNLINK PASS: the files whose index this process/// has rebuilt ([`rebuild_names`]), by file id. A pass that deletes bytes —/// the server's `media-unlink` and the client's unlink pass — asks/// [`IndexRebuilt::pending_file`] before it reads a file's queue, because a/// file moved by a build older than slice 7's store half holds an EMPTY/// `_media_key_names`, and its queue must be re-read against a whole index/// before anything drains: the rebuild names every key a row names, and/// [`insert_names`] takes each named key out of the queue (the queue's own/// "named again" rule). Each pass keeps one of these for the life of its/// process; a file whose rebuild FAILED is not remembered, and its queue is/// not drained until a later pass rebuilds it. Callers run/// [`NameSweep::rebuild_next`] with a fresh writer lock per page, and mark/// [`IndexRebuilt::finish`] only after the last page committed.#[derive(Debug, Default)]pub struct IndexRebuilt(std::sync::Mutex<BTreeSet<String>>);impl IndexRebuilt {    /// Identity needing a rebuild. Callers may read and write bounded pages,    /// releasing their file lock between them, before marking it finished.    pub fn pending_file(&self, db: &Driver) -> Result<Option<String>> {        let Some(file) = file_id(db)? else {            return Err(crate::error::StoreError::refused(                "the file has no identity, so its media-key index is not rebuilt and its unlink queue is not drained",            ));        };        let file = file.to_string();        Ok((!self.done().contains(&file)).then_some(file))    }    /// Mark only after every page committed; failures retry the additive sweep.    pub fn finish(&self, file: String) {        self.done().insert(file);    }    fn done(&self) -> std::sync::MutexGuard<'_, BTreeSet<String>> {        self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)    }}#[cfg(test)]#[path = "media_keys_tests.rs"]mod tests;