Cotton code
122 lines · 4.9 KB · RustRaw
//! The names beside the replica while a snapshot is coming down, and what//! makes one of them adoptable.//!//! The port of `apps/cotton/src/replica/snapshotFile.ts`. Three pure rules and//! nothing else, because every one of them was a bug first://!//! * **[`parse_expected_size`]** — digits only. A sidecar holding anything//!   else is an unknown promise, which means re-download, never "assume it is//!   whole".//! * **[`is_complete_download`]** — a promise AND a match AND a non-zero size.//!   A zero-byte "whole" file is refused; a temp file LARGER than the promise//!   is not complete either.//! * **[`stale_downloads`]** — a `.download` pair (and the `.download.gz`//!   with its `.download.copy` that a resume asks by) survives only while the real//!   file is absent: that is the interrupted bootstrap the next launch//!   resumes. Once the real file exists the pair is rubbish, and every//!   pre-fix `.download-<random>` is rubbish always — a random name cannot be//!   resumed by anybody.//!//! **One deliberate difference from the phone's own layout.** The TypeScript//! kept every workspace's file in ONE directory as `life-<workspaceId>.db`, so//! its sweep matched a name pattern. Here the replica is//! `client/<workspaceId>/replica.db` ([`crate::layout::Layout::replica`]) —//! one directory per workspace — so the sweep is over THAT directory and the//! names are fixed rather than patterned. The rules are the same; the regex is//! not needed.use std::path::{Path, PathBuf};/// What a snapshot is written to before it is a database.pub const DOWNLOAD_SUFFIX: &str = ".download";/// Where the promised length is kept while it is being written.pub const EXPECTED_SUFFIX: &str = ".download.size";/// The gzip as it arrives, before it is whole and inflated.pub const GZIP_SUFFIX: &str = ".download.gz";/// Which copy the gzip is of, and its two sizes — what a resume asks by.pub const COPY_SUFFIX: &str = ".download.copy";/// The biggest integer the phone's own `Number.isSafeInteger` admits.////// Kept because the sidecar is a file BOTH clients may have written: a Rust/// build reading a file a TypeScript build wrote must agree with it about what/// is a number, or the two disagree about whether a download is whole.pub const MAX_SAFE_SIZE: u64 = 9_007_199_254_740_991;/// The temp file for a replica.pub fn download_path(replica: &Path) -> PathBuf {    with_suffix(replica, DOWNLOAD_SUFFIX)}/// The sidecar holding what the server promised.pub fn expected_size_path(replica: &Path) -> PathBuf {    with_suffix(replica, EXPECTED_SUFFIX)}fn with_suffix(replica: &Path, suffix: &str) -> PathBuf {    let mut name = replica        .file_name()        .map(|name| name.to_string_lossy().to_string())        .unwrap_or_default();    name.push_str(suffix);    replica.with_file_name(name)}/// What the sidecar promised, or `None` for a promise nobody can read.pub fn parse_expected_size(text: &str) -> Option<u64> {    let trimmed = text.trim();    if trimmed.is_empty() || !trimmed.bytes().all(|byte| byte.is_ascii_digit()) {        return None;    }    trimmed        .parse::<u64>()        .ok()        .filter(|value| *value <= MAX_SAFE_SIZE)}/// Is what is on disk the whole of what was promised?pub fn is_complete_download(temp_size: u64, expected: Option<u64>) -> bool {    matches!(expected, Some(expected) if expected > 0 && temp_size == expected)}/// The leftovers under a workspace's directory that are safe to delete.////// `exists` answers whether the LIVE file is there — the caller's question,/// asked here so this stays pure.pub fn stale_downloads(names: &[String], replica_name: &str, live_exists: bool) -> Vec<String> {    let download = format!("{replica_name}{DOWNLOAD_SUFFIX}");    let expected = format!("{replica_name}{EXPECTED_SUFFIX}");    let gzip = format!("{replica_name}{GZIP_SUFFIX}");    let copy = format!("{replica_name}{COPY_SUFFIX}");    // What the app's background download left beside a replica before the    // phone fetched every byte through the one transport (13 Oct 2026).    let landed = format!("{replica_name}.download.landed");    let head = format!("{replica_name}.download.landed.head");    names        .iter()        .filter(|name| {            if **name == download                || **name == expected                || **name == gzip                || **name == copy                || **name == landed                || **name == head            {                // What an interrupted download left — rubbish somebody's                // disk is holding once the real file is here.                return live_exists;            }            // Every pre-fix `.download-<random>`: unresumable by construction,            // because nothing can work out which attempt it belonged to.            name.starts_with(&format!("{download}-"))        })        .cloned()        .collect()}#[cfg(test)]#[path = "file_tests.rs"]mod tests;