| 1 | //! Where section replicas live in the app's cache: a folder per notebook location, then a |
| 2 | //! file per section identity. OneNote lets a notebook folder be copied with its sections |
| 3 | //! keeping their identities, so identity alone cannot tell a copy's replica from the |
| 4 | //! original's; the location keeps each copy's queue its own. |
| 5 | //! |
| 6 | //! A location is a string naming where a notebook or lone section is reached: the canonical |
| 7 | //! path of a local folder or file (`local`), or `smb` for one on a share. |
| 8 | |
| 9 | use crate::fs; |
| 10 | use onestore::{Header, Stamp}; |
| 11 | use std::{ |
| 12 | io, |
| 13 | path::{Path, PathBuf}, |
| 14 | }; |
| 15 | |
| 16 | /// The file in a replica folder naming the location its replicas belong to. |
| 17 | const LOCATION: &str = "location"; |
| 18 | |
| 19 | /// The folder in `cache` holding the replicas of the sections at `location`. |
| 20 | pub fn folder(cache: &Path, location: &str) -> PathBuf { |
| 21 | cache |
| 22 | .join("replicas") |
| 23 | .join(hex(&<sha2::Sha256 as sha2::Digest>::digest(location)[..16])) |
| 24 | } |
| 25 | |
| 26 | /// The location of the local folder or file at `path`, which may have just been moved away: |
| 27 | /// its canonical path, or its folder's with its name. |
| 28 | pub fn local(path: &Path) -> io::Result<String> { |
| 29 | let canonical = |
| 30 | fs::canonicalize(path).or_else(|error| match (path.parent(), path.file_name()) { |
| 31 | (Some(parent), Some(name)) => Ok(fs::canonicalize(parent)?.join(name)), |
| 32 | _ => Err(error), |
| 33 | })?; |
| 34 | Ok(canonical.to_string_lossy().into_owned()) |
| 35 | } |
| 36 | |
| 37 | /// The location of the notebook folder `root` in `share` on the server at `address`, as its |
| 38 | /// host names them. |
| 39 | pub fn smb(address: &str, share: &str, root: &str) -> String { |
| 40 | let root = root.replace('\\', "/"); |
| 41 | format!("smb://{address}/{share}/{}", root.trim_matches('/')) |
| 42 | } |
| 43 | |
| 44 | /// Moves the replicas of the sections at `from` to `to`, with the images their publications |
| 45 | /// keep (`published`), as when the app renames or moves a notebook; with them those of every |
| 46 | /// location within it, as a copy of a section keeps its own. Each replica `to` already holds |
| 47 | /// for the same section stays. Every replica moved must be closed. |
| 48 | pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> { |
| 49 | let inner = within(cache, from); |
| 50 | move_folder(cache, from, to)?; |
| 51 | for (_, location) in inner { |
| 52 | move_folder( |
| 53 | cache, |
| 54 | &location, |
| 55 | &format!("{to}{}", &location[from.len()..]), |
| 56 | )?; |
| 57 | } |
| 58 | Ok(()) |
| 59 | } |
| 60 | |
| 61 | /// The folders of the locations within `location`, labelled, with their locations. |
| 62 | fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> { |
| 63 | let within = format!("{location}/"); |
| 64 | fs::read_dir(cache.join("replicas")) |
| 65 | .into_iter() |
| 66 | .flatten() |
| 67 | .filter_map(|entry| { |
| 68 | let folder = entry.ok()?.path(); |
| 69 | let label = fs::read_to_string(folder.join(LOCATION)).ok()?; |
| 70 | label.starts_with(&within).then_some((folder, label)) |
| 71 | }) |
| 72 | .collect() |
| 73 | } |
| 74 | |
| 75 | fn move_folder(cache: &Path, from: &str, to: &str) -> io::Result<()> { |
| 76 | let old = folder(cache, from); |
| 77 | if fs::metadata(&old).is_err() { |
| 78 | return Ok(()); |
| 79 | } |
| 80 | let new = claimed(cache, to)?; |
| 81 | for entry in fs::read_dir(&old)? { |
| 82 | let name = entry?.file_name(); |
| 83 | if Path::new(&name).extension() == Some("sqlite".as_ref()) |
| 84 | && fs::metadata(new.join(&name)).is_err() |
| 85 | { |
| 86 | adopt(&old.join(&name), &new.join(&name))?; |
| 87 | } |
| 88 | } |
| 89 | tidy(&old); |
| 90 | Ok(()) |
| 91 | } |
| 92 | |
| 93 | /// Deletes what the cache keeps of the notebook at `location`, as when the app deletes the |
| 94 | /// notebook: its replicas, edits waiting in them included, its sections' copies' and its |
| 95 | /// listing. Every replica must be closed. |
| 96 | pub fn forget(cache: &Path, location: &str) -> io::Result<()> { |
| 97 | let own = folder(cache, location); |
| 98 | let ours = fs::read_to_string(own.join(LOCATION)).is_ok_and(|label| label == location); |
| 99 | for folder in ours.then_some(own).into_iter().chain( |
| 100 | within(cache, location) |
| 101 | .into_iter() |
| 102 | .map(|(folder, _)| folder), |
| 103 | ) { |
| 104 | fs::remove_dir_all(&folder)?; |
| 105 | } |
| 106 | match fs::remove_file(crate::session::listing(cache, location)) { |
| 107 | Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), |
| 108 | _ => Ok(()), |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// The folder for `location`, made and labelled with it where it was not. |
| 113 | pub fn claimed(cache: &Path, location: &str) -> io::Result<PathBuf> { |
| 114 | let folder = folder(cache, location); |
| 115 | let label = folder.join(LOCATION); |
| 116 | if fs::metadata(&label).is_err() { |
| 117 | fs::create_dir_all(&folder)?; |
| 118 | fs::write(&label, location)?; |
| 119 | } |
| 120 | Ok(folder) |
| 121 | } |
| 122 | |
| 123 | /// The folder for `location`, having moved into it a replica for each of `sections` it lacks |
| 124 | /// from where one was left behind: |
| 125 | /// |
| 126 | /// - the cache's top or its `smb` folder, where replicas were named by identity alone before |
| 127 | /// locations named folders: taken by the first location to open the section, as that |
| 128 | /// replica served whichever copy opened then; |
| 129 | /// - the folder of a local location that no longer exists, as a notebook moved outside the |
| 130 | /// app leaves: taken only when the section file, as `stamp` reads it, stands as the |
| 131 | /// replica's base or has moved on from it (a later generation). A replica whose base is |
| 132 | /// newer than the file, or a different state of the same generation, belongs to another |
| 133 | /// copy of the section and stays. |
| 134 | /// |
| 135 | /// A replica another process holds stays where it is. |
| 136 | pub(crate) fn claim( |
| 137 | cache: &Path, |
| 138 | location: &str, |
| 139 | sections: &[[u8; 16]], |
| 140 | stamp: impl Fn(&[u8; 16]) -> Option<Stamp>, |
| 141 | ) -> io::Result<PathBuf> { |
| 142 | let folder = claimed(cache, location)?; |
| 143 | let missing: Vec<&[u8; 16]> = sections |
| 144 | .iter() |
| 145 | .filter(|identity| fs::metadata(crate::session::replica_file(&folder, identity)).is_err()) |
| 146 | .collect(); |
| 147 | if missing.is_empty() { |
| 148 | return Ok(folder); |
| 149 | } |
| 150 | let orphans = orphans(cache); |
| 151 | for identity in missing { |
| 152 | let legacy = [cache.to_owned(), cache.join("smb")] |
| 153 | .into_iter() |
| 154 | .map(|legacy| (crate::session::replica_file(&legacy, identity), true)); |
| 155 | let left = orphans |
| 156 | .iter() |
| 157 | .map(|orphan| (crate::session::replica_file(orphan, identity), false)); |
| 158 | for (replica, legacy) in legacy.chain(left) { |
| 159 | if fs::metadata(&replica).is_err() { |
| 160 | continue; |
| 161 | } |
| 162 | let adoptable = match crate::closed(&replica).and_then(|held| crate::peek(&held)) { |
| 163 | Ok((base, _)) => { |
| 164 | legacy || stamp(identity).is_some_and(|file| follows(&file, &base)) |
| 165 | } |
| 166 | Err(error) if error.busy() => false, |
| 167 | // An older schema, which opening converts, predates locations. |
| 168 | Err(_) => legacy, |
| 169 | }; |
| 170 | if adoptable { |
| 171 | adopt(&replica, &crate::session::replica_file(&folder, identity))?; |
| 172 | if let Some(parent) = replica.parent().filter(|_| !legacy) { |
| 173 | tidy(parent); |
| 174 | } |
| 175 | break; |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | Ok(folder) |
| 180 | } |
| 181 | |
| 182 | /// The replica folders of local locations that no longer exist. |
| 183 | fn orphans(cache: &Path) -> Vec<PathBuf> { |
| 184 | let Ok(entries) = fs::read_dir(cache.join("replicas")) else { |
| 185 | return Vec::new(); |
| 186 | }; |
| 187 | entries |
| 188 | .filter_map(|entry| { |
| 189 | let folder = entry.ok()?.path(); |
| 190 | let location = fs::read_to_string(folder.join(LOCATION)).ok()?; |
| 191 | let path = Path::new(&location); |
| 192 | (path.is_absolute() && fs::metadata(path).is_err()).then_some(folder) |
| 193 | }) |
| 194 | .collect() |
| 195 | } |
| 196 | |
| 197 | /// Whether the section file standing as `file` may take a replica whose base is `base`. |
| 198 | fn follows(file: &Stamp, base: &Stamp) -> bool { |
| 199 | file == base |
| 200 | || matches!( |
| 201 | (Header::parse(&file.header), Header::parse(&base.header)), |
| 202 | (Ok(file), Ok(base)) if file.generation > base.generation |
| 203 | ) |
| 204 | } |
| 205 | |
| 206 | /// Moves the replica at `from`, with the write-ahead log a crash may have left and the images |
| 207 | /// its publications keep, to `to`. |
| 208 | fn adopt(from: &Path, to: &Path) -> io::Result<()> { |
| 209 | for suffix in ["-wal", "-shm", ""] { |
| 210 | let (mut source, mut target) = (from.as_os_str().to_owned(), to.as_os_str().to_owned()); |
| 211 | source.push(suffix); |
| 212 | target.push(suffix); |
| 213 | match fs::rename(&source, &target) { |
| 214 | Err(error) if !suffix.is_empty() && error.kind() == io::ErrorKind::NotFound => {} |
| 215 | moved => moved?, |
| 216 | } |
| 217 | } |
| 218 | match fs::rename(crate::published::folder(from), crate::published::folder(to)) { |
| 219 | Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), |
| 220 | _ => Ok(()), |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// Removes a replica folder that holds no replica, with the owner lock a crash may have left |
| 225 | /// beside a cache moved away since (`crate::Owned`). |
| 226 | fn tidy(folder: &Path) { |
| 227 | let Ok(entries) = fs::read_dir(folder).and_then(|entries| { |
| 228 | entries |
| 229 | .map(|entry| Ok(entry?.file_name())) |
| 230 | .collect::<io::Result<Vec<_>>>() |
| 231 | }) else { |
| 232 | return; |
| 233 | }; |
| 234 | let left = |name: &std::ffi::OsString| { |
| 235 | name == LOCATION || name.to_string_lossy().ends_with(".sqlite-lock") |
| 236 | }; |
| 237 | if entries.iter().all(left) { |
| 238 | for name in entries { |
| 239 | let _ = fs::remove_file(folder.join(name)); |
| 240 | } |
| 241 | let _ = fs::remove_dir(folder); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | fn hex(bytes: &[u8]) -> String { |
| 246 | bytes.iter().map(|byte| format!("{byte:02x}")).collect() |
| 247 | } |