//! H3: the one absolute path the data directory persists, rewritten when it //! moves. //! //! Everything else the data directory holds is relative or regenerated at start //! — `backup/litestream.yml`, the litestream shadow directories, //! `client/connection.json`, `role.json`, `imported.json`; the registry has no //! path column. The exception is `_media.local_path` in each client replica, //! which holds `/client/media/…`, so a move has to rewrite it: one //! UPDATE per replica, before the app opens any of them. //! //! Two files per workspace carry the column — the sync replica //! (`client//replica.db`) and the photos path's `client//life.db`. use std::path::{Path, PathBuf}; use rusqlite::Connection; /// The replica file names under `client//`. const REPLICA_FILES: [&str; 2] = ["replica.db", "life.db"]; #[derive(Debug, Clone, PartialEq, Eq)] pub struct RelocatedReplica { pub file: PathBuf, pub rows: usize, } #[derive(Debug, thiserror::Error)] pub enum RelocateError { #[error("{file}: {source}")] Sqlite { file: PathBuf, #[source] source: rusqlite::Error, }, #[error("{file}: {source}")] Marker { file: PathBuf, #[source] source: std::io::Error, }, } fn with_trailing_separator(path: &Path) -> String { let text = path.to_string_lossy().to_string(); if text.ends_with(std::path::MAIN_SEPARATOR) { text } else { format!("{text}{}", std::path::MAIN_SEPARATOR) } } fn has_media_table(conn: &Connection) -> Result { let count: i64 = conn.query_row( "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = '_media'", [], |row| row.get(0), )?; Ok(count > 0) } /// Move every `local_path` that sits under `previous_data_dir` to `data_dir`, /// answering how many rows changed. /// /// The comparison is on the prefix WITH its separator, so a sibling directory /// whose name merely starts with the same characters (`CottonDB-old` beside /// `CottonDB`) is left alone. `updated_at` is deliberately not touched: the row /// did not change state, the file moved, and `_media` is device-local anyway. pub fn rewrite_media_paths( conn: &Connection, previous_data_dir: &Path, data_dir: &Path, ) -> Result { let old_prefix = with_trailing_separator(previous_data_dir); let new_prefix = with_trailing_separator(data_dir); // `substr(x, 1, width)` counts CHARACTERS in SQLite, and so does // `String::chars().count()` — a byte length would cut a multi-byte folder // name in the middle and match nothing. let width = old_prefix.chars().count() as i64; conn.execute( "UPDATE _media SET local_path = :new_prefix || substr(local_path, :cut) WHERE local_path IS NOT NULL AND substr(local_path, 1, :width) = :old_prefix", rusqlite::named_params! { ":new_prefix": new_prefix, ":old_prefix": old_prefix, ":width": width, ":cut": width + 1, }, ) } /// Every client replica under a data directory, whether or not it holds /// `_media`. fn replica_files(data_dir: &Path) -> Vec { let client_dir = data_dir.join("client"); let Ok(entries) = std::fs::read_dir(&client_dir) else { return Vec::new(); }; let mut found: Vec = Vec::new(); for entry in entries.flatten() { if !entry.path().is_dir() { continue; } for name in REPLICA_FILES { let path = entry.path().join(name); if path.exists() { found.push(path); } } } // `read_dir` has no order; the answer this returns is reported to the person // as a count and read back by tests, so it is sorted rather than left to the // filesystem. found.sort(); found } /// Rewrite the media paths in every client replica the data directory holds. /// /// Called once, immediately after the data directory is renamed and before /// anything opens a replica. A database with no `_media` table is skipped rather /// than refused: the file is on an older schema, and the migrator will add the /// table empty when the app opens it. pub fn relocate_media( data_dir: &Path, previous_data_dir: &Path, ) -> Result, RelocateError> { let mut done = Vec::new(); for file in replica_files(data_dir) { let conn = Connection::open(&file).map_err(|source| RelocateError::Sqlite { file: file.clone(), source, })?; let has_media = has_media_table(&conn).map_err(|source| RelocateError::Sqlite { file: file.clone(), source, })?; if !has_media { continue; } let rows = rewrite_media_paths(&conn, previous_data_dir, data_dir).map_err(|source| { RelocateError::Sqlite { file: file.clone(), source, } })?; done.push(RelocatedReplica { file, rows }); } Ok(done) } /// A phone's open: rewrite the media paths when the data directory is not the /// one they were written for, then record that it is. /// /// A phone cannot keep one absolute path for its data: iOS may hand the app a /// different container path after an update, and the data moved out of the /// app group into the app's own container on 6 Oct 2026 (a lock held on a /// file in a shared container got the app killed at suspension, 0xDEAD10CC). /// The folder the rows name is `Layout::media_paths_root`; with no such file /// (every phone before this) it is `fallback_previous`, the app group's /// container the app moved the data out of. Called before anything opens a /// replica. A rewrite that fails leaves the marker as it was, so the next open /// tries again. pub fn follow_data_dir( data_dir: &Path, fallback_previous: Option<&Path>, ) -> Result, RelocateError> { let layout = crate::layout::Layout::new(data_dir); let marker = layout.media_paths_root(); let recorded = std::fs::read_to_string(&marker) .ok() .map(|text| PathBuf::from(text.trim_end_matches('\n'))) .filter(|path| !path.as_os_str().is_empty()); let previous = recorded.or_else(|| fallback_previous.map(Path::to_path_buf)); let done = match previous { Some(previous) if previous != data_dir => relocate_media(data_dir, &previous)?, _ => Vec::new(), }; // An error here is for the log, not a refusal: the rows are right for // this open, and the next one rewrites nothing already under this folder. std::fs::create_dir_all(layout.client_dir()) .and_then(|()| { let beside = layout.client_dir().join(".media-paths-root.tmp"); // not a copy: media files. std::fs::write(&beside, data_dir.to_string_lossy().as_bytes())?; // not a copy: media files. std::fs::rename(&beside, &marker) }) .map_err(|source| RelocateError::Marker { file: marker.clone(), source, })?; Ok(done) } #[cfg(test)] mod tests { use super::*; /// A replica with just the column under test — the full migrator is not the /// subject. Every fixture is synthetic. fn seed_replica(path: &Path, rows: &[(&str, Option)]) { std::fs::create_dir_all(path.parent().expect("a parent")).expect("the directory"); let conn = crate::test_support::open_fixture_db(path); conn.execute_batch( "CREATE TABLE _media (key TEXT PRIMARY KEY, local_path TEXT, state TEXT NOT NULL)", ) .expect("the table"); for (key, local_path) in rows { conn.execute( "INSERT INTO _media (key, local_path, state) VALUES (?1, ?2, 'synced')", rusqlite::params![key, local_path], ) .expect("the row"); } } fn local_paths(path: &Path) -> Vec> { let conn = crate::test_support::open_fixture_db(path); let mut statement = conn .prepare("SELECT local_path FROM _media ORDER BY key") .expect("the query"); let rows = statement .query_map([], |row| row.get::<_, Option>(0)) .expect("the rows") .collect::, _>>() .expect("the values"); rows } fn text(path: PathBuf) -> Option { Some(path.to_string_lossy().to_string()) } #[test] fn it_moves_exactly_the_rows_under_the_old_prefix_and_leaves_the_rest_alone() { let root = tempfile::tempdir().expect("a temp dir"); let old = root.path().join("old"); let now = root.path().join("new"); let replica = now.join("client").join("ws-1").join("replica.db"); seed_replica( &replica, &[ ("a", text(old.join("client/media/aa/one.jpg"))), ("b", text(now.join("client/media/bb/two.jpg"))), ("c", None), ], ); let conn = crate::test_support::open_fixture_db(&replica); assert_eq!( rewrite_media_paths(&conn, &old, &now).expect("the update"), 1 ); drop(conn); assert_eq!( local_paths(&replica), vec![ text(now.join("client/media/aa/one.jpg")), text(now.join("client/media/bb/two.jpg")), None, ] ); } #[test] fn it_does_not_rewrite_a_sibling_directory_that_merely_starts_with_the_same_characters() { let root = tempfile::tempdir().expect("a temp dir"); let old = root.path().join("CottonDB"); let now = root.path().join("moved"); let replica = root.path().join("replica.db"); seed_replica( &replica, &[( "a", text(root.path().join("CottonDB-old/client/media/x.jpg")), )], ); let conn = crate::test_support::open_fixture_db(&replica); assert_eq!( rewrite_media_paths(&conn, &old, &now).expect("the update"), 0 ); drop(conn); assert_eq!( local_paths(&replica), vec![text(root.path().join("CottonDB-old/client/media/x.jpg"))] ); } #[test] fn it_rewrites_every_client_replica_the_sync_replica_and_the_photos_path_s_life_db() { let root = tempfile::tempdir().expect("a temp dir"); let old = root.path().join("old"); let now = root.path().join("new"); let sync = now.join("client").join("ws-1").join("replica.db"); let photos = now.join("client").join("ws-1").join("life.db"); seed_replica(&sync, &[("a", text(old.join("client/media/aa/one.jpg")))]); seed_replica(&photos, &[("b", text(old.join("client/media/bb/two.jpg")))]); let done = relocate_media(&now, &old).expect("the relocation"); assert_eq!(done.iter().map(|entry| entry.rows).sum::(), 2); assert_eq!( local_paths(&sync), vec![text(now.join("client/media/aa/one.jpg"))] ); assert_eq!( local_paths(&photos), vec![text(now.join("client/media/bb/two.jpg"))] ); } #[test] fn it_does_nothing_at_all_when_the_data_dir_holds_no_client_replicas() { let root = tempfile::tempdir().expect("a temp dir"); assert_eq!( relocate_media(root.path(), &root.path().join("old")).expect("the relocation"), Vec::new() ); } #[test] fn it_skips_a_database_with_no_media_table_rather_than_failing() { let root = tempfile::tempdir().expect("a temp dir"); let now = root.path().join("new"); let replica = now.join("client").join("ws-1").join("replica.db"); std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the directory"); let conn = crate::test_support::open_fixture_db(&replica); conn.execute_batch("CREATE TABLE _meta (only_one INTEGER PRIMARY KEY)") .expect("the table"); drop(conn); assert_eq!( relocate_media(&now, &root.path().join("old")).expect("the relocation"), Vec::new() ); } #[test] fn a_phone_whose_data_left_the_app_group_rewrites_its_rows_once_and_records_the_folder() { let root = tempfile::tempdir().expect("a temp dir"); let group = root.path().join("Shared/AppGroup/G"); let own = root.path().join("Data/Application/A/Library/Application Support/Cotton"); let replica = own.join("client").join("ws-1").join("replica.db"); seed_replica(&replica, &[("a", text(group.join("client/media/aa/one.jpg")))]); let done = follow_data_dir(&own, Some(&group)).expect("the follow"); assert_eq!(done.iter().map(|entry| entry.rows).sum::(), 1); assert_eq!(local_paths(&replica), vec![text(own.join("client/media/aa/one.jpg"))]); let layout = crate::layout::Layout::new(&own); assert_eq!( std::fs::read_to_string(layout.media_paths_root()).expect("the marker"), own.to_string_lossy() ); // The second open has nothing to do, whatever the fallback says. assert!(follow_data_dir(&own, Some(&group)).expect("again").is_empty()); } #[test] fn a_container_that_moved_on_an_update_is_followed_from_the_recorded_folder() { let root = tempfile::tempdir().expect("a temp dir"); let before = root.path().join("Data/Application/A/Cotton"); let after = root.path().join("Data/Application/B/Cotton"); let replica = before.join("client").join("ws-1").join("replica.db"); seed_replica(&replica, &[("a", text(before.join("client/media/aa/one.jpg")))]); follow_data_dir(&before, None).expect("the first open"); std::fs::create_dir_all(after.parent().expect("a parent")).expect("the parent"); std::fs::rename(&before, &after).expect("the system moves the container"); let done = follow_data_dir(&after, None).expect("the open after the update"); assert_eq!(done.iter().map(|entry| entry.rows).sum::(), 1); assert_eq!( local_paths(&after.join("client").join("ws-1").join("replica.db")), vec![text(after.join("client/media/aa/one.jpg"))] ); } #[test] fn a_fresh_phone_rewrites_nothing_and_records_its_folder() { let root = tempfile::tempdir().expect("a temp dir"); let own = root.path().join("Cotton"); assert!(follow_data_dir(&own, Some(&root.path().join("group"))).expect("open").is_empty()); assert!(crate::layout::Layout::new(&own).media_paths_root().exists()); } }