//! H2/H4: resolving the data directory, adopting the old one, and the two //! refusals. //! //! Runs BEFORE anything opens a file — before the single-instance check, before //! logging, before the server exists. The order matters: a refusal that arrives //! after a file is open is not a refusal. //! //! The table (spec 2026-09-07-mac-home-folder-data-dir-design): //! //! old is a data dir / new absent -> rename (same volume: atomic), then H3 //! old absent or not / new absent -> start fresh in ~/CottonDB //! anything / new present -> use ~/CottonDB; the old one is never read //! old is a data dir / new present -> refuse: two databases, and no guessing //! //! Adoption is skipped entirely when `COTTON_MAC_DATA_DIR` is set: an override //! is an explicit instruction (a rehearsal, a restore, a test), and moving the //! owner's real directory into a scratch run would be the opposite of one. use std::path::{Path, PathBuf}; use cotton_core::flavor::Flavor; use super::paths::{legacy_data_dir, resolve_data_dir}; use super::relocate_media::{relocate_media, RelocatedReplica}; use super::synced_location::{ read_file_provider_attribute, synced_location_refusal, synced_refusal_message, }; /// The three markers that make a directory THIS app's data directory. const DATA_DIR_MARKERS: [&str; 3] = ["role.json", "registry.db", "identity"]; /// Chromium's own state, as the OLD data directory held it. /// /// About 2 MB of caches, GPU shaders and a stale SingletonLock — never a byte of /// anybody's data. The rename carries the whole directory, so this folder would /// arrive in `~/CottonDB` and sit there for ever. Swept on the adoption path /// ONLY. It outlives Electron on purpose: the folder being adopted was written /// BY the Electron app, so the sweep is exactly as necessary after the Swift /// port as before it. const ELECTRON_STATE_DIR: &str = "electron"; /// `EXDEV`, the errno a rename across volumes fails with — 18 on both Darwin and /// Linux. Named here rather than pulled from `libc`: this crate takes no C /// dependency for one integer, and the number is part of the refusal's meaning. const EXDEV: i32 = 18; #[derive(Debug, Clone, PartialEq, Eq)] pub struct DataDirRefusal { pub title: String, pub message: String, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum PrepareDataDirResult { Ready { data_dir: PathBuf }, Refused { refusal: DataDirRefusal }, } impl PrepareDataDirResult { pub fn data_dir(&self) -> Option<&Path> { match self { Self::Ready { data_dir } => Some(data_dir), Self::Refused { .. } => None, } } } type AttributeReader = Box Option + Send + Sync>; type Renamer = Box std::io::Result<()> + Send + Sync>; type Remover = Box; type Relocator = Box Result, String> + Send + Sync>; type Logger = Box; /// What `prepare_data_dir` reaches the world through. Every one is injected so a /// test can make the move fail the way another volume does, and prove what was /// removed. pub struct PrepareOps { read_attribute: AttributeReader, rename: Renamer, remove: Remover, relocate: Relocator, log: Logger, } impl Default for PrepareOps { fn default() -> Self { Self::system() } } impl PrepareOps { /// The real ones: the extended attribute, `rename(2)`, a recursive remove, /// and the media-path rewrite. pub fn system() -> Self { Self { read_attribute: Box::new(read_file_provider_attribute), // not a copy: the whole data folder moved to its new home in one rename, every copy in it together. rename: Box::new(|from, to| std::fs::rename(from, to)), remove: Box::new(|path| { // not a copy: the old Electron app's state folder. let _ = std::fs::remove_dir_all(path); }), relocate: Box::new(|previous, data_dir| { relocate_media(data_dir, previous).map_err(|error| error.to_string()) }), log: Box::new(|_| ()), } } pub fn with_read_attribute( mut self, read: impl Fn(&Path) -> Option + Send + Sync + 'static, ) -> Self { self.read_attribute = Box::new(read); self } pub fn with_rename( mut self, rename: impl Fn(&Path, &Path) -> std::io::Result<()> + Send + Sync + 'static, ) -> Self { self.rename = Box::new(rename); self } pub fn with_remove(mut self, remove: impl Fn(&Path) + Send + Sync + 'static) -> Self { self.remove = Box::new(remove); self } pub fn with_relocate( mut self, relocate: impl Fn(&Path, &Path) -> Result, String> + Send + Sync + 'static, ) -> Self { self.relocate = Box::new(relocate); self } pub fn with_log(mut self, log: impl Fn(&str) + Send + Sync + 'static) -> Self { self.log = Box::new(log); self } } /// A directory is this app's data directory when it holds one of the three /// markers. pub fn is_data_dir(path: &Path) -> bool { if !path.exists() { return false; } DATA_DIR_MARKERS .iter() .any(|marker| path.join(marker).exists()) } /// Why `data_dir` is the OTHER app's folder, as the refusal `cotton_open` /// carries — or `None` when this app may use it. /// /// The rule is `cotton_core::flavor`'s ([`Flavor::refusal_for_data_dir`]: /// the other app's home folder, the real app's legacy folder, a trailing /// slash, a symlink); this only gives it a title. Asked by /// [`prepare_data_dir`] FIRST, and by `cotton_open` on its own when a caller /// says not to prepare — a folder that is not this app's is refused whether or /// not anything else about it is checked. pub fn foreign_folder_refusal(flavor: Flavor, home: &Path, data_dir: &Path) -> Option { let message = flavor.refusal_for_data_dir(home, data_dir)?; let title = match flavor { Flavor::Dev => "This folder is CottonDB's", Flavor::Business => "This folder belongs to another app", Flavor::Real => "This folder is Cotton Dev's", }; Some(DataDirRefusal { title: title.to_string(), message, }) } pub fn prepare_data_dir( flavor: Flavor, home: &Path, over: Option<&str>, ops: &PrepareOps, ) -> PrepareDataDirResult { let resolved = resolve_data_dir(flavor, home, over); // THE OTHER APP'S FOLDER, before anything else is asked of it — an // override included, because `COTTON_MAC_DATA_DIR=~/CottonDB` on a Cotton // Dev build is exactly the instruction this exists to refuse. if let Some(refusal) = foreign_folder_refusal(flavor, home, &resolved.path) { return PrepareDataDirResult::Refused { refusal }; } // H4 first, and for the override too: an explicit instruction is not a // licence to put somebody's database inside iCloud Drive. if let Some(synced) = synced_location_refusal(&resolved.path, home, &*ops.read_attribute) { return PrepareDataDirResult::Refused { refusal: DataDirRefusal { title: "CottonDB cannot use a synced folder".to_string(), message: synced_refusal_message(&synced, &resolved.path), }, }; } if resolved.overridden { (ops.log)(&format!( "cottondb-mac: using the data folder COTTON_MAC_DATA_DIR names — {}", resolved.path.display() )); return PrepareDataDirResult::Ready { data_dir: resolved.path, }; } // ADOPTION IS THE REAL APP'S ALONE. The legacy folder under Application // Support is CottonDB's history; Cotton Dev never lived there, and moving // it into `~/CottonDev` would carry the real household into a dev build. if flavor != Flavor::Real { return PrepareDataDirResult::Ready { data_dir: resolved.path, }; } let legacy = legacy_data_dir(home); let legacy_holds_data = is_data_dir(&legacy); let target_exists = resolved.path.exists(); if target_exists { if legacy_holds_data { return PrepareDataDirResult::Refused { refusal: DataDirRefusal { title: "CottonDB found two databases".to_string(), message: [ "There is a CottonDB folder in two places on this Mac:".to_string(), format!("{}\n{}", resolved.path.display(), legacy.display()), "The app will not guess which one is yours. Move or delete one of them, then open CottonDB again.".to_string(), ] .join("\n\n"), }, }; } return PrepareDataDirResult::Ready { data_dir: resolved.path, }; } if !legacy_holds_data { return PrepareDataDirResult::Ready { data_dir: resolved.path, }; } if let Err(error) = (ops.rename)(&legacy, &resolved.path) { let reason = if error.raw_os_error() == Some(EXDEV) { "your home folder is on another disk from where CottonDB used to keep its data, so the folder cannot simply be moved".to_string() } else { format!("the folder could not be moved ({error})") }; return PrepareDataDirResult::Refused { refusal: DataDirRefusal { title: "CottonDB could not move its data folder".to_string(), message: [ format!( "CottonDB now keeps your database at {}, and it tried to move the old folder there.", resolved.path.display() ), format!("{}", legacy.display()), format!("That did not work: {reason}."), "Nothing was changed or deleted. Move that folder yourself, then open CottonDB again.".to_string(), ] .join("\n\n"), }, }; } (ops.log)(&format!( "cottondb-mac: moved the data folder from {} to {}", legacy.display(), resolved.path.display() )); // The old app's own state came along with the rename and is of no use to // anything now, so dropping it here leaves the folder holding only the // person's data. Never touched on any other path: an existing `~/CottonDB` // and an overridden one are not ours to tidy. let electron_state = resolved.path.join(ELECTRON_STATE_DIR); if electron_state.exists() { (ops.remove)(&electron_state); (ops.log)(&format!( "cottondb-mac: removed the app's old cache folder that came with the move — {}", electron_state.display() )); } match (ops.relocate)(&legacy, &resolved.path) { Ok(rewritten) => { let rows: usize = rewritten.iter().map(|entry| entry.rows).sum(); if rows > 0 { (ops.log)(&format!( "cottondb-mac: pointed {rows} stored file path(s) at the new folder" )); } } // The move itself has already succeeded, so refusing here would leave a // moved folder and a person staring at an error — and the next launch // would take the "the new folder exists" path anyway. The failure is // said out loud instead, because its whole consequence is bounded and // self-healing: a stale `local_path` is a file the media drain fetches // again. Err(reason) => (ops.log)(&format!( "cottondb-mac: could not point the stored file paths at the new folder ({reason}) — the files are still there and will be fetched again" )), } PrepareDataDirResult::Ready { data_dir: resolved.path, } } #[cfg(test)] mod tests { use super::*; use std::sync::{Arc, Mutex}; // THE ADOPTION SUITE IS THE REAL APP'S: adoption is CottonDB's alone, so // every case below runs as it. Cotton Dev's own cases are at the end. fn prepare_data_dir(home: &Path, over: Option<&str>, ops: &PrepareOps) -> PrepareDataDirResult { super::prepare_data_dir(Flavor::Real, home, over, ops) } fn home_data_dir(home: &Path) -> PathBuf { super::super::paths::home_data_dir(Flavor::Real, home) } /// A directory that reads as a data directory: `role.json` is one of the /// three markers. Every fixture is synthetic. fn seed_data_dir(path: &Path) { std::fs::create_dir_all(path).expect("the directory"); std::fs::write(path.join("role.json"), r#"{"kind":"server"}"#).expect("the marker"); } /// Nothing on these temporary directories is ever synced. fn no_attribute() -> PrepareOps { PrepareOps::system().with_read_attribute(|_| None) } #[test] fn it_renames_the_old_directory_into_the_home_folder_and_rewrites_the_media_paths() { let home = tempfile::tempdir().expect("a temp home"); let legacy = legacy_data_dir(home.path()); seed_data_dir(&legacy); let moved: Arc>> = Arc::new(Mutex::new(Vec::new())); let seen = Arc::clone(&moved); let result = prepare_data_dir( home.path(), None, &no_attribute().with_relocate(move |previous, data_dir| { seen.lock() .expect("the record") .push((previous.to_path_buf(), data_dir.to_path_buf())); Ok(Vec::new()) }), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); assert!(home_data_dir(home.path()).join("role.json").exists()); assert!(!legacy.exists()); assert_eq!( moved.lock().expect("the record").clone(), vec![(legacy, home_data_dir(home.path()))] ); } #[test] fn it_drops_the_app_s_own_cache_folder_that_the_rename_carried_along() { let home = tempfile::tempdir().expect("a temp home"); let legacy = legacy_data_dir(home.path()); seed_data_dir(&legacy); // What the old data directory held beside the person's data. std::fs::create_dir_all(legacy.join("electron").join("Cache")).expect("the cache"); std::fs::write(legacy.join("electron").join("Cache").join("x"), "cached").expect("a file"); let result = prepare_data_dir( home.path(), None, &no_attribute().with_relocate(|_, _| Ok(Vec::new())), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); assert!(home_data_dir(home.path()).join("role.json").exists()); // The folder a person opens holds their data and nothing else. assert!(!home_data_dir(home.path()).join("electron").exists()); } #[test] fn it_leaves_an_existing_folder_s_own_cache_directory_alone_only_the_move_sweeps_one() { let home = tempfile::tempdir().expect("a temp home"); std::fs::create_dir_all(legacy_data_dir(home.path()).join("electron")) .expect("the old one"); seed_data_dir(&home_data_dir(home.path())); std::fs::create_dir_all(home_data_dir(home.path()).join("electron")).expect("the new one"); let result = prepare_data_dir( home.path(), None, &no_attribute().with_remove(|_| panic!("nothing may be removed when no move happened")), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); assert!(home_data_dir(home.path()).join("electron").exists()); } #[test] fn it_never_sweeps_an_overridden_folder_a_scratch_dir_is_not_ours_to_tidy() { let home = tempfile::tempdir().expect("a temp home"); let scratch = home.path().join("scratch"); std::fs::create_dir_all(scratch.join("electron")).expect("the scratch"); let result = prepare_data_dir( home.path(), Some(scratch.to_str().expect("a path")), &no_attribute().with_remove(|_| panic!("nothing may be removed under the override")), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: scratch.clone() } ); assert!(scratch.join("electron").exists()); } #[test] fn it_starts_fresh_when_there_is_no_old_directory_creating_nothing_itself() { let home = tempfile::tempdir().expect("a temp home"); let result = prepare_data_dir(home.path(), None, &no_attribute()); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); assert!(!home_data_dir(home.path()).exists()); } #[test] fn it_leaves_an_old_directory_that_is_not_a_data_dir_exactly_where_it_is() { let home = tempfile::tempdir().expect("a temp home"); let legacy = legacy_data_dir(home.path()); std::fs::create_dir_all(legacy.join("electron")).expect("the old one"); let result = prepare_data_dir(home.path(), None, &no_attribute()); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); assert!(legacy.join("electron").exists()); assert!(!home_data_dir(home.path()).exists()); } #[test] fn it_uses_the_home_folder_and_never_reads_the_old_one_once_the_new_one_exists() { let home = tempfile::tempdir().expect("a temp home"); let legacy = legacy_data_dir(home.path()); std::fs::create_dir_all(legacy.join("electron")).expect("the old one"); seed_data_dir(&home_data_dir(home.path())); let result = prepare_data_dir(home.path(), None, &no_attribute()); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); assert!(legacy.join("electron").exists()); } #[test] fn it_refuses_to_start_when_both_are_data_dirs_naming_both_paths() { let home = tempfile::tempdir().expect("a temp home"); seed_data_dir(&legacy_data_dir(home.path())); seed_data_dir(&home_data_dir(home.path())); let result = prepare_data_dir(home.path(), None, &no_attribute()); let PrepareDataDirResult::Refused { refusal } = result else { panic!("two data directories must refuse"); }; assert!(refusal .message .contains(&home_data_dir(home.path()).display().to_string())); assert!(refusal .message .contains(&legacy_data_dir(home.path()).display().to_string())); // Both are still there: a refusal deletes nothing. assert!(legacy_data_dir(home.path()).join("role.json").exists()); assert!(home_data_dir(home.path()).join("role.json").exists()); } #[test] fn it_refuses_with_the_reason_when_the_home_is_on_another_volume_rather_than_copying_gigabytes() { let home = tempfile::tempdir().expect("a temp home"); seed_data_dir(&legacy_data_dir(home.path())); let result = prepare_data_dir( home.path(), None, &no_attribute().with_rename(|_, _| Err(std::io::Error::from_raw_os_error(EXDEV))), ); let PrepareDataDirResult::Refused { refusal } = result else { panic!("a cross-volume move must refuse"); }; assert!(refusal.message.contains("another disk")); assert!(refusal .message .contains(&legacy_data_dir(home.path()).display().to_string())); assert!(legacy_data_dir(home.path()).join("role.json").exists()); } #[test] fn it_refuses_on_any_other_rename_failure_too_rather_than_starting_on_an_empty_database() { let home = tempfile::tempdir().expect("a temp home"); seed_data_dir(&legacy_data_dir(home.path())); let result = prepare_data_dir( home.path(), None, &no_attribute().with_rename(|_, _| { Err(std::io::Error::new( std::io::ErrorKind::PermissionDenied, "EACCES: permission denied", )) }), ); assert!(matches!(result, PrepareDataDirResult::Refused { .. })); } #[test] fn it_skips_adoption_entirely_when_the_override_names_the_directory() { let home = tempfile::tempdir().expect("a temp home"); seed_data_dir(&legacy_data_dir(home.path())); let scratch = home.path().join("scratch"); let result = prepare_data_dir( home.path(), Some(scratch.to_str().expect("a path")), &no_attribute(), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: scratch.clone() } ); assert!(legacy_data_dir(home.path()).join("role.json").exists()); assert!(!home_data_dir(home.path()).exists()); } #[test] fn the_synced_refusal_comes_first_and_refuses_before_touching_the_old_directory() { let home = tempfile::tempdir().expect("a temp home"); seed_data_dir(&legacy_data_dir(home.path())); let target = home_data_dir(home.path()); let result = prepare_data_dir( home.path(), None, &PrepareOps::system() .with_read_attribute(move |path| { (path == target).then(|| "com.apple.CloudDocs.iCloudDriveFileProvider/x".into()) }) .with_rename(|_, _| panic!("the rename must never be reached")), ); let PrepareDataDirResult::Refused { refusal } = result else { panic!("a synced folder must refuse"); }; assert!(refusal .message .contains(&home_data_dir(home.path()).display().to_string())); assert!(legacy_data_dir(home.path()).join("role.json").exists()); } #[test] fn the_synced_refusal_checks_the_override_too_an_instruction_is_not_a_licence() { let home = tempfile::tempdir().expect("a temp home"); let documents = home.path().join("Documents"); let scratch = documents.join("scratch"); let stamped = documents.clone(); let result = prepare_data_dir( home.path(), Some(scratch.to_str().expect("a path")), &PrepareOps::system().with_read_attribute(move |path| { (path == stamped).then(|| "com.apple.CloudDocs.iCloudDriveFileProvider/x".into()) }), ); let PrepareDataDirResult::Refused { refusal } = result else { panic!("a synced override must refuse"); }; assert!(refusal.message.contains(&documents.display().to_string())); } #[test] fn a_failed_media_rewrite_is_said_out_loud_and_the_app_still_starts() { let home = tempfile::tempdir().expect("a temp home"); seed_data_dir(&legacy_data_dir(home.path())); let lines: Arc>> = Arc::new(Mutex::new(Vec::new())); let said = Arc::clone(&lines); let result = prepare_data_dir( home.path(), None, &no_attribute() .with_relocate(|_, _| Err("replica.db: database is locked".to_string())) .with_log(move |line| said.lock().expect("the log").push(line.to_string())), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home_data_dir(home.path()) } ); let said = lines.lock().expect("the log").join("\n"); assert!(said.contains("could not point the stored file paths")); assert!(said.contains("database is locked")); } // ── Cotton Dev ──────────────────────────────────────────────────────── fn as_dev(home: &Path, over: Option<&str>) -> PrepareDataDirResult { super::prepare_data_dir(Flavor::Dev, home, over, &no_attribute()) } fn refused_naming(result: PrepareDataDirResult, folder: &Path) -> DataDirRefusal { let PrepareDataDirResult::Refused { refusal } = result else { panic!("the other app's folder must be refused, got {result:?}"); }; assert!( refusal.message.contains(&folder.display().to_string()), "the refusal names the folder: {}", refusal.message ); refusal } #[test] fn cotton_dev_opens_its_own_folder_and_never_adopts_the_real_app_s_old_one() { let home = tempfile::tempdir().expect("a temp home"); let legacy = legacy_data_dir(home.path()); seed_data_dir(&legacy); let result = super::super::prepare_data_dir( Flavor::Dev, home.path(), None, &no_attribute().with_rename(|_, _| panic!("Cotton Dev must never move a folder")), ); assert_eq!( result, PrepareDataDirResult::Ready { data_dir: home.path().join("CottonDev") } ); assert!(legacy.join("role.json").exists(), "the real app's folder is untouched"); assert!(!home.path().join("CottonDB").exists()); } #[test] fn cotton_dev_refuses_an_override_naming_the_real_app_s_folder() { let home = tempfile::tempdir().expect("a temp home"); let real = home.path().join("CottonDB"); seed_data_dir(&real); refused_naming(as_dev(home.path(), real.to_str()), &real); // The same folder, spelt with a trailing slash or a `.`, is the same folder. let slashed = format!("{}/", real.display()); let PrepareDataDirResult::Refused { .. } = as_dev(home.path(), Some(&slashed)) else { panic!("a trailing slash is the same folder"); }; let dotted = real.join("."); let PrepareDataDirResult::Refused { .. } = as_dev(home.path(), dotted.to_str()) else { panic!("`.` is the same folder"); }; // And the real app's legacy folder is the real app's too. let legacy = legacy_data_dir(home.path()); refused_naming(as_dev(home.path(), legacy.to_str()), &legacy); } #[test] fn cotton_dev_refuses_a_symlink_to_the_real_app_s_folder() { let home = tempfile::tempdir().expect("a temp home"); let real = home.path().join("CottonDB"); seed_data_dir(&real); let link = home.path().join("innocent-looking"); std::os::unix::fs::symlink(&real, &link).expect("the link"); refused_naming(as_dev(home.path(), link.to_str()), &link); } #[test] fn the_real_app_refuses_cotton_dev_s_folder_and_still_opens_its_own() { let home = tempfile::tempdir().expect("a temp home"); let dev = home.path().join("CottonDev"); let PrepareDataDirResult::Refused { refusal } = prepare_data_dir(home.path(), dev.to_str(), &no_attribute()) else { panic!("the real app must refuse Cotton Dev's folder"); }; assert!(refusal.message.contains(&dev.display().to_string())); assert_eq!( prepare_data_dir(home.path(), None, &no_attribute()), PrepareDataDirResult::Ready { data_dir: home.path().join("CottonDB") } ); } #[test] fn a_folder_that_is_neither_app_s_is_no_business_of_the_flavor_rule() { let home = tempfile::tempdir().expect("a temp home"); let scratch = home.path().join("scratch"); for flavor in Flavor::ALL { assert_eq!(foreign_folder_refusal(flavor, home.path(), &scratch), None); } } } /// The directory checks and its process lease precede adoption's first SQLite /// open. The caller retains the lease for the core's lifetime. #[derive(Debug)] pub enum LockedDataDirError { Refused(DataDirRefusal), Lock(cotton_store::process_lock::LockError), } pub fn prepare_locked_data_dir( flavor: Flavor, home: &Path, over: Option<&str>, ops: &PrepareOps, holder: cotton_store::process_lock::Holder, ) -> Result<(PathBuf, std::sync::Arc), LockedDataDirError> { let resolved = resolve_data_dir(flavor, home, over); if let Some(refusal) = foreign_folder_refusal(flavor, home, &resolved.path) { return Err(LockedDataDirError::Refused(refusal)); } if let Some(synced) = synced_location_refusal(&resolved.path, home, &*ops.read_attribute) { return Err(LockedDataDirError::Refused(DataDirRefusal { title: "CottonDB cannot use a synced folder".into(), message: synced_refusal_message(&synced, &resolved.path), })); } let legacy = legacy_data_dir(home); let before_adoption = if flavor == Flavor::Real && !resolved.overridden && !resolved.path.exists() && is_data_dir(&legacy) { &legacy } else { &resolved.path }; let lease = cotton_store::process_lock::ProcessLock::claim(before_adoption, holder).map_err(LockedDataDirError::Lock)?; match prepare_data_dir(flavor, home, over, ops) { PrepareDataDirResult::Ready { data_dir } => Ok((data_dir, lease)), PrepareDataDirResult::Refused { refusal } => Err(LockedDataDirError::Refused(refusal)), } }