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
9use crate::fs;
10use onestore::{Header, Stamp};
11use std::{
12 io,
13 path::{Path, PathBuf},
14 time::Duration,
15};
16use web_time::Instant;
17
18/// The file in a replica folder naming the location its replicas belong to.
19const LOCATION: &str = "location";
20
21/// The folder in `cache` holding the replicas of the sections at `location`.
22pub fn folder(cache: &Path, location: &str) -> PathBuf {
23 cache
24 .join("replicas")
25 .join(hex(&<sha2::Sha256 as sha2::Digest>::digest(location)[..16]))
26}
27
28/// The location of the local folder or file at `path`, which may have just been moved away:
29/// its canonical path, or its folder's with its name.
30pub fn local(path: &Path) -> io::Result<String> {
31 let canonical =
32 fs::canonicalize(path).or_else(|error| match (path.parent(), path.file_name()) {
33 (Some(parent), Some(name)) => Ok(fs::canonicalize(parent)?.join(name)),
34 _ => Err(error),
35 })?;
36 Ok(canonical.to_string_lossy().into_owned())
37}
38
39/// The location of the notebook folder `root` in `share` on the server at `address`, as its
40/// host names them.
41pub fn smb(address: &str, share: &str, root: &str) -> String {
42 let root = root.replace('\\', "/");
43 format!("smb://{address}/{share}/{}", root.trim_matches('/'))
44}
45
46/// Moves the replicas of the sections at `from` to `to`, with the images their publications
47/// keep (`published`), as when the app renames or moves a notebook; with them those of every
48/// location within it, as a copy of a section keeps its own. Each replica `to` already holds
49/// for the same section stays. Every replica moved must be closed.
50pub fn moved(cache: &Path, from: &str, to: &str) -> io::Result<()> {
51 if from == to {
52 return Ok(());
53 }
54 let inner = within(cache, from);
55 move_folder(cache, from, to)?;
56 for (_, location) in inner {
57 move_folder(
58 cache,
59 &location,
60 &format!("{to}{}", &location[from.len()..]),
61 )?;
62 }
63 Ok(())
64}
65
66/// Moves a notebook's replicas (and its copy-section replicas and discovery listing) from
67/// `from` to `to`, waiting up to `wait` for any closing section worker to release its cache.
68/// If `to` already holds a replica for the same section with no queued edits while `from`
69/// has queued edits, `from`'s replica replaces it so local changes survive; if both hold
70/// queued edits, returns `AlreadyExists` without moving anything.
71pub fn relocate(cache: &Path, from: &str, to: &str, wait: Duration) -> io::Result<()> {
72 if from == to {
73 return Ok(());
74 }
75 let deadline = Instant::now() + wait;
76 let mut locations = vec![(from.to_owned(), to.to_owned())];
77 for (_, location) in within(cache, from) {
78 let target = format!("{to}{}", &location[from.len()..]);
79 locations.push((location, target));
80 }
81
82 enum Action {
83 Adopt(PathBuf, PathBuf),
84 Replace(PathBuf, PathBuf),
85 DropOld(PathBuf),
86 }
87
88 struct FolderPlan {
89 old: PathBuf,
90 to: String,
91 actions: Vec<Action>,
92 }
93
94 let mut plan = Vec::new();
95 for (src, dst) in locations {
96 let old = folder(cache, &src);
97 if fs::metadata(&old).is_err() {
98 continue;
99 }
100 let new = folder(cache, &dst);
101 let mut actions = Vec::new();
102 for entry in fs::read_dir(&old)? {
103 let name = entry?.file_name();
104 if Path::new(&name).extension() != Some("sqlite".as_ref()) {
105 continue;
106 }
107 let old_file = old.join(&name);
108 let new_file = new.join(&name);
109 let old_queued = {
110 let connection = wait_closed(&old_file, deadline)?;
111 queued(&connection)
112 };
113 if fs::metadata(&new_file).is_ok() {
114 let new_queued = {
115 let connection = wait_closed(&new_file, deadline)?;
116 queued(&connection)
117 };
118 if old_queued > 0 && new_queued > 0 {
119 return Err(io::Error::new(
120 io::ErrorKind::AlreadyExists,
121 "The new location already has unsaved changes.",
122 ));
123 }
124 if old_queued > 0 {
125 actions.push(Action::Replace(old_file, new_file));
126 } else {
127 actions.push(Action::DropOld(old_file));
128 }
129 } else {
130 actions.push(Action::Adopt(old_file, new_file));
131 }
132 }
133 plan.push(FolderPlan {
134 old,
135 to: dst,
136 actions,
137 });
138 }
139
140 for folder_plan in plan {
141 if folder_plan
142 .actions
143 .iter()
144 .any(|action| matches!(action, Action::Adopt(..) | Action::Replace(..)))
145 {
146 claimed(cache, &folder_plan.to)?;
147 }
148 for action in folder_plan.actions {
149 match action {
150 Action::Adopt(old_file, new_file) => adopt(&old_file, &new_file)?,
151 Action::Replace(old_file, new_file) => {
152 crate::remove_replica(&new_file)?;
153 adopt(&old_file, &new_file)?;
154 }
155 Action::DropOld(old_file) => crate::remove_replica(&old_file)?,
156 }
157 }
158 tidy(&folder_plan.old);
159 }
160
161 let from_listing = crate::session::listing(cache, from);
162 let to_listing = crate::session::listing(cache, to);
163 if fs::metadata(&from_listing).is_ok() {
164 if fs::metadata(&to_listing).is_err() {
165 if let Some(parent) = to_listing.parent() {
166 fs::create_dir_all(parent)?;
167 }
168 fs::rename(&from_listing, &to_listing)?;
169 } else {
170 let _ = fs::remove_file(&from_listing);
171 }
172 }
173 Ok(())
174}
175
176/// Opens a closed replica, retrying while another holder releases it until `deadline`.
177fn wait_closed(path: &Path, deadline: Instant) -> io::Result<rusqlite::Connection> {
178 loop {
179 match crate::cache_connection(path) {
180 Ok(connection) => return Ok(connection),
181 Err(error) if error.busy() => {
182 if Instant::now() >= deadline {
183 return Err(io::Error::new(
184 io::ErrorKind::ResourceBusy,
185 "A section of this notebook is still busy; try again.",
186 ));
187 }
188 #[cfg(not(target_arch = "wasm32"))]
189 std::thread::sleep(Duration::from_millis(50));
190 }
191 Err(error) => return Err(io::Error::other(error.to_string())),
192 }
193 }
194}
195
196/// Number of queued edits in a closed replica; treats an unreadable schema conservatively as
197/// non-empty so it is never discarded.
198fn queued(connection: &rusqlite::Connection) -> u64 {
199 connection
200 .query_row("SELECT count(*) FROM edits", [], |row| row.get::<_, i64>(0))
201 .ok()
202 .and_then(|count| u64::try_from(count).ok())
203 .unwrap_or(1)
204}
205
206/// The folders of the locations within `location`, labelled, with their locations.
207fn within(cache: &Path, location: &str) -> Vec<(PathBuf, String)> {
208 let within = format!("{location}/");
209 fs::read_dir(cache.join("replicas"))
210 .into_iter()
211 .flatten()
212 .filter_map(|entry| {
213 let folder = entry.ok()?.path();
214 let label = fs::read_to_string(folder.join(LOCATION)).ok()?;
215 label.starts_with(&within).then_some((folder, label))
216 })
217 .collect()
218}
219
220fn move_folder(cache: &Path, from: &str, to: &str) -> io::Result<()> {
221 let old = folder(cache, from);
222 if fs::metadata(&old).is_err() {
223 return Ok(());
224 }
225 let new = claimed(cache, to)?;
226 for entry in fs::read_dir(&old)? {
227 let name = entry?.file_name();
228 if Path::new(&name).extension() == Some("sqlite".as_ref())
229 && fs::metadata(new.join(&name)).is_err()
230 {
231 adopt(&old.join(&name), &new.join(&name))?;
232 }
233 }
234 tidy(&old);
235 Ok(())
236}
237
238/// Deletes what the cache keeps of the notebook at `location`, as when the app deletes the
239/// notebook: its replicas, edits waiting in them included, its sections' copies' and its
240/// listing. Every replica must be closed.
241pub fn forget(cache: &Path, location: &str) -> io::Result<()> {
242 let own = folder(cache, location);
243 let ours = fs::read_to_string(own.join(LOCATION)).is_ok_and(|label| label == location);
244 for folder in ours.then_some(own).into_iter().chain(
245 within(cache, location)
246 .into_iter()
247 .map(|(folder, _)| folder),
248 ) {
249 fs::remove_dir_all(&folder)?;
250 }
251 match fs::remove_file(crate::session::listing(cache, location)) {
252 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
253 _ => Ok(()),
254 }
255}
256
257/// The folder for `location`, made and labelled with it where it was not.
258pub fn claimed(cache: &Path, location: &str) -> io::Result<PathBuf> {
259 let folder = folder(cache, location);
260 let label = folder.join(LOCATION);
261 if fs::metadata(&label).is_err() {
262 fs::create_dir_all(&folder)?;
263 fs::write(&label, location)?;
264 }
265 Ok(folder)
266}
267
268/// The folder for `location`, having moved into it a replica for each of `sections` it lacks
269/// from where one was left behind:
270///
271/// - the cache's top or its `smb` folder, where replicas were named by identity alone before
272/// locations named folders: taken by the first location to open the section, as that
273/// replica served whichever copy opened then;
274/// - the folder of a local location that no longer exists, as a notebook moved outside the
275/// app leaves: taken only when the section file, as `stamp` reads it, stands as the
276/// replica's base or has moved on from it (a later generation). A replica whose base is
277/// newer than the file, or a different state of the same generation, belongs to another
278/// copy of the section and stays.
279///
280/// A replica another process holds stays where it is.
281pub(crate) fn claim(
282 cache: &Path,
283 location: &str,
284 sections: &[[u8; 16]],
285 stamp: impl Fn(&[u8; 16]) -> Option<Stamp>,
286) -> io::Result<PathBuf> {
287 let folder = claimed(cache, location)?;
288 let missing: Vec<&[u8; 16]> = sections
289 .iter()
290 .filter(|identity| fs::metadata(crate::session::replica_file(&folder, identity)).is_err())
291 .collect();
292 if missing.is_empty() {
293 return Ok(folder);
294 }
295 let orphans = orphans(cache);
296 for identity in missing {
297 let legacy = [cache.to_owned(), cache.join("smb")]
298 .into_iter()
299 .map(|legacy| (crate::session::replica_file(&legacy, identity), true));
300 let left = orphans
301 .iter()
302 .map(|orphan| (crate::session::replica_file(orphan, identity), false));
303 for (replica, legacy) in legacy.chain(left) {
304 if fs::metadata(&replica).is_err() {
305 continue;
306 }
307 let adoptable = match crate::closed(&replica).and_then(|held| crate::peek(&held)) {
308 Ok((base, _)) => {
309 legacy || stamp(identity).is_some_and(|file| follows(&file, &base))
310 }
311 Err(error) if error.busy() => false,
312 // An older schema, which opening converts, predates locations.
313 Err(_) => legacy,
314 };
315 if adoptable {
316 adopt(&replica, &crate::session::replica_file(&folder, identity))?;
317 if let Some(parent) = replica.parent().filter(|_| !legacy) {
318 tidy(parent);
319 }
320 break;
321 }
322 }
323 }
324 Ok(folder)
325}
326
327/// The replica folders of local locations that no longer exist.
328fn orphans(cache: &Path) -> Vec<PathBuf> {
329 let Ok(entries) = fs::read_dir(cache.join("replicas")) else {
330 return Vec::new();
331 };
332 entries
333 .filter_map(|entry| {
334 let folder = entry.ok()?.path();
335 let location = fs::read_to_string(folder.join(LOCATION)).ok()?;
336 let path = Path::new(&location);
337 (path.is_absolute() && fs::metadata(path).is_err()).then_some(folder)
338 })
339 .collect()
340}
341
342/// Whether the section file standing as `file` may take a replica whose base is `base`.
343fn follows(file: &Stamp, base: &Stamp) -> bool {
344 file == base
345 || matches!(
346 (Header::parse(&file.header), Header::parse(&base.header)),
347 (Ok(file), Ok(base)) if file.generation > base.generation
348 )
349}
350
351/// Moves the replica at `from`, with the write-ahead log a crash may have left and the images
352/// its publications keep, to `to`.
353fn adopt(from: &Path, to: &Path) -> io::Result<()> {
354 for suffix in ["-wal", "-shm", ""] {
355 let (mut source, mut target) = (from.as_os_str().to_owned(), to.as_os_str().to_owned());
356 source.push(suffix);
357 target.push(suffix);
358 match fs::rename(&source, &target) {
359 Err(error) if !suffix.is_empty() && error.kind() == io::ErrorKind::NotFound => {}
360 moved => moved?,
361 }
362 }
363 match fs::rename(crate::published::folder(from), crate::published::folder(to)) {
364 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
365 _ => Ok(()),
366 }
367}
368
369/// Removes a replica folder that holds no replica, with the owner lock a crash may have left
370/// beside a cache moved away since (`crate::Owned`).
371fn tidy(folder: &Path) {
372 let Ok(entries) = fs::read_dir(folder).and_then(|entries| {
373 entries
374 .map(|entry| Ok(entry?.file_name()))
375 .collect::<io::Result<Vec<_>>>()
376 }) else {
377 return;
378 };
379 let left = |name: &std::ffi::OsString| {
380 name == LOCATION || name.to_string_lossy().ends_with(".sqlite-lock")
381 };
382 if entries.iter().all(left) {
383 for name in entries {
384 let _ = fs::remove_file(folder.join(name));
385 }
386 let _ = fs::remove_dir(folder);
387 }
388}
389
390fn hex(bytes: &[u8]) -> String {
391 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
392}