//! A replaced device file remains available until its replacement opens — //! and one left over from an earlier cycle never blocks the next: it goes //! when it holds nothing the live copy lacks ([`release_if_spent`]). use cotton_store::Driver; use std::path::{Path, PathBuf}; use crate::layout::Layout; pub(crate) const SUFFIX: &str = ".before-update"; pub(crate) fn path(replica: &Path) -> PathBuf { let mut name = replica.file_name().unwrap_or_default().to_os_string(); name.push(SUFFIX); replica.with_file_name(name) } pub(crate) fn check_copy(replica: &Path, copy: &Driver) -> cotton_store::Result<()> { let saved = path(replica); if !saved.exists() { return Ok(()); } let db = Driver::open_reader(saved)?; // Empty stores in an old incomplete file have no position to preserve, // even when their columns do not match this build's receipt index. let mut has_receipts = false; for table in ["_writes", "_tombstones"] { if db .get( "SELECT name FROM sqlite_master WHERE type='table' AND name=?", &[table.to_owned().into()], )? .is_some() { has_receipts |= db .get(&format!("SELECT 1 FROM {table} LIMIT 1"), &[])? .is_some(); } } if !has_receipts { return Ok(()); } // A filtered cut records the full source positions in _cursors. let arrived = cotton_store::cursors::seen_ceiling(copy)?; for (author, top) in cotton_store::cursors::cursor_ceiling(&db)? { if arrived.get(&author).is_none_or(|seen| seen < &top) { return Err(cotton_store::StoreError::refused( "the snapshot is older than this device's receipts; its previous copy is kept until a newer snapshot arrives" )); } } Ok(()) } /// The copy saved before an update leaves through the one function (QUEUE BAD OP 4): one holding anything unsent is /// kept aside, never removed. Only that file and its own files move (QUEUE BAD OP 5, item 3): the folder beside it /// holds the live copy, and is never moved. pub(crate) fn release(replica: &Path) { if let Err(error) = crate::copy_keep::retire_at(&path(replica), crate::copy_keep::Ending::keep("the copy saved before an update was spent")) { eprintln!("cotton-client: the copy saved before an update stays where it is ({error})"); } } /// RELEASE A LEFTOVER PREDECESSOR when it holds nothing the live copy lacks: /// the live copy is this device's own — claimed, stamped with this device's id /// — and every author's receipts in the predecessor are at or below what the /// live copy holds of that author ([`check_copy`]). A live copy not yet /// claimed keeps it: the claim reads its cursors and the crash check its /// presence. Answers whether it went (or there was none). pub(crate) fn release_if_spent(layout: &Layout, workspace_id: &str) -> bool { let replica = layout.replica(workspace_id); if !path(&replica).exists() { return true; } let Some(device_id) = crate::replica::known_device_id(layout) else { return false; }; let spent = Driver::open_reader(&replica).is_ok_and(|live| { cotton_store::meta::read_meta(&live).ok().flatten().is_some_and(|meta| meta.device_id == device_id) && check_copy(&replica, &live).is_ok() }); if spent { release(&replica); eprintln!("cotton-client: removed the previous copy of {workspace_id}: it held nothing the live copy lacks"); } spent } /// PUT BACK A COPY THE DELETED FALLBACK SET ASIDE — this device's own file, /// renamed beside the live name by a build whose failed move fetched a /// replacement (255 and earlier). With nothing at the live name the open took /// the no-file arm and fetched a whole copy over a phone that had one: the /// owner's 256 asked for 738 MB at launch (12 Oct 2026). A whole copy is only /// for a device with no file (architect, 12 Oct 2026, 256), and a file at the /// predecessor name is a file. /// /// So the predecessor goes back to its own name, and the set-aside's download /// in flight — partial bytes, a copy id the app's carrier would go on asking /// by — goes with the fetch that is no longer wanted. The move that follows /// takes it in place or stops on the honest page. /// /// Left alone while a WHOLE copy waits beside it: that is a re-hydrate killed /// between its rename and its swap (or a replacement already landed), which /// the bootstrap adopts and claims from the bytes on disk, with no request. /// Answers whether it put one back. pub(crate) fn restore_set_aside(layout: &Layout, workspace_id: &str) -> bool { let replica = layout.replica(workspace_id); let saved = path(&replica); if replica.exists() || !saved.exists() || whole_copy_beside(&replica) { return false; } // Moved through the one place a copy moves (QUEUE BAD OP 4): its journal with it, the file last. if let Err(error) = crate::copy_keep::relocate(&saved, &replica) { eprintln!("cotton-client: the set-aside copy of {workspace_id} was not put back ({error})"); return false; } super::sweep(&replica); // The set-aside's reason was its own cycle's; the move that follows // writes a new one if it still cannot take the copy. super::not_moved::clear(layout, workspace_id); eprintln!("cotton-client: put the set-aside copy of {workspace_id} back at its own name; its replacement download is dropped"); true } /// A whole copy beside the replica, waiting to be put in place without a /// request: a finished download. fn whole_copy_beside(replica: &Path) -> bool { use super::file::{download_path, expected_size_path, is_complete_download, parse_expected_size}; std::fs::metadata(download_path(replica)).is_ok_and(|info| { std::fs::read_to_string(expected_size_path(replica)) .is_ok_and(|promise| is_complete_download(info.len(), parse_expected_size(&promise))) }) }