//! One-shot removal of an observed unreadable phone copy. The old directory //! is retained whole, including SQLite sidecars; no serving file is touched. use super::client::ClientController; use serde_json::{json, Value}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::{LazyLock, Mutex}; use std::time::SystemTime; #[derive(Clone, PartialEq, Eq)] struct Fingerprint(Vec<(String, u64, Option)>); fn fingerprint(path: &Path) -> Option { let parent = path.parent()?; if !std::fs::symlink_metadata(parent).ok()?.is_dir() || !std::fs::symlink_metadata(path).ok()?.is_file() { return None; } let mut entries = Vec::new(); for entry in std::fs::read_dir(parent).ok()? { let entry = entry.ok()?; // The shared-memory index is a reader's lock/cache, not a new copy. // Diagnostic reads can change it; it is still kept by the rename. if entry.file_name().to_string_lossy().ends_with("-shm") { continue; } let meta = std::fs::symlink_metadata(entry.path()).ok()?; if meta.file_type().is_symlink() { return None; } entries.push(( entry.file_name().to_string_lossy().to_string(), meta.len(), meta.modified().ok(), )); } entries.sort(); Some(Fingerprint(entries)) } #[derive(Clone)] struct Offer { token: String, database: String, name: String, reason: String, stamp: Option, fingerprint: Fingerprint, } static OFFERS: LazyLock>>> = LazyLock::new(Default::default); /// Only a read that refused an existing held file creates an offer. Missing /// files are arriving. pub(crate) fn observe(client: &ClientController, id: &str, name: &str, reason: &str) { if !client .databases() .unwrap_or_default() .iter() .any(|held| held.id == id) { return; } let path = client.layout().replica(id); let stamp = super::database_files::stamp(&path).ok(); let Some(fingerprint) = fingerprint(&path) else { forget(client, id); return; }; let mut all = OFFERS.lock().unwrap_or_else(|error| error.into_inner()); let held = all.entry(client.layout().root().to_path_buf()).or_default(); if held .get(id) .is_some_and(|offer| offer.fingerprint == fingerprint) { return; } held.insert( id.into(), Offer { token: cotton_client::seams::uuid_v4(&cotton_client::seams::SystemRandom), database: id.into(), name: name.into(), reason: reason.into(), stamp, fingerprint, }, ); } pub(crate) fn forget(client: &ClientController, id: &str) { if let Some(held) = OFFERS .lock() .unwrap_or_else(|error| error.into_inner()) .get_mut(client.layout().root()) { held.remove(id); } } pub(crate) fn offers(client: &ClientController) -> Vec { let said = super::diagnostics::said(); let mut all = OFFERS.lock().unwrap_or_else(|error| error.into_inner()); let held = all.entry(client.layout().root().to_path_buf()).or_default(); held.retain(|id, offer| { fingerprint(&client.layout().replica(id)).as_ref() == Some(&offer.fingerprint) }); held.values() .map(|offer| { json!({ "token":offer.token,"databaseId":offer.database,"databaseName":offer.name, "filename":format!("{}/replica.db",offer.database),"schemaVersion":offer.stamp, "bundleId":said.bundle_id,"build":said.build, "reason":cotton_core::device::reported_state::redact_line(&offer.reason), }) }) .collect() } /// Consume before checking: a replay, stale button or invented target never /// removes a later file. The old copy and every sidecar stay together. pub(crate) fn remove(client: &ClientController, token: &str) -> Result { let offer = { let mut all = OFFERS.lock().unwrap_or_else(|error| error.into_inner()); let held = all.entry(client.layout().root().to_path_buf()).or_default(); let id = held .iter() .find(|(_, offer)| offer.token == token) .map(|(id, _)| id.clone()) .ok_or("This removal act is no longer offered.")?; held.remove(&id) .ok_or("This removal act was already used.")? }; let source = client.layout().replica(&offer.database); let kept = client .layout() .refused_copies_dir(&offer.database) .join(&offer.token); client.archive_refused_copy(&offer.database, &kept, || { if fingerprint(&source).as_ref() != Some(&offer.fingerprint) { return Err( "This copy changed since its refusal; read it again before removing it.".into(), ); } Ok(()) })?; Ok(kept) } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; const DATABASE: &str = "22222222-2222-4222-8222-222222222222"; fn fixture() -> (tempfile::TempDir, ClientController) { let dir = tempfile::tempdir().unwrap(); let layout = cotton_client::layout::Layout::new(dir.path()); std::fs::create_dir_all(layout.client_dir()).unwrap(); std::fs::write(layout.connection_json(), serde_json::to_vec(&json!({"mode":"local","baseUrl":"","workspaceId":"11111111-1111-4111-8111-111111111111","places":[{"id":DATABASE,"name":"Synthetic shared","available":true,"unavailableSince":null}]})).unwrap()).unwrap(); let path = layout.replica(DATABASE); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, b"synthetic unreadable copy").unwrap(); let client = ClientController::new( layout, Arc::new(crate::events::EventBus::new()), Some("Etc/UTC".into()), None, ); (dir, client) } /// RULE: Removing an unreadable copy is an offered, one-shot act; it keeps the entire original directory and cannot remove a replacement or be replayed. #[test] fn an_offered_act_keeps_the_original_and_cannot_be_replayed() { let (_dir, client) = fixture(); let source = client.layout().replica(DATABASE); let wal = source.with_extension("db-wal"); std::fs::write(&wal, b"synthetic sidecar").unwrap(); observe( &client, DATABASE, "Synthetic shared", "cannot read this file", ); let offer = offers(&client).pop().unwrap(); let token = offer["token"].as_str().unwrap(); let kept = remove(&client, token).unwrap(); assert!(!source.exists()); assert_eq!( std::fs::read(kept.join("replica.db")).unwrap(), b"synthetic unreadable copy" ); assert_eq!( std::fs::read(kept.join("replica.db-wal")).unwrap(), b"synthetic sidecar" ); std::fs::create_dir_all(source.parent().unwrap()).unwrap(); std::fs::write(&source, b"synthetic replacement").unwrap(); assert!(remove(&client, token).is_err()); assert_eq!(std::fs::read(source).unwrap(), b"synthetic replacement"); } /// RULE: An arriving copy has no removal act, and an offered act cannot remove a file changed since the refusal was observed. #[test] fn arrival_and_a_changed_file_are_never_removed() { let (_dir, client) = fixture(); let source = client.layout().replica(DATABASE); observe( &client, DATABASE, "Synthetic shared", "cannot read this file", ); let offer = offers(&client).pop().unwrap(); std::fs::write(&source, b"a changed synthetic copy").unwrap(); assert!(remove(&client, offer["token"].as_str().unwrap()).is_err()); assert_eq!(std::fs::read(&source).unwrap(), b"a changed synthetic copy"); std::fs::remove_file(source).unwrap(); observe(&client, DATABASE, "Synthetic shared", "arriving"); assert!(offers(&client).is_empty()); } /// RULE: A removal act never detaches a known unsent change from its live copy. #[test] fn a_known_unsent_change_keeps_the_live_copy() { let (_dir, client) = fixture(); let source = client.layout().replica(DATABASE); std::fs::remove_file(&source).unwrap(); let db = rusqlite::Connection::open(&source).unwrap(); db.execute_batch( "CREATE TABLE _outbox(op_id TEXT); INSERT INTO _outbox VALUES ('synthetic-unsent')", ) .unwrap(); drop(db); observe( &client, DATABASE, "Synthetic shared", "cannot read this file", ); let offer = offers(&client).pop().unwrap(); assert!(remove(&client, offer["token"].as_str().unwrap()).is_err()); assert!(source.exists()); let db = rusqlite::Connection::open(&source).unwrap(); assert_eq!( db.query_row("SELECT COUNT(*) FROM _outbox", [], |row| row .get::<_, i64>(0)) .unwrap(), 1 ); } }