mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-02 02:46:10 -06:00
A library's files were written by path, so a path that came to lead
somewhere else (a share mounted over the folder, the folder moved away and another put in its place) made the session write into that other folder: its catalog.snap and catalog.log were replaced, and dropping the lock removed the owner note of the program that had the library open. OpenedFolder records the folder's device and inode number (and when it was made, where the file system keeps that) when a library opens, and check() asks, with one stat, whether the path still leads to it. A drive or share mounted again gets another device number, and some file systems number their folders anew at every mount, so a folder also counts when it holds exactly the owner note this session's lock wrote (the lock vouches for it, and the note holds a value no other lock's note has), or when it has the same inode number and both creation times are known and equal; on the same device two different creation times are two folders, since an inode number is given again to a folder made later. FsStore (both stores of a library, the snapshot worker), the catalog log's thread and the lock's owner note ask before they write; a refusal is an ordinary write error that names the path, so the changes stay queued, the app says why they are unsaved, and saving goes on once the folder is back. The thumbnail cache gets a gate that the library closes the same way, and its takeover, prune and clear passes look at it every 256 files. The catalog log is opened by its path for each batch and appended to only while it is as long as what the thread wrote. A copy of the folder put at the path holds the note and counts as the library, but its log lacks what was written after the copy was made: it is refused like a failed write (reported, with later changes taken meanwhile), and the snapshot the app takes for held records replaces it, instead of going on writing into the folder that was moved away. A longer log is cut back only after a write of the thread's own failed. The lock removes the owner note only when it is the one it wrote, in the folder it locked. Reopening a path whose folder was replaced takes that folder's own lock instead of handing the old one over, so does the check_library preflight, and a lock taken in another folder than the stores recorded is refused. A Move import removes its originals only after the catalog log is on disk, not when it was handed to the log's thread. Windows reports no folder identity through std (nightly only): there the check only asks that a folder is still at the path.
This commit is contained in:
@@ -26,6 +26,7 @@ pub mod lock;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod log_writer;
|
||||
pub mod model;
|
||||
pub mod opened_folder;
|
||||
pub mod query;
|
||||
pub mod rules;
|
||||
pub mod safe_file;
|
||||
@@ -44,6 +45,7 @@ use lightcraft_develop::DevelopSettings;
|
||||
pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of};
|
||||
pub use lock::{LibraryLock, LockError, LockOwner};
|
||||
pub use model::*;
|
||||
pub use opened_folder::OpenedFolder;
|
||||
pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64};
|
||||
pub use rules::{Match, Rule, RuleSet};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -1543,6 +1545,8 @@ mod tests_lock;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_log_thread;
|
||||
#[cfg(test)]
|
||||
mod tests_opened_folder;
|
||||
#[cfg(test)]
|
||||
mod tests_repair;
|
||||
#[cfg(test)]
|
||||
mod tests_rule_order;
|
||||
|
||||
+87
-19
@@ -18,17 +18,26 @@
|
||||
//! descriptor frees the lock whatever copies a child still holds.
|
||||
//! - Who holds it (process id, computer, program, version) is written to `catalog.lock.owner`, for
|
||||
//! the error message. Only dropping the [`LibraryLock`] removes it, so a program that ends with
|
||||
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). It's a separate
|
||||
//! file because a Windows lock also blocks reading the locked file. It's only a hint: it may be
|
||||
//! missing or left over from a crash.
|
||||
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). Dropping
|
||||
//! removes only the note this lock wrote itself, with the bytes it wrote, and only while the
|
||||
//! path still leads to the folder it locked (a folder that holds exactly that note is it, whatever
|
||||
//! its numbers say: [`OpenedFolder::vouch`]): a note in another folder (a share mounted over the
|
||||
//! library's folder), or one another process wrote over ours, belongs to whoever has that library
|
||||
//! open (issue #3240). It's a separate file because a Windows lock also blocks reading the
|
||||
//! locked file. It's only a hint: it may be missing or left over from a crash. The note holds a
|
||||
//! value no other lock's note has ([`LockOwner::token`]), so no two folders hold the same note.
|
||||
//! - File systems without lock support (some network shares): the library opens unlocked, with a
|
||||
//! warning — refusing it would lock the user out of their own library. Locks over SMB/NFS are
|
||||
//! advisory and depend on the server; the owner file is then the only hint.
|
||||
//! - Browser storage (OPFS) has no file locks: see the web host for its own guard.
|
||||
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::hash::{BuildHasher, Hasher, RandomState};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::opened_folder::OpenedFolder;
|
||||
|
||||
/// The lock file in the library directory.
|
||||
pub const LOCK: &str = "catalog.lock";
|
||||
@@ -47,6 +56,10 @@ pub struct LockOwner {
|
||||
pub version: String,
|
||||
/// When it opened the library (seconds since 1970).
|
||||
pub since: u64,
|
||||
/// This lock's alone, also among those one process takes in the same second: the note is what
|
||||
/// tells the folder that was locked from every other ([`OpenedFolder::vouch`], issue #3240), so
|
||||
/// no two may be the same. A count of locks mixed with a random key. Not a secret.
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
impl LockOwner {
|
||||
@@ -58,6 +71,7 @@ impl LockOwner {
|
||||
program: program.to_string(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
since: web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0),
|
||||
token: lock_token(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +96,14 @@ fn host_name() -> String {
|
||||
env.or_else(|| std::fs::read_to_string("/etc/hostname").ok()).map(|h| h.trim().to_string()).filter(|h| !h.is_empty()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A value no other lock's note has ([`LockOwner::token`]).
|
||||
fn lock_token() -> String {
|
||||
static LOCKS: AtomicU64 = AtomicU64::new(0);
|
||||
let mut h = RandomState::new().build_hasher();
|
||||
h.write_u64(LOCKS.fetch_add(1, Ordering::Relaxed));
|
||||
format!("{:016x}", h.finish())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LockError {
|
||||
/// Another process has the library open.
|
||||
@@ -97,14 +119,20 @@ pub struct LibraryLock {
|
||||
/// `None` when the file system can't lock (the library is open unlocked).
|
||||
file: Option<File>,
|
||||
held: bool,
|
||||
/// The folder `dir` named when the lock was taken: the lock file and the owner note are in it
|
||||
/// (`None`: it couldn't be looked at).
|
||||
folder: Option<OpenedFolder>,
|
||||
/// The owner note as this lock wrote it (`None`: it wrote none).
|
||||
note: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl LibraryLock {
|
||||
/// Lock `dir` (which must exist) for this process. Fails only when another process holds it.
|
||||
pub fn acquire(dir: &Path, program: &str) -> Result<LibraryLock, LockError> {
|
||||
let folder = OpenedFolder::at(dir).ok();
|
||||
let unlocked = |why: io::Error| {
|
||||
log::warn!("library {}: can't lock {LOCK} ({why}); opening it without protection against a second program", dir.display());
|
||||
LibraryLock { dir: dir.to_path_buf(), file: None, held: false }
|
||||
LibraryLock { dir: dir.to_path_buf(), file: None, held: false, folder: folder.clone(), note: None }
|
||||
};
|
||||
let file = match OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join(LOCK)) {
|
||||
Ok(f) => f,
|
||||
@@ -118,15 +146,20 @@ impl LibraryLock {
|
||||
}
|
||||
Err(TryLockError::Error(e)) => return Ok(unlocked(e)),
|
||||
}
|
||||
// A new file in place of whatever is at the name: a link planted there in a library folder
|
||||
// someone else prepared is removed, never written through (as for the staging files, #1502).
|
||||
let owner = LockOwner::this_process(program);
|
||||
if let Ok(json) = serde_json::to_vec_pretty(&owner)
|
||||
&& let Err(e) = crate::store::create_staging(&dir.join(OWNER)).and_then(|mut f| f.write_all(&json))
|
||||
{
|
||||
log::warn!("library {}: can't write {OWNER}: {e}", dir.display());
|
||||
}
|
||||
Ok(LibraryLock { dir: dir.to_path_buf(), file: Some(file), held: true })
|
||||
let note = serde_json::to_vec_pretty(&LockOwner::this_process(program)).ok().and_then(|json| match write_note(dir, folder.as_ref(), &json) {
|
||||
Ok(()) => {
|
||||
// from now on the folder that holds this note is the locked one, whatever its numbers say
|
||||
if let Some(folder) = &folder {
|
||||
folder.vouch(&json);
|
||||
}
|
||||
Some(json)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("library {}: can't write {OWNER}: {e}", dir.display());
|
||||
None
|
||||
}
|
||||
});
|
||||
Ok(LibraryLock { dir: dir.to_path_buf(), file: Some(file), held: true, folder, note })
|
||||
}
|
||||
|
||||
/// The OS lock is held (`false`: the file system can't lock; opened unprotected).
|
||||
@@ -138,6 +171,16 @@ impl LibraryLock {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
/// The folder the lock was taken in, as `dir` named it then (`None`: it couldn't be looked at).
|
||||
pub fn folder(&self) -> Option<&OpenedFolder> {
|
||||
self.folder.as_ref()
|
||||
}
|
||||
|
||||
/// The owner note this lock wrote (`None`: it wrote none, so no folder is told by it).
|
||||
pub fn note(&self) -> Option<&[u8]> {
|
||||
self.note.as_deref()
|
||||
}
|
||||
|
||||
/// Another descriptor on the locked file: what a process spawned by another thread holds
|
||||
/// between fork and exec (a `dup` refers to the same open file description). Tests only (the
|
||||
/// test that uses it is Unix-only: `flock` semantics).
|
||||
@@ -145,17 +188,42 @@ impl LibraryLock {
|
||||
pub(crate) fn descriptor_copy(&self) -> Option<File> {
|
||||
self.file.as_ref().and_then(|f| f.try_clone().ok())
|
||||
}
|
||||
|
||||
/// Remove the owner note if it is this lock's: the path still leads to the folder the lock was
|
||||
/// taken in (or to one that holds this very note), and the note has the bytes this lock wrote
|
||||
/// there (issue #3240).
|
||||
fn remove_own_note(&self) {
|
||||
let Some(ours) = &self.note else { return };
|
||||
if self.folder.as_ref().is_some_and(|f| f.check().is_err()) {
|
||||
return;
|
||||
}
|
||||
let path = self.dir.join(OWNER);
|
||||
if crate::opened_folder::holds_exactly(&path, ours) {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the owner note into `dir`: a new file in place of whatever is at the name (a link planted
|
||||
/// there in a library folder someone else prepared is removed, never written through, as for the
|
||||
/// staging files, #1502), and only while `dir` still leads to the folder the lock file was opened in.
|
||||
fn write_note(dir: &Path, folder: Option<&OpenedFolder>, json: &[u8]) -> io::Result<()> {
|
||||
if let Some(folder) = folder {
|
||||
folder.check()?;
|
||||
}
|
||||
crate::store::create_staging(&dir.join(OWNER))?.write_all(json)
|
||||
}
|
||||
|
||||
impl Drop for LibraryLock {
|
||||
/// Remove the owner note while still holding the lock (so it can't delete the next holder's),
|
||||
/// then release the lock explicitly. Closing the handle isn't enough on Unix: `flock` lasts
|
||||
/// while any copy of the descriptor is open, and a process another thread is spawning holds a
|
||||
/// copy of every descriptor until it execs (issue #680). If the unlock fails the handle still
|
||||
/// closes right after, which releases the lock once every copy is gone, as before.
|
||||
/// Remove the owner note, if it is ours, while still holding the lock (so it can't delete the
|
||||
/// next holder's), then release the lock explicitly. Closing the handle isn't enough on Unix:
|
||||
/// `flock` lasts while any copy of the descriptor is open, and a process another thread is
|
||||
/// spawning holds a copy of every descriptor until it execs (issue #680). If the unlock fails
|
||||
/// the handle still closes right after, which releases the lock once every copy is gone, as
|
||||
/// before.
|
||||
fn drop(&mut self) {
|
||||
if self.held {
|
||||
let _ = std::fs::remove_file(self.dir.join(OWNER));
|
||||
self.remove_own_note();
|
||||
if let Some(f) = &self.file
|
||||
&& let Err(e) = f.unlock()
|
||||
{
|
||||
|
||||
@@ -17,6 +17,19 @@
|
||||
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
|
||||
//! everything handed over before; the caller waits for them. Dropping the writer waits for
|
||||
//! everything handed over and tries a last time.
|
||||
//!
|
||||
//! **Every write asks the [`OpenedFolder`] first**, on this thread (a `stat` never makes the caller
|
||||
//! wait for the drive): when the log's path no longer leads to the folder the store opened (a share
|
||||
//! mounted over it, issue #3240) nothing is written. The bytes are held like those of any other
|
||||
//! write that failed, and written once the folder that was opened is back at the path.
|
||||
//!
|
||||
//! **The log is opened by its path for each batch, never kept open.** A copy of the library's folder
|
||||
//! put at the path counts as the opened one (it holds the lock's note) and has a log of its own: a
|
||||
//! file kept open from before would go on writing into the folder that was moved away. A log that
|
||||
//! isn't as long as what this thread wrote (a fragment of its own failed write is cut first) is not
|
||||
//! the one it wrote, and appending to it would leave a gap: what it was handed is held like a failed
|
||||
//! write (reported; later appends are taken meanwhile, since retrying can't heal it), and the
|
||||
//! snapshot the app takes for held records, which holds every change, replaces the log.
|
||||
|
||||
use std::io::{self, Seek, Write};
|
||||
use std::path::PathBuf;
|
||||
@@ -24,6 +37,8 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::opened_folder::OpenedFolder;
|
||||
|
||||
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
/// How often held bytes are retried while a failure stands and nothing else arrives.
|
||||
@@ -45,6 +60,8 @@ struct Shared {
|
||||
failed: Option<String>,
|
||||
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
|
||||
held_records: usize,
|
||||
/// The file isn't the log the thread wrote: only a replace helps, so appends are taken.
|
||||
foreign: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct LogWriter {
|
||||
@@ -63,12 +80,12 @@ fn not_written(why: &str) -> io::Error {
|
||||
}
|
||||
|
||||
impl LogWriter {
|
||||
/// A writer for `dir/name` (`None` when no thread can start: the store then writes itself).
|
||||
pub(crate) fn start(dir: PathBuf, name: &str) -> Option<LogWriter> {
|
||||
/// A writer for `name` in the folder (`None` when no thread can start: the store then writes itself).
|
||||
pub(crate) fn start(folder: OpenedFolder, name: &str) -> Option<LogWriter> {
|
||||
let (tx, rx) = channel::<Msg>();
|
||||
let shared = Arc::new(Mutex::new(Shared::default()));
|
||||
let sh = shared.clone();
|
||||
let mut w = Writer::new(dir, name);
|
||||
let mut w = Writer::new(folder, name);
|
||||
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
|
||||
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
|
||||
}
|
||||
@@ -89,9 +106,11 @@ impl LogWriter {
|
||||
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
|
||||
/// be written: the caller keeps `data` and appends it again later.
|
||||
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
|
||||
if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() {
|
||||
return Err(not_written(&why));
|
||||
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(why) = sh.failed.as_deref().filter(|_| !sh.foreign) {
|
||||
return Err(not_written(why));
|
||||
}
|
||||
drop(sh);
|
||||
self.send(Msg::Append(data.to_vec()))
|
||||
}
|
||||
|
||||
@@ -133,17 +152,22 @@ impl Drop for LogWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread's side: the file and what is held for it.
|
||||
/// The thread's side: how much of the file is written, and what is held for it.
|
||||
struct Writer {
|
||||
dir: PathBuf,
|
||||
path: PathBuf,
|
||||
tmp: PathBuf,
|
||||
file: Option<std::fs::File>,
|
||||
/// The folder the store opened: asked before anything is written.
|
||||
folder: OpenedFolder,
|
||||
/// Bytes of the file written whole and synced (`None` until the file was first opened).
|
||||
good: Option<u64>,
|
||||
/// Handed over, not yet written and synced.
|
||||
held: Vec<u8>,
|
||||
failed: Option<String>,
|
||||
/// A write failed after the file was open: bytes of it may be past `good`, cut before the retry.
|
||||
torn: bool,
|
||||
/// The file isn't the log this thread wrote ([`Writer::open`]).
|
||||
foreign: bool,
|
||||
}
|
||||
|
||||
fn lines(b: &[u8]) -> usize {
|
||||
@@ -151,71 +175,60 @@ fn lines(b: &[u8]) -> usize {
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
fn new(dir: PathBuf, name: &str) -> Writer {
|
||||
fn new(folder: OpenedFolder, name: &str) -> Writer {
|
||||
let dir = folder.path().to_path_buf();
|
||||
let path = dir.join(name);
|
||||
let tmp = dir.join(format!("{name}.tmp"));
|
||||
Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None }
|
||||
Writer { dir, path, tmp, folder, good: None, held: Vec::new(), failed: None, torn: false, foreign: false }
|
||||
}
|
||||
|
||||
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
|
||||
crate::fault::check(&self.dir, step)
|
||||
}
|
||||
|
||||
/// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut).
|
||||
fn open(&mut self) -> io::Result<u64> {
|
||||
if let (Some(_), Some(g)) = (&self.file, self.good) {
|
||||
return Ok(g);
|
||||
}
|
||||
/// Open the file by its path, positioned at `good`, and say where that is. A fragment a failed
|
||||
/// write left past `good` is cut; any other length is not the log this thread wrote (a copy was
|
||||
/// put at the path, or it was changed): refused.
|
||||
fn open(&mut self) -> io::Result<(std::fs::File, u64)> {
|
||||
self.folder.check()?;
|
||||
// (a link or a device planted at the name meanwhile is refused, as at the first append)
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
|
||||
let len = f.metadata()?.len();
|
||||
let good = match self.good {
|
||||
None => len,
|
||||
Some(g) if len > g => {
|
||||
Some(g) if len == g => g,
|
||||
Some(g) if len > g && self.torn => {
|
||||
f.set_len(g)?;
|
||||
g
|
||||
}
|
||||
Some(g) if len < g => {
|
||||
// shorter than what was synced: someone else cut it; continue at its end
|
||||
log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display());
|
||||
len
|
||||
Some(g) => {
|
||||
self.foreign = true;
|
||||
return Err(io::Error::other(format!(
|
||||
"{} holds {len} bytes, the log this session wrote has {g}: it is another file, so nothing is appended to it and a snapshot replaces it",
|
||||
self.path.display()
|
||||
)));
|
||||
}
|
||||
Some(g) => g,
|
||||
};
|
||||
f.seek(io::SeekFrom::Start(good))?;
|
||||
self.good = Some(good);
|
||||
self.file = Some(f);
|
||||
Ok(good)
|
||||
self.foreign = false;
|
||||
Ok((f, good))
|
||||
}
|
||||
|
||||
/// Write and sync what is held.
|
||||
/// Write and sync what is held; a failure leaves `good` as it was, and the retry cuts what was left past it.
|
||||
fn write_held(&mut self) -> io::Result<()> {
|
||||
if self.held.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let r = (|| {
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
self.open()?;
|
||||
let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?;
|
||||
f.write_all(&self.held)?;
|
||||
self.hook(crate::fault::Step::Sync)?;
|
||||
self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data()
|
||||
})();
|
||||
match r {
|
||||
Ok(()) => {
|
||||
let n = self.held.len() as u64;
|
||||
self.good = Some(self.good.unwrap_or(0).saturating_add(n));
|
||||
self.held.clear();
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
// the handle may be dead (a network share that reconnected, a removed volume): the
|
||||
// retry opens the file again and cuts what this attempt left past `good`
|
||||
self.file = None;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
let (mut f, good) = self.open()?;
|
||||
let written = f.write_all(&self.held).and_then(|()| self.hook(crate::fault::Step::Sync)).and_then(|()| f.sync_data());
|
||||
self.torn = written.is_err();
|
||||
written?;
|
||||
self.good = Some(good.saturating_add(self.held.len() as u64));
|
||||
self.held.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cut the logical log (file then held) to `len` bytes.
|
||||
@@ -223,7 +236,7 @@ impl Writer {
|
||||
let good = match self.good {
|
||||
Some(g) => g,
|
||||
None => match self.open() {
|
||||
Ok(g) => g,
|
||||
Ok((_, g)) => g,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
@@ -237,7 +250,7 @@ impl Writer {
|
||||
self.held.truncate(keep);
|
||||
return Ok(());
|
||||
}
|
||||
self.file = None;
|
||||
self.folder.check()?;
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
|
||||
Ok(f) => f,
|
||||
@@ -256,7 +269,7 @@ impl Writer {
|
||||
}
|
||||
|
||||
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
|
||||
self.file = None;
|
||||
self.folder.check()?;
|
||||
let written = (|| {
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
let mut f = crate::store::create_staging(&self.tmp)?;
|
||||
@@ -273,6 +286,8 @@ impl Writer {
|
||||
self.good = Some(data.len() as u64);
|
||||
self.held.clear();
|
||||
self.failed = None;
|
||||
self.torn = false;
|
||||
self.foreign = false;
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -299,6 +314,7 @@ impl Writer {
|
||||
fn publish(&self, shared: &Mutex<Shared>) {
|
||||
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
|
||||
sh.foreign = self.foreign && sh.failed.is_some();
|
||||
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
//! The folder a library was opened from, and whether its path still leads to it (issue #3240).
|
||||
//!
|
||||
//! A library's files are written by path (`<library>/catalog.snap`, …), and a path can come to lead
|
||||
//! somewhere else while the library is open: a share mounted over the folder, or the folder moved
|
||||
//! away and another one put at its path. A session that went on writing then replaced the catalog
|
||||
//! of the library on the share with its own.
|
||||
//!
|
||||
//! [`OpenedFolder`] remembers which folder the path named when the library was opened;
|
||||
//! [`OpenedFolder::check`] asks, with one `stat`, whether it still does. Every write of a library
|
||||
//! file asks first ([`crate::FsStore`], its log thread, [`crate::LibraryLock`]) and is refused,
|
||||
//! writing nothing, when the answer is no. The refusal is an ordinary write error, so the changes
|
||||
//! stay queued and the app says why they aren't saved. The next write asks again: with the folder
|
||||
//! that was opened back at the path, saving goes on.
|
||||
//!
|
||||
//! - **Unix:** a folder is its device and inode number. A volume that is mounted again (a drive
|
||||
//! plugged in again, a share reconnected) gets another device number: its folder counts as the
|
||||
//! same when its inode number and its creation time agree (without one: the note below), so
|
||||
//! saving goes on there as it did before this check. A clone of the volume, with the same inode
|
||||
//! numbers and creation times, counts as that volume mounted again: nothing the check can see
|
||||
//! tells them apart. A folder moved away keeps its own inode number; one deleted and made again
|
||||
//! may be given the same inode number back, so on the same device two creation times that are
|
||||
//! both known must agree too.
|
||||
//! - **The note of the lock:** some file systems number a folder anew each time they are mounted
|
||||
//! (FAT and exFAT on Linux, sshfs, cifs without server inode numbers) and some keep no creation
|
||||
//! time to go by (NFS). A folder that holds exactly the owner note this session's lock wrote
|
||||
//! ([`OpenedFolder::vouch`]) is the opened folder whatever its numbers say: the note holds a
|
||||
//! value found in no other lock's note, so no other library has it. A copy of this library's
|
||||
//! folder made while it was open does, and counts as the library (the log in it is checked when
|
||||
//! it is written to: [`crate::FsStore`]); a share mounted over the folder, with a library of its
|
||||
//! own or none, never does.
|
||||
//! - **Windows:** `std` offers the volume serial number and the file index only on nightly
|
||||
//! (`windows_by_handle`, rust-lang/rust#63010), so there is no identity to compare yet. The check
|
||||
//! only asks that the path is still a folder, and a share mounted over a folder isn't noticed.
|
||||
//! - A check is not a lock: a folder replaced between the `stat` and the write that follows it is
|
||||
//! still written to. Closing that window takes I/O relative to an open directory handle
|
||||
//! (`openat`, `renameat`), which the library doesn't use.
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// Which folder a path named: the device and the inode number the system reports for it, and when
|
||||
/// the folder was made where the file system keeps that.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
struct FolderId {
|
||||
dev: u64,
|
||||
ino: u64,
|
||||
born: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl FolderId {
|
||||
#[cfg(unix)]
|
||||
fn of(folder: &std::fs::Metadata) -> Option<FolderId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Some(FolderId { dev: folder.dev(), ino: folder.ino(), born: made_at(folder.created()) })
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn of(_: &std::fs::Metadata) -> Option<FolderId> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `other` is the same folder: the same inode number, and then, where both creation
|
||||
/// times are known, the same creation time, else the same device number. A volume that is mounted
|
||||
/// again gets another device number, and saving went on there before there was a check; two
|
||||
/// creation times that differ are two folders, also on one device (an inode number is given
|
||||
/// again to a folder made later). Without both times another device is another folder: a
|
||||
/// refused save is better than a write into another volume's folder with that inode number.
|
||||
fn is(&self, other: &FolderId) -> bool {
|
||||
self.ino == other.ino
|
||||
&& match (self.born, other.born) {
|
||||
(Some(was), Some(now)) => was == now,
|
||||
_ => self.dev == other.dev,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a folder was made, where the file system says. macOS reports 0 (the Unix epoch) for a file
|
||||
/// system that keeps no creation time (NFS, macFUSE): the same for every folder there, so no folder
|
||||
/// is told from another by it.
|
||||
#[cfg(unix)]
|
||||
fn made_at(created: io::Result<SystemTime>) -> Option<SystemTime> {
|
||||
created.ok().filter(|t| *t != SystemTime::UNIX_EPOCH)
|
||||
}
|
||||
|
||||
/// The folder a library was opened from (see the module docs). Clones share one record, so the
|
||||
/// stores, the log's thread and the lock of a library all ask about the same folder.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OpenedFolder {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
path: PathBuf,
|
||||
/// `None` where the system gives a folder no identity (Windows, for now).
|
||||
id: Option<FolderId>,
|
||||
/// The last check refused: a change is logged when it starts and when it ends, not at every write.
|
||||
refused: AtomicBool,
|
||||
/// The owner note this session's lock wrote into the folder (see [`OpenedFolder::vouch`]); set once.
|
||||
note: OnceLock<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl OpenedFolder {
|
||||
/// The folder `path` names now (a link is followed). Fails when it names no folder.
|
||||
pub fn at(path: &Path) -> io::Result<OpenedFolder> {
|
||||
let folder = std::fs::metadata(path)?;
|
||||
if !folder.is_dir() {
|
||||
return Err(io::Error::other(format!("{} is not a folder", path.display())));
|
||||
}
|
||||
Ok(OpenedFolder::new(path, FolderId::of(&folder)))
|
||||
}
|
||||
|
||||
fn new(path: &Path, id: Option<FolderId>) -> OpenedFolder {
|
||||
OpenedFolder { inner: Arc::new(Inner { path: path.to_path_buf(), id, refused: AtomicBool::new(false), note: OnceLock::new() }) }
|
||||
}
|
||||
|
||||
/// The path the folder was opened by.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.inner.path
|
||||
}
|
||||
|
||||
/// `other` was recorded for the same folder (always, where folders have no identity). A folder
|
||||
/// that holds the note this session's lock wrote is the same whatever its numbers say
|
||||
/// ([`OpenedFolder::vouch`]): the library opened again after a drive was mounted again keeps its lock.
|
||||
pub fn same_folder(&self, other: &OpenedFolder) -> bool {
|
||||
match (self.inner.id, other.inner.id) {
|
||||
(Some(a), Some(b)) => a.is(&b) || self.holds_note(other.path()),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the owner note this session's lock wrote into the folder ([`crate::LibraryLock`]); the
|
||||
/// first one is kept. From then on a folder at the path that holds exactly these bytes is the
|
||||
/// opened folder even when its numbers say otherwise: some file systems number a folder anew at
|
||||
/// every mount (FAT and exFAT on Linux, sshfs), so a drive plugged in again would be refused for
|
||||
/// the rest of the session. The bytes are this lock's alone (the process, the program, the time
|
||||
/// it was taken and a value found in no other note): another library's folder doesn't have them
|
||||
/// (issue #3240), only a copy of this one made while it was open, which counts as it.
|
||||
pub fn vouch(&self, note: &[u8]) {
|
||||
let _ = self.inner.note.set(note.to_vec());
|
||||
}
|
||||
|
||||
/// The note [`OpenedFolder::vouch`] recorded (`None`: none was, the numbers decide alone).
|
||||
pub fn note(&self) -> Option<&[u8]> {
|
||||
self.inner.note.get().map(Vec::as_slice)
|
||||
}
|
||||
|
||||
/// `Ok` while the path leads to the folder that was opened (or to one that holds this session's
|
||||
/// note: [`OpenedFolder::vouch`]); else an error that says what is there now and what to do.
|
||||
pub fn check(&self) -> io::Result<()> {
|
||||
let inner = &*self.inner;
|
||||
let now = match std::fs::metadata(&inner.path) {
|
||||
Ok(now) => now,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(self.refuse("nothing is there now")),
|
||||
// The drive doesn't answer: the write would fail the same way, with less to go on.
|
||||
Err(e) => {
|
||||
let what = format!("can't tell whether {} is still the folder this library was opened from: {e}", inner.path.display());
|
||||
return Err(io::Error::new(e.kind(), what));
|
||||
}
|
||||
};
|
||||
if !now.is_dir() {
|
||||
return Err(self.refuse("it isn't a folder now"));
|
||||
}
|
||||
if let (Some(was), Some(is)) = (inner.id, FolderId::of(&now))
|
||||
&& !was.is(&is)
|
||||
&& !self.holds_note(&inner.path)
|
||||
{
|
||||
// (the same device number is the same volume's: another folder on it was put at the path)
|
||||
return Err(self.refuse(if was.dev == is.dev { "it was moved or replaced" } else { "a different drive or share is there now" }));
|
||||
}
|
||||
if inner.refused.swap(false, Ordering::Relaxed) {
|
||||
log::info!("library folder {}: the folder this library was opened from is back", inner.path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for a path that doesn't lead to the opened folder, `what` being what is there.
|
||||
fn refuse(&self, what: &str) -> io::Error {
|
||||
let path = self.inner.path.display();
|
||||
let why = format!(
|
||||
"{path} is no longer the folder this library was opened from ({what}), so nothing is written to it: put the original folder back"
|
||||
);
|
||||
if !self.inner.refused.swap(true, Ordering::Relaxed) {
|
||||
log::warn!("library folder {why}");
|
||||
}
|
||||
io::Error::other(why)
|
||||
}
|
||||
|
||||
/// Whether the folder at `dir` holds the note this session's lock wrote ([`OpenedFolder::vouch`]).
|
||||
fn holds_note(&self, dir: &Path) -> bool {
|
||||
self.note().is_some_and(|ours| holds_exactly(&dir.join(crate::lock::OWNER), ours))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is a plain file that holds exactly `bytes`. A link, a folder or a file of another
|
||||
/// size is no match and is not read (a pipe would block, a large file would be read for nothing).
|
||||
pub(crate) fn holds_exactly(path: &Path, bytes: &[u8]) -> bool {
|
||||
let plain = std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file() && m.len() == bytes.len() as u64);
|
||||
plain && std::fs::read(path).is_ok_and(|now| now == bytes)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
impl OpenedFolder {
|
||||
/// `path` as a volume that numbers its folders anew at every mount would have recorded it: other
|
||||
/// device and inode numbers than the folder has now, and no creation time (a mount can't be
|
||||
/// faked in a test).
|
||||
pub(crate) fn recorded_under_other_numbers(path: &Path) -> OpenedFolder {
|
||||
let now = std::fs::metadata(path).ok().and_then(|m| FolderId::of(&m));
|
||||
OpenedFolder::new(path, now.map(|n| FolderId { dev: n.dev.wrapping_add(1), ino: n.ino.wrapping_add(1), born: None }))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn scratch(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lc-opened-folder-unit-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn id(dev: u64, ino: u64, born: Option<u64>) -> FolderId {
|
||||
FolderId { dev, ino, born: born.map(|s| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(s)) }
|
||||
}
|
||||
|
||||
/// A folder is the same one when its inode number agrees and then its device number does or, where
|
||||
/// both creation times are known, its creation time: a volume that is mounted again has another
|
||||
/// device number, and an inode number is given again to a folder made later. Anything less sure
|
||||
/// is another folder.
|
||||
#[test]
|
||||
fn a_folder_on_a_volume_mounted_again_is_the_same_folder_only_when_it_was_made_at_the_same_time() {
|
||||
let was = id(7, 100, Some(1_000));
|
||||
assert!(was.is(&id(7, 100, Some(1_000))), "the same");
|
||||
assert!(!was.is(&id(7, 100, Some(2_000))), "the inode number of a folder that is gone, given to one made later");
|
||||
assert!(was.is(&id(9, 100, Some(1_000))), "mounted again under another device number");
|
||||
assert!(!was.is(&id(9, 100, Some(2_000))), "another volume's folder that has that inode number");
|
||||
assert!(!was.is(&id(9, 100, None)), "no creation time to tell by");
|
||||
assert!(!id(7, 100, None).is(&id(9, 100, None)), "none known at all");
|
||||
assert!(id(7, 100, None).is(&id(7, 100, None)), "the same device, and none to tell by");
|
||||
assert!(id(7, 100, None).is(&id(7, 100, Some(1_000))), "a creation time known for one folder only is no reason to refuse");
|
||||
assert!(!was.is(&id(7, 101, Some(1_000))), "another folder on the volume");
|
||||
assert!(!was.is(&id(9, 101, Some(1_000))), "another folder on another volume");
|
||||
}
|
||||
|
||||
/// The same rule in a check, with the device number recorded at open made different from the
|
||||
/// one reported now (a mount can't be faked in a test).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_check_accepts_a_remounted_volume_and_refuses_another_volumes_folder() {
|
||||
let dir = scratch("remount");
|
||||
let real = FolderId::of(&std::fs::metadata(&dir).unwrap()).unwrap();
|
||||
let recorded = |id: FolderId| OpenedFolder::new(&dir, Some(id));
|
||||
|
||||
let remounted = recorded(FolderId { dev: real.dev.wrapping_add(1), ..real });
|
||||
match real.born {
|
||||
Some(_) => remounted.check().expect("the same inode number and creation time: the same folder, mounted again"),
|
||||
None => assert!(remounted.check().is_err(), "no creation time to tell by: refused"),
|
||||
}
|
||||
let other = recorded(FolderId { dev: real.dev.wrapping_add(1), ino: real.ino.wrapping_add(1), ..real });
|
||||
let msg = other.check().expect_err("another volume's folder").to_string();
|
||||
assert!(msg.contains("a different drive or share is there now"), "{msg}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The same rule in a check, with the creation time recorded at open made different from the one
|
||||
/// reported now (a folder made again under the inode number of one that was deleted can't be
|
||||
/// arranged in a test): the same device and inode number with another creation time is another
|
||||
/// folder, unless it holds the note this session's lock wrote.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_made_again_under_the_same_inode_number_is_another_folder_unless_it_holds_the_note() {
|
||||
let dir = scratch("made-again");
|
||||
let real = FolderId::of(&std::fs::metadata(&dir).unwrap()).unwrap();
|
||||
let Some(born) = real.born else {
|
||||
OpenedFolder::new(&dir, Some(real)).check().expect("no creation time to tell by: the numbers decide");
|
||||
return;
|
||||
};
|
||||
let earlier = OpenedFolder::new(&dir, Some(FolderId { born: Some(born + std::time::Duration::from_secs(3600)), ..real }));
|
||||
let msg = earlier.check().expect_err("the same numbers, made at another time").to_string();
|
||||
assert!(msg.contains("it was moved or replaced"), "{msg}");
|
||||
assert!(!earlier.same_folder(&OpenedFolder::at(&dir).unwrap()), "not the folder that lock was taken in");
|
||||
|
||||
let note = b"the note of the lock";
|
||||
earlier.vouch(note);
|
||||
std::fs::write(dir.join(crate::lock::OWNER), note).unwrap();
|
||||
earlier.check().expect("this session's note: the folder it locked, whatever its numbers say");
|
||||
assert!(earlier.same_folder(&OpenedFolder::at(&dir).unwrap()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// macOS reports a creation time of 0 for a file system that keeps none (NFS, macFUSE), the same
|
||||
/// for every folder on it: that is no creation time, or any two such folders that have an inode
|
||||
/// number in common would be taken for one folder mounted again.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_creation_time_of_zero_is_no_creation_time() {
|
||||
let made = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
assert_eq!(made_at(Ok(made)), Some(made));
|
||||
assert_eq!(made_at(Ok(SystemTime::UNIX_EPOCH)), None);
|
||||
assert_eq!(made_at(Err(io::Error::other("this file system keeps none"))), None);
|
||||
}
|
||||
|
||||
/// A file system that numbers its folders anew at every mount (FAT and exFAT on Linux, sshfs)
|
||||
/// gives a folder that was opened other numbers: it is that folder when it holds the note this
|
||||
/// session's lock wrote, and no other folder is. (A mount can't be faked in a test: the numbers
|
||||
/// recorded at open are made different from the folder's.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_with_other_numbers_is_the_opened_one_only_while_it_holds_the_note_the_lock_wrote() {
|
||||
let dir = scratch("note");
|
||||
let note = br#"{"pid":4242,"host":"here","program":"LightCraft","version":"0.2.0","since":1}"#;
|
||||
let renumbered = OpenedFolder::recorded_under_other_numbers(&dir);
|
||||
let msg = renumbered.check().expect_err("other numbers, and no note vouched for").to_string();
|
||||
assert!(msg.contains("a different drive or share is there now"), "{msg}");
|
||||
|
||||
renumbered.vouch(note);
|
||||
assert_eq!(renumbered.note(), Some(note.as_slice()));
|
||||
let path = dir.join(crate::lock::OWNER);
|
||||
assert!(renumbered.check().is_err(), "the note is vouched for, the folder holds none");
|
||||
let longer = [note.as_slice(), b" ".as_slice()].concat();
|
||||
for other in [note.to_ascii_uppercase(), longer, note[1..].to_vec(), Vec::new()] {
|
||||
std::fs::write(&path, &other).unwrap();
|
||||
assert!(renumbered.check().is_err(), "another note: {}", String::from_utf8_lossy(&other));
|
||||
}
|
||||
std::fs::write(&path, note).unwrap();
|
||||
renumbered.check().expect("this session's note: the folder it locked, whatever its numbers say");
|
||||
|
||||
// what is no note: a link to one, a folder
|
||||
let elsewhere = dir.join("elsewhere");
|
||||
std::fs::rename(&path, &elsewhere).unwrap();
|
||||
std::os::unix::fs::symlink(&elsewhere, &path).unwrap();
|
||||
assert!(renumbered.check().is_err(), "a link to the bytes is no note");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
assert!(renumbered.check().is_err(), "a folder is no note");
|
||||
|
||||
// the first note is the one that counts
|
||||
renumbered.vouch(b"another");
|
||||
assert_eq!(renumbered.note(), Some(note.as_slice()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The lock is handed over to a library opened again from the same folder, and a folder that
|
||||
/// holds the note this session's lock wrote is that folder whatever its numbers say (a drive
|
||||
/// that was mounted again): not one with no such note.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_that_holds_the_locks_note_is_the_same_folder_for_the_hand_over() {
|
||||
let dir = scratch("hand-over");
|
||||
let other = scratch("hand-over-other");
|
||||
let note = b"the note of the lock";
|
||||
let at_open = OpenedFolder::recorded_under_other_numbers(&dir);
|
||||
let now = OpenedFolder::at(&dir).unwrap();
|
||||
assert!(!at_open.same_folder(&now), "other numbers, no note");
|
||||
|
||||
at_open.vouch(note);
|
||||
assert!(!at_open.same_folder(&now), "the note is vouched for, the folder holds none");
|
||||
std::fs::write(dir.join(crate::lock::OWNER), note).unwrap();
|
||||
assert!(at_open.same_folder(&now));
|
||||
assert!(!at_open.same_folder(&OpenedFolder::at(&other).unwrap()), "another folder holds no such note");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&other);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,16 @@
|
||||
//!
|
||||
//! [`FsStore`] is the native implementation (a library directory); [`MemStore`] keeps files in
|
||||
//! memory (tests, ephemeral sessions) and lets tests simulate crashes by editing the bytes. A web
|
||||
//! host can implement [`Store`] over OPFS.
|
||||
//! host can implement [`Store`] over OPFS. [`FsStore`] writes only while its directory still leads
|
||||
//! to the folder it opened ([`crate::OpenedFolder`], issue #3240).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::opened_folder::OpenedFolder;
|
||||
|
||||
/// A flat namespace of named files with the few operations the journal needs.
|
||||
pub trait Store: Send {
|
||||
/// The whole file, or `None` if it doesn't exist.
|
||||
@@ -73,6 +76,9 @@ pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
/// Files in a directory.
|
||||
pub struct FsStore {
|
||||
dir: PathBuf,
|
||||
/// The folder `dir` named when the store was opened. Every write asks it first and is refused
|
||||
/// when `dir` leads somewhere else now (issue #3240); so does the log's thread.
|
||||
folder: OpenedFolder,
|
||||
/// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread
|
||||
/// writes the log (the browser build, or one that couldn't start).
|
||||
appender: Option<(String, std::fs::File)>,
|
||||
@@ -82,15 +88,26 @@ pub struct FsStore {
|
||||
}
|
||||
|
||||
impl FsStore {
|
||||
/// Use `dir` (created if missing).
|
||||
/// Use `dir` (created if missing). The store writes to the folder `dir` names now, and only
|
||||
/// while it still does.
|
||||
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
|
||||
std::fs::create_dir_all(dir.as_ref())?;
|
||||
Ok(FsStore {
|
||||
dir: dir.as_ref().to_path_buf(),
|
||||
Ok(FsStore::in_folder(OpenedFolder::at(dir.as_ref())?))
|
||||
}
|
||||
/// A store in a folder that was recorded already, so that the stores, the lock and the caches
|
||||
/// of one library ask about the same folder.
|
||||
pub fn in_folder(folder: OpenedFolder) -> FsStore {
|
||||
FsStore {
|
||||
dir: folder.path().to_path_buf(),
|
||||
folder,
|
||||
appender: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
log: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// The folder the store opened.
|
||||
pub fn folder(&self) -> &OpenedFolder {
|
||||
&self.folder
|
||||
}
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
@@ -155,6 +172,7 @@ impl Store for FsStore {
|
||||
self.sync_dir();
|
||||
return Ok(());
|
||||
}
|
||||
self.folder.check()?;
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
}
|
||||
@@ -180,6 +198,7 @@ impl Store for FsStore {
|
||||
self.sync_dir();
|
||||
return Ok(buf.len() as u64);
|
||||
}
|
||||
self.folder.check()?;
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
}
|
||||
@@ -209,6 +228,7 @@ impl Store for FsStore {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if self.log.is_none() && !crate::fault::on_caller(&self.dir) {
|
||||
self.folder.check()?;
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
if !self.path(name).exists() {
|
||||
// created here, so the open's errors are this append's and its entry is durable
|
||||
@@ -216,13 +236,14 @@ impl Store for FsStore {
|
||||
self.sync_dir();
|
||||
}
|
||||
self.appender = None;
|
||||
self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name);
|
||||
self.log = crate::log_writer::LogWriter::start(self.folder.clone(), name);
|
||||
}
|
||||
// (another name than the log's is written here, as without a thread)
|
||||
if let Some(w) = self.log_for(name) {
|
||||
return w.append(data);
|
||||
}
|
||||
}
|
||||
self.folder.check()?;
|
||||
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
let existed = self.path(name).exists();
|
||||
@@ -254,6 +275,7 @@ impl Store for FsStore {
|
||||
if let Some(w) = self.log_for(name) {
|
||||
return w.truncate(len);
|
||||
}
|
||||
self.folder.check()?;
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
}
|
||||
@@ -274,7 +296,7 @@ impl Store for FsStore {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn background_writer(&self) -> Option<Box<dyn Store>> {
|
||||
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None }))
|
||||
Some(Box::new(FsStore { dir: self.dir.clone(), folder: self.folder.clone(), appender: None, log: None }))
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
|
||||
@@ -84,6 +84,41 @@ fn a_link_at_the_owner_note_is_never_written_through() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The note is what tells the folder that was locked from every other folder (issue #3240), so no two
|
||||
/// locks write the same one, also when one process takes them in the same second. A note written
|
||||
/// before it had a value of its own is still read.
|
||||
#[test]
|
||||
fn every_lock_writes_a_note_of_its_own() {
|
||||
let notes: std::collections::HashSet<Vec<u8>> =
|
||||
(0..2_000).map(|_| serde_json::to_vec_pretty(&LockOwner::this_process("LightCraft")).unwrap()).collect();
|
||||
assert_eq!(notes.len(), 2_000, "one note for each lock");
|
||||
let old: LockOwner = serde_json::from_slice(br#"{"pid":7,"host":"elsewhere","program":"LightCraft","version":"0.2.0","since":1}"#).unwrap();
|
||||
assert!(old.pid == 7 && old.token.is_empty());
|
||||
}
|
||||
|
||||
/// Two libraries locked by one process in the same second: the folder of the second, put at the
|
||||
/// path of the first, doesn't hold the first lock's note, so it isn't taken for the folder that was
|
||||
/// locked.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_folder_of_another_lock_taken_in_the_same_second_is_not_the_folder_that_was_locked() {
|
||||
let _serial = serial();
|
||||
let (first_dir, second_dir) = (temp_dir("same-second-one"), temp_dir("same-second-two"));
|
||||
let first = LibraryLock::acquire(&first_dir, "LightCraft").unwrap();
|
||||
let second = LibraryLock::acquire(&second_dir, "LightCraft").unwrap();
|
||||
assert_ne!(first.note(), second.note(), "each lock wrote its own note");
|
||||
|
||||
let away = first_dir.with_extension("away");
|
||||
std::fs::rename(&first_dir, &away).unwrap();
|
||||
std::fs::rename(&second_dir, &first_dir).unwrap();
|
||||
let msg = first.folder().unwrap().check().expect_err("another library's folder is at the path now").to_string();
|
||||
assert!(msg.contains("is no longer the folder this library was opened from"), "{msg}");
|
||||
drop(second);
|
||||
drop(first);
|
||||
let _ = std::fs::remove_dir_all(&first_dir);
|
||||
let _ = std::fs::remove_dir_all(&away);
|
||||
}
|
||||
|
||||
/// Another process holds the lock; when it is killed (a crash), the OS releases it.
|
||||
#[test]
|
||||
fn lock_held_by_another_process_is_released_when_it_dies() {
|
||||
@@ -199,3 +234,90 @@ fn dropping_the_lock_frees_the_library_while_another_thread_spawns_processes() {
|
||||
&refused[..refused.len().min(3)]
|
||||
);
|
||||
}
|
||||
|
||||
/// Issue #3240: dropping the lock removes the owner note it wrote, and only that one. Another
|
||||
/// process that has the folder open (the library on a share that the folder was mounted over)
|
||||
/// wrote the note in the folder at the path now; removing it, as dropping the lock did before,
|
||||
/// took away the only hint of who holds that library.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dropping_the_lock_keeps_the_owner_note_of_a_folder_that_replaced_the_locked_one() {
|
||||
let _serial = serial();
|
||||
let base = temp_dir("owner-replaced");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
assert!(lock.held());
|
||||
std::fs::rename(&dir, base.join("lib.away")).unwrap();
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let theirs = br#"{"pid":999999,"host":"elsewhere","program":"LightCraft","version":"0.2.0","since":1}"#;
|
||||
std::fs::write(dir.join(OWNER), theirs).unwrap();
|
||||
drop(lock);
|
||||
assert_eq!(std::fs::read(dir.join(OWNER)).ok().as_deref(), Some(&theirs[..]), "the note of the folder at the path now is theirs");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A folder that holds this lock's note, byte for byte, is the locked folder whatever its numbers say
|
||||
/// ([`OpenedFolder::vouch`]): a copy of the library's folder made while it was open, put where the
|
||||
/// locked one was, counts as it. So the note goes from there too, as from the locked folder.
|
||||
/// (A note with other bytes is another's, as the test above has it.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dropping_the_lock_removes_a_copy_of_its_note_from_the_folder_that_holds_it() {
|
||||
let _serial = serial();
|
||||
let base = temp_dir("owner-copied");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
let note = std::fs::read(dir.join(OWNER)).unwrap();
|
||||
std::fs::rename(&dir, base.join("lib.away")).unwrap();
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
drop(lock);
|
||||
assert!(!dir.join(OWNER).exists(), "the folder at the path holds exactly this lock's note: it is the locked folder");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The lock vouches for the note it wrote in the record of its folder: that is what recognizes the
|
||||
/// folder when a file system numbers it anew (a drive mounted again), and what the library takes
|
||||
/// over for its stores.
|
||||
#[test]
|
||||
fn the_lock_vouches_for_the_note_it_wrote_in_the_record_of_its_folder() {
|
||||
let _serial = serial();
|
||||
let dir = temp_dir("vouch");
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
let written = std::fs::read(dir.join(OWNER)).unwrap();
|
||||
assert_eq!(lock.note(), Some(written.as_slice()), "the bytes in the folder");
|
||||
assert_eq!(lock.folder().and_then(OpenedFolder::note), Some(written.as_slice()), "are what its folder's record vouches for");
|
||||
drop(lock);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// In the locked folder itself, a note another process wrote over this lock's is theirs too (a
|
||||
/// share that lost this lock's hold and gave it to another computer): it stays when this lock
|
||||
/// is dropped. On every system.
|
||||
#[test]
|
||||
fn dropping_the_lock_keeps_an_owner_note_another_process_wrote() {
|
||||
let _serial = serial();
|
||||
let dir = temp_dir("owner-theirs");
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
assert!(lock.held());
|
||||
let theirs = br#"{"pid":999999,"host":"elsewhere","program":"LightCraft","version":"0.2.0","since":1}"#;
|
||||
std::fs::write(dir.join(OWNER), theirs).unwrap();
|
||||
drop(lock);
|
||||
assert_eq!(std::fs::read(dir.join(OWNER)).ok().as_deref(), Some(&theirs[..]), "a note another process wrote is not ours to remove");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The inverse: the folder is the locked one and the note is as this lock wrote it, so it goes
|
||||
/// (the library can be opened by the next program, with no note left naming this one).
|
||||
#[test]
|
||||
fn dropping_the_lock_removes_its_own_note_from_its_own_folder() {
|
||||
let _serial = serial();
|
||||
let dir = temp_dir("owner-own");
|
||||
let lock = LibraryLock::acquire(&dir, "LightCraft").unwrap();
|
||||
assert!(dir.join(OWNER).is_file());
|
||||
drop(lock);
|
||||
assert!(!dir.join(OWNER).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -105,7 +105,12 @@ fn a_failed_write_is_held_reported_and_retried() {
|
||||
store.flush().unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(true));
|
||||
let f = fail.clone();
|
||||
fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) }));
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(
|
||||
move |step| if f.load(Ordering::SeqCst) && step == fault::Step::Sync { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) },
|
||||
),
|
||||
);
|
||||
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
|
||||
store.append(LOG, b"1\n2\n").unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
@@ -135,6 +140,35 @@ fn a_failed_write_is_held_reported_and_retried() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A log longer than the thread wrote is cut back only when a write of its own failed (that
|
||||
/// fragment is its own). A failure that never touched the file (here the write step, as a folder
|
||||
/// refused while another is put at the path) leaves the log it finds alone: it may be another
|
||||
/// folder's, and cutting it would corrupt it.
|
||||
#[test]
|
||||
fn a_log_longer_than_the_thread_wrote_is_not_cut_unless_its_own_write_failed() {
|
||||
let dir = temp_dir("not-torn");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(LOG, b"0\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(true));
|
||||
let f = fail.clone();
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(
|
||||
move |step| if f.load(Ordering::SeqCst) && step == fault::Step::Write { Err(std::io::Error::other("refused (test)")) } else { Ok(()) },
|
||||
),
|
||||
);
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
let theirs = b"0\nrecords of another log\n";
|
||||
std::fs::write(dir.join(LOG), theirs).unwrap();
|
||||
fail.store(false, Ordering::SeqCst);
|
||||
wait_until("looked at again", || store.unwritten().is_some_and(|(_, why)| why.contains("another file")));
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), theirs, "left as it was found");
|
||||
fault::remove(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
|
||||
/// journal over a log that failed has no gap (no damage on load).
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Issue #3240: a library's files are written to the folder it was opened from, not to whatever its
|
||||
//! path leads to later (a share mounted over the folder, or the folder moved away and another put
|
||||
//! at its path). A folder's identity is its device and inode number, so the tests that move a
|
||||
//! folder run on Unix; the rest hold everywhere.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::journal::{LOG, SNAPSHOT};
|
||||
use crate::lock::OWNER;
|
||||
use crate::*;
|
||||
|
||||
/// The start of the sentence a refused write ends with.
|
||||
const REFUSED: &str = "is no longer the folder this library was opened from";
|
||||
|
||||
fn scratch(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-opened-folder-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The files in `dir` with their bytes, by name.
|
||||
#[cfg(unix)]
|
||||
fn files_in(dir: &Path) -> Vec<(String, Vec<u8>)> {
|
||||
let mut files: Vec<_> = std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.map(|e| {
|
||||
let e = e.unwrap();
|
||||
(e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Another library's folder where `dir` was, and the folder that was there moved to the path
|
||||
/// returned: what a share mounted over `dir` looks like (the path leads somewhere else, and the
|
||||
/// folder that was opened is out of reach).
|
||||
#[cfg(unix)]
|
||||
fn put_another_folder_at(dir: &Path) -> PathBuf {
|
||||
let away = dir.with_extension("away");
|
||||
std::fs::rename(dir, &away).unwrap();
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
std::fs::write(dir.join(SNAPSHOT), b"their snapshot").unwrap();
|
||||
std::fs::write(dir.join(LOG), b"their log\n").unwrap();
|
||||
std::fs::write(dir.join(OWNER), b"their note").unwrap();
|
||||
away
|
||||
}
|
||||
|
||||
/// Every way a store writes is refused in a folder that replaced the opened one, whether or not
|
||||
/// the log's own thread has started, and nothing is written in either folder.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_store_writes_nothing_into_a_folder_that_replaced_the_one_it_opened() {
|
||||
for log_running in [false, true] {
|
||||
let base = scratch(&format!("store-{log_running}"));
|
||||
let dir = base.join("lib");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.write_atomic(SNAPSHOT, b"ours").unwrap();
|
||||
if log_running {
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
}
|
||||
let away = put_another_folder_at(&dir);
|
||||
let (theirs, ours) = (files_in(&dir), files_in(&away));
|
||||
|
||||
let results = [
|
||||
("write_atomic", store.write_atomic(SNAPSHOT, b"x")),
|
||||
("write_atomic_with", store.write_atomic_with(SNAPSHOT, &mut |w| w.write_all(b"x")).map(|_| ())),
|
||||
("write_atomic of the log", store.write_atomic(LOG, b"")),
|
||||
("write_atomic of a settings file", store.write_atomic("prefs.json", b"{}")),
|
||||
("truncate", store.truncate(LOG, 0)),
|
||||
];
|
||||
let appended = store.append(LOG, b"2\n");
|
||||
let flushed = store.flush();
|
||||
|
||||
// what matters most: nothing was written, in either folder
|
||||
assert_eq!(files_in(&dir), theirs, "the folder at the path now is untouched (log thread running: {log_running})");
|
||||
assert_eq!(files_in(&away), ours, "and so is the folder that was opened: saving stops (log thread running: {log_running})");
|
||||
|
||||
// and each write was refused, with the reason
|
||||
for (what, r) in results {
|
||||
let e = r.expect_err(what);
|
||||
assert!(e.to_string().contains(REFUSED), "{what}: {e}");
|
||||
}
|
||||
if log_running {
|
||||
// handed over to the log's thread, which refuses to write it: held, and said so
|
||||
appended.expect("the thread takes it");
|
||||
let e = flushed.expect_err("the thread can't write it");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
let (held, why) = store.unwritten().expect("held, not dropped");
|
||||
assert!(held == 1 && why.contains(REFUSED), "{held}: {why}");
|
||||
} else {
|
||||
let e = appended.expect_err("the first append");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
}
|
||||
|
||||
if log_running {
|
||||
// the folder that was opened is back at the path: what was held is written, into it
|
||||
std::fs::rename(&dir, base.join("lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &dir).unwrap();
|
||||
store.flush().expect("saving resumes");
|
||||
assert_eq!(store.unwritten(), None);
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n2\n");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
}
|
||||
|
||||
/// A compaction that starts after the folder was replaced writes through a second handle on the
|
||||
/// same files: it is bound to the folder the store opened too.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_snapshot_writer_of_a_store_is_bound_to_the_folder_the_store_opened() {
|
||||
let base = scratch("worker");
|
||||
let dir = base.join("lib");
|
||||
let store = FsStore::open(&dir).unwrap();
|
||||
let _away = put_another_folder_at(&dir);
|
||||
let theirs = files_in(&dir);
|
||||
let mut worker = store.background_writer().expect("a store on disk has one");
|
||||
let e = worker.write_atomic_with(SNAPSHOT, &mut |w| w.write_all(b"ours")).expect_err("refused");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert_eq!(files_in(&dir), theirs);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A journal's save (the closing snapshot) in a folder that replaced the opened one fails with the
|
||||
/// reason and writes nothing; with the folder back, the same call saves.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_journal_cannot_snapshot_into_a_folder_that_replaced_the_one_it_opened() {
|
||||
let base = scratch("journal");
|
||||
let dir = base.join("lib");
|
||||
let (mut journal, catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
let away = put_another_folder_at(&dir);
|
||||
let theirs = files_in(&dir);
|
||||
let e = journal.snapshot(&catalog).expect_err("the path leads to another library's folder");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert_eq!(files_in(&dir), theirs);
|
||||
|
||||
std::fs::rename(&dir, base.join("lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &dir).unwrap();
|
||||
journal.snapshot(&catalog).expect("the folder is back");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A file system that numbers its folders anew at every mount (FAT and exFAT on Linux, sshfs) gives
|
||||
/// the folder other numbers: it is the opened folder again while it holds the note this session's
|
||||
/// lock wrote, for every way a store writes, the log's thread included. (A mount can't be faked in
|
||||
/// a test: the numbers the store recorded at open are made different from the folder's.)
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_store_writes_into_a_folder_with_other_numbers_while_the_folder_holds_this_sessions_note() {
|
||||
let dir = scratch("renumbered");
|
||||
let note = b"the note this session's lock wrote";
|
||||
let folder = OpenedFolder::recorded_under_other_numbers(&dir);
|
||||
folder.vouch(note);
|
||||
let mut store = FsStore::in_folder(folder);
|
||||
|
||||
let e = store.write_atomic(SNAPSHOT, b"x").expect_err("other numbers, and no note in the folder");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert!(files_in(&dir).is_empty(), "nothing was written");
|
||||
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.write_atomic(SNAPSHOT, b"one").expect("the note vouches for the folder");
|
||||
store.write_atomic_with(SNAPSHOT, &mut |w| w.write_all(b"two")).expect("a snapshot written in pieces too");
|
||||
assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), b"two");
|
||||
store.append(LOG, b"1\n").expect("the first append starts the log's thread");
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n");
|
||||
|
||||
// another program's note over this session's: what the thread is handed is held, not written
|
||||
std::fs::write(dir.join(OWNER), b"theirs").unwrap();
|
||||
store.append(LOG, b"2\n").expect("the thread takes it");
|
||||
let e = store.flush().expect_err("the thread can't write it");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n");
|
||||
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.flush().expect("this session's note is back: what was held is written");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"1\n2\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A copy of the library's folder (the note in it too) put at the path counts as the opened folder,
|
||||
/// but its log is not the one the log's thread wrote: the thread opens the log by its path for each
|
||||
/// batch and appends only while it is the length the thread left. A log that isn't is refused like a
|
||||
/// failed write (held, reported): not written on through a file kept open in the folder that was
|
||||
/// moved away, where the copy would never get it, and not appended to at its end, where it would
|
||||
/// have a gap. The log reset of a snapshot replaces it and takes what was held.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_log_that_is_not_the_one_the_thread_wrote_is_not_appended_to() {
|
||||
let base = scratch("log-copy");
|
||||
let dir = base.join("lib");
|
||||
let note = b"the note this session's lock wrote";
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.folder().vouch(note);
|
||||
std::fs::write(dir.join(OWNER), note).unwrap();
|
||||
store.append(LOG, b"1\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
|
||||
// a copy made now, which the folder that was opened outgrows, put in its place
|
||||
let copy = base.join("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
for (name, bytes) in files_in(&dir) {
|
||||
std::fs::write(copy.join(name), bytes).unwrap();
|
||||
}
|
||||
store.append(LOG, b"2\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let away = base.join("away");
|
||||
std::fs::rename(&dir, &away).unwrap();
|
||||
std::fs::rename(©, &dir).unwrap();
|
||||
let (theirs, ours) = (files_in(&dir), files_in(&away));
|
||||
|
||||
store.append(LOG, b"3\n").unwrap();
|
||||
let e = store.flush().expect_err("the log at the path is not the one this session wrote");
|
||||
assert!(e.to_string().contains("holds 2 bytes, the log this session wrote has 4"), "{e}");
|
||||
assert_eq!(files_in(&dir), theirs, "nothing is appended to it");
|
||||
assert_eq!(files_in(&away), ours, "and nothing is written on through a file kept open in the folder that was moved away");
|
||||
assert_eq!(store.unwritten().map(|(n, _)| n), Some(1), "held, not dropped");
|
||||
store.append(LOG, b"4\n").expect("later records are taken: retrying can't heal this, only a replace of the log does");
|
||||
assert_eq!(files_in(&dir), theirs, "and not written either");
|
||||
|
||||
store.write_atomic(LOG, b"tail\n").unwrap();
|
||||
assert_eq!(store.unwritten(), None, "the snapshot's log holds what was held");
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
|
||||
store.append(LOG, b"5\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n5\n", "and appending goes on");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_is_the_opened_one_while_its_path_leads_to_it() {
|
||||
let dir = scratch("same");
|
||||
let folder = OpenedFolder::at(&dir).unwrap();
|
||||
folder.check().unwrap();
|
||||
std::fs::write(dir.join("catalog.snap"), b"x").unwrap();
|
||||
std::fs::create_dir(dir.join("thumbs")).unwrap();
|
||||
folder.check().expect("what is written in it changes nothing");
|
||||
assert!(folder.same_folder(&folder.clone()));
|
||||
assert_eq!(folder.path(), dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_that_is_not_a_folder_cannot_be_opened() {
|
||||
let dir = scratch("not-a-folder");
|
||||
let file = dir.join("file");
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
assert!(OpenedFolder::at(&file).expect_err("a file").to_string().contains("is not a folder"));
|
||||
assert!(OpenedFolder::at(&dir.join("missing")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder that is gone is said to be gone, on every system.
|
||||
#[test]
|
||||
fn a_folder_that_is_gone_is_reported_as_gone() {
|
||||
let base = scratch("gone");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let folder = OpenedFolder::at(&dir).unwrap();
|
||||
std::fs::remove_dir(&dir).unwrap();
|
||||
let e = folder.check().expect_err("nothing is there");
|
||||
let msg = e.to_string();
|
||||
assert!(msg.contains(REFUSED) && msg.contains("nothing is there now") && msg.contains(&dir.display().to_string()), "{msg}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The reason names the path and what to do; a folder moved and replaced is told from a gone one.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replaced_folder_is_refused_until_the_opened_one_is_back() {
|
||||
let base = scratch("replaced");
|
||||
let dir = base.join("lib");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let folder = OpenedFolder::at(&dir).unwrap();
|
||||
let away = put_another_folder_at(&dir);
|
||||
let msg = folder.check().expect_err("another folder is at the path").to_string();
|
||||
assert!(msg.contains(REFUSED) && msg.contains("moved or replaced") && msg.contains(&dir.display().to_string()), "{msg}");
|
||||
assert!(msg.contains("put the original folder back"), "{msg}");
|
||||
assert!(!folder.same_folder(&OpenedFolder::at(&dir).unwrap()), "the other folder is another folder");
|
||||
|
||||
std::fs::rename(&dir, base.join("lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &dir).unwrap();
|
||||
folder.check().expect("the opened folder is back");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A library reached through a link is the folder the link leads to: a link that stays is no
|
||||
/// reason to refuse, and one pointed at another folder is.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_to_the_folder_is_followed() {
|
||||
let base = scratch("link");
|
||||
let (one, two, link) = (base.join("one"), base.join("two"), base.join("link"));
|
||||
std::fs::create_dir(&one).unwrap();
|
||||
std::fs::create_dir(&two).unwrap();
|
||||
std::os::unix::fs::symlink(&one, &link).unwrap();
|
||||
let folder = OpenedFolder::at(&link).unwrap();
|
||||
folder.check().expect("the link still leads to it");
|
||||
std::fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink(&two, &link).unwrap();
|
||||
assert!(folder.check().is_err(), "the link leads to another folder now");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
@@ -338,12 +338,14 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
|
||||
}
|
||||
|
||||
/// Move, after the commit: save the library, then remove each source whose destination is
|
||||
/// still intact. Nothing is removed when the library can't be saved.
|
||||
/// still intact. Nothing is removed when the library can't be saved: saved is on disk, not just
|
||||
/// handed to the catalog log's thread, which looks at the folder only when it writes (issue #3240),
|
||||
/// so the log is flushed first.
|
||||
fn finish_moves(s: &mut Session, placed: Vec<crate::import_move::Placed>, log0: usize, report: &mut ImportReport) {
|
||||
// (saving here clears the pending ops, so the sidecars `execute` would auto-write are written here)
|
||||
let auto: Vec<Op> = if s.xmp.auto_write { s.pending_log.get(log0..).map(<[Op]>::to_vec).unwrap_or_default() } else { Vec::new() };
|
||||
let before = s.pending_log.len();
|
||||
if let Err(e) = s.persist() {
|
||||
if let Err(e) = s.persist().and_then(|()| s.flush_log()) {
|
||||
for p in placed {
|
||||
let reason = format!("the library could not be saved ({e}): the original stays; the photo uses the copy at {}", p.dst.display());
|
||||
report.kept.push(Kept { path: p.src.to_string_lossy().to_string(), reason });
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lightcraft_catalog::{FsStore, Journal, LibraryLock, LoadReport, Store};
|
||||
use lightcraft_catalog::{FsStore, Journal, LibraryLock, LoadReport, OpenedFolder, Store};
|
||||
use lightcraft_develop::Preset;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -155,6 +155,10 @@ pub struct Library {
|
||||
warnings_reported: usize,
|
||||
/// Settings files that couldn't be read or set aside: never overwritten this session.
|
||||
blocked: Vec<&'static str>,
|
||||
/// The folder the library was opened from (`None`: its stores were given, not opened here). The
|
||||
/// stores hold their own copy; this one is for what is not a store, so far the thumbnail cache
|
||||
/// (issue #3240).
|
||||
folder: Option<OpenedFolder>,
|
||||
/// Keeps other processes out of this library while it's open (last: released after the
|
||||
/// journal's background snapshot has landed).
|
||||
lock: Option<LibraryLock>,
|
||||
@@ -168,10 +172,19 @@ pub struct LibraryStores {
|
||||
pub catalog: Box<dyn Store>,
|
||||
/// presets.json, view.json, prefs.json.
|
||||
pub files: Box<dyn Store>,
|
||||
/// `dir` is a real directory (enables `Originals/` copies and the `thumbs/` disk cache).
|
||||
/// `dir` is a real directory (enables `Originals/` copies and the `thumbs/` disk cache). The cache
|
||||
/// is bound to the folder `dir` named when the library opened, which only [`Session::open_library`]
|
||||
/// records: the stores of [`Session::open_library_in`] (browser storage, memory) have no folder.
|
||||
pub on_disk: bool,
|
||||
}
|
||||
|
||||
/// What the thumbnail cache asks before it changes its folder: `false` while the library's path leads
|
||||
/// to another folder than the one it was opened from (issue #3240). `None`: there is no folder to ask.
|
||||
fn disk_gate(folder: Option<&OpenedFolder>) -> Option<lightcraft_preview::WriteGate> {
|
||||
let folder = folder?.clone();
|
||||
Some(std::sync::Arc::new(move || folder.check().is_ok()))
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
struct PresetsFile {
|
||||
@@ -359,6 +372,17 @@ fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The lock for the library at `dir`. One taken in another folder than `folder` (the stores' record,
|
||||
/// which holds no note yet, so only the numbers are compared) means the path changed since the
|
||||
/// stores recorded it, and nothing of this open is consistent: refused.
|
||||
pub(crate) fn lock_in(dir: &Path, folder: &OpenedFolder) -> Result<LibraryLock> {
|
||||
let lock = LibraryLock::acquire(dir, &program_name()).map_err(|e| EngineError::LibraryInUse(e.to_string()))?;
|
||||
if lock.folder().is_some_and(|f| !folder.same_folder(f)) {
|
||||
return Err(EngineError::Other(format!("{} changed while the library was being opened; open it again", dir.display())));
|
||||
}
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
/// This program, for the lock owner note ("LightCraft", "lightcraft-cli").
|
||||
fn program_name() -> String {
|
||||
let exe = std::env::current_exe().ok().and_then(|p| p.file_stem().map(|s| s.to_string_lossy().to_string()));
|
||||
@@ -464,8 +488,14 @@ impl Session {
|
||||
return Err(EngineError::Other(format!("{} is not a folder", dir.display())));
|
||||
}
|
||||
std::fs::read_dir(&dir).map_err(|e| EngineError::Other(format!("can't open library {}: {e}", dir.display())))?;
|
||||
// the library open in this session keeps its lock when reopened; any other must be free
|
||||
let current = self.library.as_ref().is_some_and(|l| l.on_disk && same_dir(&l.dir, &dir));
|
||||
// the library open in this session keeps its lock when reopened, if it was taken in the folder
|
||||
// at the path now (as in `open_library`); any other must be free
|
||||
let here = OpenedFolder::at(&dir).ok();
|
||||
let current = self.library.as_ref().is_some_and(|l| {
|
||||
l.on_disk
|
||||
&& same_dir(&l.dir, &dir)
|
||||
&& l.lock.as_ref().is_some_and(|k| k.folder().is_none_or(|f| here.as_ref().is_none_or(|h| f.same_folder(h))))
|
||||
});
|
||||
if !current && is_library(&dir) {
|
||||
drop(LibraryLock::acquire(&dir, &program_name()).map_err(|e| EngineError::LibraryInUse(e.to_string()))?);
|
||||
}
|
||||
@@ -489,16 +519,30 @@ impl Session {
|
||||
return Err(EngineError::LightroomCatalog { path: dir, catalog: place.catalog });
|
||||
}
|
||||
let dir = resolve_dir(&dir)?;
|
||||
let open = || FsStore::open(&dir).map_err(|e| EngineError::Other(format!("can't open library {}: {e}", dir.display())));
|
||||
let stores = LibraryStores { catalog: Box::new(open()?), files: Box::new(open()?), on_disk: true, dir: dir.clone() };
|
||||
// the library open in this session (same directory): hand its lock over
|
||||
let reused = self.library.as_mut().filter(|l| same_dir(&l.dir, &dir)).and_then(|l| l.lock.take());
|
||||
let catalog = FsStore::open(&dir).map_err(|e| EngineError::Other(format!("can't open library {}: {e}", dir.display())))?;
|
||||
// the folder `dir` names now: both stores write only while it still does (issue #3240)
|
||||
let folder = catalog.folder().clone();
|
||||
let stores =
|
||||
LibraryStores { catalog: Box::new(catalog), files: Box::new(FsStore::in_folder(folder.clone())), on_disk: true, dir: dir.clone() };
|
||||
// the library open in this session (same directory, same folder): hand its lock over. A lock
|
||||
// on another folder than the path leads to now protects nothing here: take this one's own.
|
||||
// (A lock that couldn't look at its folder is handed over as before.)
|
||||
let reused = self
|
||||
.library
|
||||
.as_mut()
|
||||
.filter(|l| same_dir(&l.dir, &dir))
|
||||
.and_then(|l| l.lock.take_if(|k| k.folder().is_none_or(|f| f.same_folder(&folder))));
|
||||
let reusing = reused.is_some();
|
||||
let mut lock = match reused {
|
||||
Some(l) => Some(l),
|
||||
None => Some(LibraryLock::acquire(&dir, &program_name()).map_err(|e| EngineError::LibraryInUse(e.to_string()))?),
|
||||
None => Some(lock_in(&dir, &folder)?),
|
||||
};
|
||||
if let Err(e) = self.open_stores(stores, seed_demo, &mut lock) {
|
||||
// what tells the folder when its numbers can't (a drive that numbers its folders anew each
|
||||
// time it is mounted): the note this session's lock wrote into it
|
||||
if let Some(note) = lock.as_ref().and_then(LibraryLock::note) {
|
||||
folder.vouch(note);
|
||||
}
|
||||
if let Err(e) = self.open_stores(stores, seed_demo, &mut lock, Some(folder)) {
|
||||
if reusing && let Some(lib) = self.library.as_mut() {
|
||||
lib.lock = lock.take();
|
||||
}
|
||||
@@ -511,7 +555,7 @@ impl Session {
|
||||
/// this session's catalog. Not locked: the host guards against a second opener (see
|
||||
/// [`Session::open_library`] for directories).
|
||||
pub fn open_library_in(&mut self, stores: LibraryStores, seed_demo: bool) -> Result<&LoadReport> {
|
||||
self.open_stores(stores, seed_demo, &mut None)?;
|
||||
self.open_stores(stores, seed_demo, &mut None, None)?;
|
||||
self.loaded_report()
|
||||
}
|
||||
|
||||
@@ -522,8 +566,9 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open `stores`; the new library takes `lock` once nothing can fail any more.
|
||||
fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option<LibraryLock>) -> Result<()> {
|
||||
/// Open `stores`; the new library takes `lock` once nothing can fail any more. `folder` is the
|
||||
/// folder they write to, when they write to one: the thumbnail cache asks it too.
|
||||
fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option<LibraryLock>, folder: Option<OpenedFolder>) -> Result<()> {
|
||||
let LibraryStores { dir, catalog, mut files, on_disk } = stores;
|
||||
// the current library may be these same files: let its background snapshot land first, and
|
||||
// what its log's thread was handed reach the file before the new journal reads it. When
|
||||
@@ -663,7 +708,7 @@ impl Session {
|
||||
// photo ids are per library: drop decoded sources of the previous one
|
||||
self.media.clear_sources();
|
||||
if on_disk {
|
||||
self.media.attach_disk_cache(&dir.join("thumbs"), self.cache_bytes());
|
||||
self.media.attach_disk_cache(&dir.join("thumbs"), self.cache_bytes(), disk_gate(folder.as_ref()));
|
||||
self.tidy_thumbnail_cache();
|
||||
}
|
||||
let view_written = self.view_json();
|
||||
@@ -684,6 +729,7 @@ impl Session {
|
||||
settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(settings.warnings).collect(),
|
||||
warnings_reported: 0,
|
||||
blocked: settings.blocked,
|
||||
folder,
|
||||
lock: lock.take(),
|
||||
});
|
||||
// forget untouched Local records of folders not browsed for a while (journaled at once)
|
||||
@@ -972,8 +1018,8 @@ impl Session {
|
||||
pub fn set_cache_mb(&mut self, mb: u32) -> Result<()> {
|
||||
self.cache_mb = mb;
|
||||
if let Some(lib) = self.library.as_ref().filter(|l| l.on_disk) {
|
||||
let dir = lib.thumbs_dir();
|
||||
self.media.set_disk_cache_bytes(&dir, self.cache_bytes());
|
||||
let (dir, gate) = (lib.thumbs_dir(), disk_gate(lib.folder.as_ref()));
|
||||
self.media.set_disk_cache_bytes(&dir, self.cache_bytes(), gate);
|
||||
}
|
||||
self.save_prefs()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::settings_hash::SettingsHashes;
|
||||
use super::source::{DecodedSource, DenoiseSpec, PairLoader, RENDERED_MEM_BYTES, SourceLevel, SourceRef, THUMB_SOURCE_BYTES};
|
||||
use super::{Arc, DcpProfile, DevelopSettings, HashMap, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
|
||||
use lightcraft_preview::WriteGate;
|
||||
|
||||
/// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the
|
||||
/// file system, so it can be asked on the UI thread.
|
||||
@@ -85,19 +86,24 @@ pub(crate) fn rendered_budget(share: usize) -> usize {
|
||||
impl MediaCache {
|
||||
/// Keep rendered thumbnails on disk in `dir` as well. The cache this replaces is retired
|
||||
/// (its files stay): render jobs still holding it can't write through it any more, even
|
||||
/// into a directory a later clear emptied (`dir` may be the same one).
|
||||
pub fn attach_disk_cache(&mut self, dir: &std::path::Path, disk_bytes: u64) {
|
||||
/// into a directory a later clear emptied (`dir` may be the same one). `gate` is asked before
|
||||
/// the cache changes its folder (`lightcraft_preview::DiskCache::set_gate`).
|
||||
pub fn attach_disk_cache(&mut self, dir: &std::path::Path, disk_bytes: u64, gate: Option<WriteGate>) {
|
||||
self.rendered.retire();
|
||||
self.rendered = Arc::new(PreviewCache::with_disk(rendered_budget(self.budget), dir, disk_bytes));
|
||||
let cache = PreviewCache::with_disk(rendered_budget(self.budget), dir, disk_bytes);
|
||||
if let (Some(disk), Some(gate)) = (cache.disk(), gate) {
|
||||
disk.set_gate(gate);
|
||||
}
|
||||
self.rendered = Arc::new(cache);
|
||||
}
|
||||
|
||||
/// Change the disk budget of the cache in `dir`: in place when that cache is attached (its
|
||||
/// thumbnails are keyed by content, so they and the textures shown from them stay valid,
|
||||
/// and the same cache object keeps its generation), else attach it.
|
||||
pub fn set_disk_cache_bytes(&mut self, dir: &std::path::Path, disk_bytes: u64) {
|
||||
/// and the same cache object keeps its generation), else attach it (with `gate`).
|
||||
pub fn set_disk_cache_bytes(&mut self, dir: &std::path::Path, disk_bytes: u64, gate: Option<WriteGate>) {
|
||||
match self.rendered.disk().filter(|d| d.dir() == dir) {
|
||||
Some(d) => d.set_budget(disk_bytes),
|
||||
None => self.attach_disk_cache(dir, disk_bytes),
|
||||
None => self.attach_disk_cache(dir, disk_bytes, gate),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ mod mask_effects;
|
||||
mod mask_geometry;
|
||||
mod merge;
|
||||
mod move_to_share;
|
||||
#[cfg(unix)]
|
||||
mod opened_folder;
|
||||
mod organize;
|
||||
mod persist;
|
||||
mod prefs;
|
||||
|
||||
@@ -15,7 +15,7 @@ fn temp_dir(tag: &str) -> PathBuf {
|
||||
d
|
||||
}
|
||||
|
||||
fn write_png(path: &Path, seed: u8) {
|
||||
pub(super) fn write_png(path: &Path, seed: u8) {
|
||||
let (w, h) = (40usize, 24usize);
|
||||
let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect();
|
||||
let img = lightcraft_raster::Rgba8 { width: w, height: h, data };
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//! Issue #3240: an open library writes only to the folder it opened. When its path leads to another
|
||||
//! folder (a share mounted over it, or the folder moved away and another put in its place), saving
|
||||
//! stops with the reason, nothing is written there, and the changes are kept until the folder that
|
||||
//! was opened is back. A folder's identity is its device and inode number, so these run on Unix.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_catalog::{LibraryLock, OpenedFolder};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
/// What the reason for a refused save says.
|
||||
const REFUSED: &str = "is no longer the folder this library was opened from";
|
||||
|
||||
fn scratch(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-opened-folder-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// What `dir` holds, by name: a file's bytes (a folder is listed, empty).
|
||||
fn files_in(dir: &Path) -> Vec<(String, Vec<u8>)> {
|
||||
let mut files: Vec<_> = std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.map(|e| {
|
||||
let e = e.unwrap();
|
||||
let bytes = if e.path().is_dir() { Vec::new() } else { std::fs::read(e.path()).unwrap() };
|
||||
(e.file_name().to_string_lossy().into_owned(), bytes)
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Another library's folder where `lib` was, as a share mounted over it would look: the folder that
|
||||
/// was opened is moved to the path returned, out of the path's reach.
|
||||
fn put_another_library_at(lib: &Path) -> PathBuf {
|
||||
let away = lib.with_extension("away");
|
||||
std::fs::rename(lib, &away).unwrap();
|
||||
std::fs::create_dir(lib).unwrap();
|
||||
let theirs: [(&str, &[u8]); 4] =
|
||||
[("catalog.snap", b"their snapshot"), ("catalog.log", b"their log\n"), ("catalog.lock.owner", b"their note"), ("presets.json", b"{}")];
|
||||
for (name, bytes) in theirs {
|
||||
std::fs::write(lib.join(name), bytes).unwrap();
|
||||
}
|
||||
away
|
||||
}
|
||||
|
||||
/// A copy of `lib`'s files (the lock's note included) in a folder of its own beside it, as a folder
|
||||
/// copied while the library was open would be.
|
||||
fn copy_of(lib: &Path) -> PathBuf {
|
||||
let copy = lib.with_extension("copy");
|
||||
std::fs::create_dir(©).unwrap();
|
||||
for e in std::fs::read_dir(lib).unwrap().map(Result::unwrap).filter(|e| e.path().is_file()) {
|
||||
std::fs::copy(e.path(), copy.join(e.file_name())).unwrap();
|
||||
}
|
||||
copy
|
||||
}
|
||||
|
||||
/// `copy` where `lib` was, as a copy put in its place would be: the folder that was opened is
|
||||
/// moved to the path returned.
|
||||
fn swap_in(lib: &Path, copy: &Path) -> PathBuf {
|
||||
let away = lib.with_extension("away");
|
||||
std::fs::rename(lib, &away).unwrap();
|
||||
std::fs::rename(copy, lib).unwrap();
|
||||
away
|
||||
}
|
||||
|
||||
/// A copy of `lib`'s files (the lock's note included) where `lib` was: the folder that was opened
|
||||
/// is moved to the path returned.
|
||||
fn put_a_copy_at(lib: &Path) -> PathBuf {
|
||||
swap_in(lib, ©_of(lib))
|
||||
}
|
||||
|
||||
/// What a crash now would leave: the catalog files at `lib`, copied and opened elsewhere.
|
||||
fn after_a_crash(lib: &Path) -> Session {
|
||||
let crashed = lib.with_extension("crashed");
|
||||
std::fs::create_dir_all(&crashed).unwrap();
|
||||
for name in ["catalog.snap", "catalog.log"] {
|
||||
if lib.join(name).exists() {
|
||||
std::fs::copy(lib.join(name), crashed.join(name)).unwrap();
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.open_library(&crashed, false).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The demo library at `lib`, open, with one change (a rating of 2) already on disk.
|
||||
fn open_with_a_saved_change(lib: &Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.open_library(lib, true).unwrap();
|
||||
s.execute("photo.rate", &json!({"rating": 2})).unwrap();
|
||||
s.flush_log().unwrap();
|
||||
assert_eq!(s.unsaved(), None);
|
||||
s
|
||||
}
|
||||
|
||||
/// The acceptance case: the folder at the path is replaced while the library is open. The next
|
||||
/// save is refused with the reason, the new folder (and the owner note in it) is untouched, and so
|
||||
/// is the folder that was opened: the session stops saving.
|
||||
#[test]
|
||||
fn a_folder_that_replaced_the_open_library_is_not_written_to() {
|
||||
let base = scratch("replaced");
|
||||
let lib = base.join("Lib");
|
||||
let mut s = open_with_a_saved_change(&lib);
|
||||
let id = s.selection.active.unwrap();
|
||||
|
||||
let away = put_another_library_at(&lib);
|
||||
let (theirs, ours) = (files_in(&lib), files_in(&away));
|
||||
|
||||
// two changes after the swap, then quitting: the first is applied in memory and handed to the log's
|
||||
// thread, which can't write it where the path leads now; the second is refused as it is made
|
||||
let _ = s.execute("photo.rate", &json!({"rating": 5}));
|
||||
let applied = s.catalog.photo(id).unwrap().rating;
|
||||
let flushed = s.flush_log();
|
||||
let held = s.unsaved().map(|(n, why)| (n, why.to_owned()));
|
||||
let second = s.execute("photo.rate", &json!({"rating": 4}));
|
||||
let closed = s.close_library();
|
||||
|
||||
// what matters most: nothing was written, into either folder
|
||||
assert_eq!(files_in(&lib), theirs, "nothing is written into the folder at the path now, its owner note included");
|
||||
assert_eq!(files_in(&away), ours, "nor into the folder that was opened: saving stops");
|
||||
|
||||
// and each step said why
|
||||
assert_eq!(applied, 5, "the change is applied");
|
||||
let e = flushed.expect_err("the folder at the path isn't the one that was opened");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
let (n, why) = held.expect("saved in memory only");
|
||||
assert!(n >= 1 && why.contains(REFUSED) && why.contains(&lib.display().to_string()), "{n}: {why}");
|
||||
let e = second.expect_err("not saved");
|
||||
assert!(matches!(e, EngineError::NotSaved(_)) && e.to_string().contains(REFUSED), "{e:?}");
|
||||
let e = closed.expect_err("nowhere to write");
|
||||
assert!(e.to_string().contains(REFUSED), "{e}");
|
||||
|
||||
drop(s);
|
||||
assert_eq!(files_in(&lib), theirs, "not even when the session ends: its owner note stays");
|
||||
assert_eq!(files_in(&away), ours);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The inverse: with the folder that was opened back at the path, what was held and what was
|
||||
/// queued is written into it, and the library reopens with both.
|
||||
#[test]
|
||||
fn saving_goes_on_when_the_folder_that_was_opened_is_back() {
|
||||
let base = scratch("back");
|
||||
let lib = base.join("Lib");
|
||||
let mut s = open_with_a_saved_change(&lib);
|
||||
let id = s.selection.active.unwrap();
|
||||
|
||||
let away = put_another_library_at(&lib);
|
||||
let _ = s.execute("photo.rate", &json!({"rating": 5}));
|
||||
s.flush_log().expect_err("refused");
|
||||
s.execute("photo.rate", &json!({"rating": 4})).expect_err("refused");
|
||||
assert!(s.unsaved().is_some());
|
||||
|
||||
std::fs::rename(&lib, base.join("Lib.theirs")).unwrap();
|
||||
std::fs::rename(&away, &lib).unwrap();
|
||||
s.flush_log().expect("what the log's thread held is written");
|
||||
s.persist().expect("and what was queued");
|
||||
s.flush_log().unwrap();
|
||||
assert_eq!(s.unsaved(), None);
|
||||
s.close_library().unwrap();
|
||||
drop(s);
|
||||
|
||||
let mut again = Session::new();
|
||||
again.open_library(&lib, true).unwrap();
|
||||
assert_eq!(again.catalog.photo(id).unwrap().rating, 4, "both changes were saved, in order");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// Reopening the path of a replaced folder doesn't carry the old lock over: it is on the folder
|
||||
/// that was opened, so the folder at the path now gets its own, and is refused while another
|
||||
/// program has it open.
|
||||
#[test]
|
||||
fn reopening_the_path_of_a_replaced_folder_takes_that_folders_lock() {
|
||||
let base = scratch("relock");
|
||||
let lib = base.join("Lib");
|
||||
let mut s = open_with_a_saved_change(&lib);
|
||||
|
||||
let _away = put_another_library_at(&lib);
|
||||
let other_program = LibraryLock::acquire(&lib, "other").unwrap();
|
||||
let e = s.open_library(&lib, false).expect_err("the folder at the path is in use");
|
||||
assert!(matches!(e, EngineError::LibraryInUse(_)), "{e:?}");
|
||||
assert!(s.library.is_some(), "the library that was open stays open");
|
||||
drop(other_program);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The thumbnail cache is bound to the folder too: a thumbnail finished after the swap is kept in
|
||||
/// memory, and no `thumbs` folder is made in the folder at the path now.
|
||||
#[test]
|
||||
fn thumbnails_are_not_cached_into_a_folder_that_replaced_the_open_library() {
|
||||
let base = scratch("thumbs");
|
||||
let lib = base.join("Lib");
|
||||
let s = open_with_a_saved_change(&lib);
|
||||
let _away = put_another_library_at(&lib);
|
||||
let theirs = files_in(&lib);
|
||||
|
||||
let key = lightcraft_preview::hash_bytes(b"a thumbnail");
|
||||
s.media.rendered.put(key, Arc::new(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[10, 20, 30, 255]; 16] }));
|
||||
assert!(s.media.rendered.get(key).is_some(), "kept in memory");
|
||||
assert_eq!(files_in(&lib), theirs, "no thumbnail folder is made in the folder at the path now");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A Move import takes the originals off the card only once the library is on disk: the catalog
|
||||
/// log's thread is handed the records at once and looks at the folder when it writes them, so the
|
||||
/// move waits for that. With the folder replaced the originals stay (the session holds the records
|
||||
/// of the copies, which are not on disk).
|
||||
#[test]
|
||||
fn a_move_import_keeps_its_originals_while_the_library_cannot_be_saved() {
|
||||
let base = scratch("move");
|
||||
let (lib, card, dest) = (base.join("Lib"), base.join("card"), base.join("dest"));
|
||||
let mut s = Session::new().with_fs();
|
||||
s.clock = Box::new(|| "2026-01-14T05:58:48".to_string());
|
||||
s.open_library(&lib, true).unwrap();
|
||||
s.execute("photo.rate", &json!({"rating": 2})).unwrap();
|
||||
s.flush_log().unwrap();
|
||||
let _away = put_another_library_at(&lib);
|
||||
super::import_move::write_png(&card.join("a.png"), 1);
|
||||
|
||||
let params = json!({"paths": [card.to_string_lossy()], "mode": "move", "destination": dest.to_string_lossy()});
|
||||
let r = s.execute("library.import", ¶ms).unwrap();
|
||||
assert!(card.join("a.png").is_file(), "the original stays while the library that points at its copy is not on disk: {r}");
|
||||
assert_eq!(r["moved"].as_array().map_or(0, Vec::len), 0, "{r}");
|
||||
let reason = r["kept"][0]["reason"].as_str().unwrap_or_default();
|
||||
assert!(reason.contains("could not be saved") && reason.contains(REFUSED), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// What tells the folder when its numbers can't is the note this session's lock wrote into it: a copy
|
||||
/// of the library's folder (the note in it too) put where the opened one was counts as the opened
|
||||
/// folder, so saving goes on and the closing snapshot is written into it. (The case this stands for
|
||||
/// is a drive that numbers its folders anew each time it is mounted; a mount can't be made in a
|
||||
/// test. A folder with no such note, or another one, never counts: the tests above.)
|
||||
#[test]
|
||||
fn a_folder_that_holds_the_note_of_the_open_library_counts_as_the_folder_that_was_opened() {
|
||||
let base = scratch("note");
|
||||
let lib = base.join("Lib");
|
||||
let mut s = open_with_a_saved_change(&lib);
|
||||
let id = s.selection.active.unwrap();
|
||||
assert!(lib.join("catalog.lock.owner").is_file(), "the lock wrote its note");
|
||||
|
||||
let away = put_a_copy_at(&lib);
|
||||
let snapshot = std::fs::read(away.join("catalog.snap")).ok();
|
||||
s.execute("photo.rate", &json!({"rating": 5})).expect("the folder at the path holds this session's note: saving goes on");
|
||||
s.flush_log().expect("the log's thread is not refused either");
|
||||
assert_eq!(s.unsaved(), None);
|
||||
s.close_library().expect("the closing snapshot is written into the folder at the path");
|
||||
drop(s);
|
||||
assert_eq!(std::fs::read(away.join("catalog.snap")).ok(), snapshot, "the folder that was moved away keeps its snapshot");
|
||||
|
||||
let mut again = Session::new();
|
||||
again.open_library(&lib, true).unwrap();
|
||||
assert_eq!(again.catalog.photo(id).unwrap().rating, 5, "the folder at the path has the change made after the swap");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A copy made while the library was open counts as it, but its log lacks what was written after the
|
||||
/// copy was made: appending to it would leave a gap, and the file the log's thread had open is in the
|
||||
/// folder that was moved away, so a change made after the swap would be saved nowhere the path leads
|
||||
/// to. The thread refuses a log it didn't write and holds what it was handed, and the snapshot the
|
||||
/// frame loop takes for held records (it holds every change) replaces the copy's log: a crash right
|
||||
/// after has the change made before the swap and the one made after it.
|
||||
#[test]
|
||||
fn a_copy_that_lacks_changes_is_made_whole_by_a_snapshot() {
|
||||
let base = scratch("copy-gap");
|
||||
let lib = base.join("Lib");
|
||||
let mut s = open_with_a_saved_change(&lib);
|
||||
let id = s.selection.active.unwrap();
|
||||
|
||||
let copy = copy_of(&lib);
|
||||
s.execute("photo.rate", &json!({"rating": 3})).unwrap();
|
||||
s.flush_log().unwrap();
|
||||
let away = swap_in(&lib, ©);
|
||||
let ours = files_in(&away);
|
||||
|
||||
s.execute("photo.rate", &json!({"rating": 5})).unwrap();
|
||||
let _ = s.flush_log();
|
||||
s.execute("photo.rate", &json!({"rating": 4})).expect("a second change while the first is held is taken: only a snapshot heals the log");
|
||||
let t = std::time::Instant::now();
|
||||
while s.unsaved().is_some() || s.library.as_ref().unwrap().journal().snapshot_running() {
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(20), "never made whole: {:?}", s.unsaved());
|
||||
s.persist_if_dirty();
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert_eq!(files_in(&away), ours, "nothing was written into the folder that was moved away");
|
||||
assert_eq!(after_a_crash(&lib).catalog.photo(id).unwrap().rating, 4, "a crash now loses nothing");
|
||||
s.close_library().unwrap();
|
||||
drop(s);
|
||||
let mut again = Session::new();
|
||||
again.open_library(&lib, true).unwrap();
|
||||
assert_eq!(again.catalog.photo(id).unwrap().rating, 4);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// The lock is taken in the folder the path leads to, a moment after the stores recorded the folder:
|
||||
/// a path that came to lead to another folder in between (a share mounted as the library opens) is
|
||||
/// refused, and the lock taken there is let go again with its note.
|
||||
#[test]
|
||||
fn a_lock_taken_in_another_folder_than_the_stores_recorded_is_refused() {
|
||||
let base = scratch("lock-race");
|
||||
let (recorded, now) = (base.join("Recorded"), base.join("Now"));
|
||||
std::fs::create_dir_all(&recorded).unwrap();
|
||||
std::fs::create_dir_all(&now).unwrap();
|
||||
let folder = OpenedFolder::at(&recorded).unwrap();
|
||||
|
||||
let e = crate::library::lock_in(&now, &folder).expect_err("the path leads to another folder than the stores recorded");
|
||||
assert!(e.to_string().contains("changed while the library was being opened"), "{e}");
|
||||
assert!(!now.join("catalog.lock.owner").exists(), "the lock taken there is let go again, its note too");
|
||||
|
||||
drop(crate::library::lock_in(&recorded, &folder).expect("the folder the stores recorded"));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// Checking a path before the library open now is closed: the lock this session holds is on the
|
||||
/// folder that was opened, so for the folder that replaced it the answer is what opening it would
|
||||
/// say, that another program has it open, and nothing is closed first.
|
||||
#[test]
|
||||
fn checking_the_path_of_a_replaced_folder_finds_the_lock_of_the_folder_there_now() {
|
||||
let base = scratch("check");
|
||||
let lib = base.join("Lib");
|
||||
let s = open_with_a_saved_change(&lib);
|
||||
s.check_library(&lib).expect("the library that is open keeps its lock when it is opened again");
|
||||
|
||||
let _away = put_another_library_at(&lib);
|
||||
let other_program = LibraryLock::acquire(&lib, "other").unwrap();
|
||||
let e = s.check_library(&lib).expect_err("another program has the folder at the path open");
|
||||
assert!(matches!(e, EngineError::LibraryInUse(_)), "{e:?}");
|
||||
drop(other_program);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
+68
-14
@@ -32,8 +32,8 @@
|
||||
//! (issue #1504).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use lightcraft_raster::Rgba8;
|
||||
|
||||
@@ -60,6 +60,10 @@ const TIDIED: &str = ".lightcraft-thumbs";
|
||||
/// to take a folder for more than a cache.
|
||||
const DROPPINGS: [&str; 3] = [".DS_Store", "desktop.ini", "Thumbs.db"];
|
||||
|
||||
/// How many files a tidy goes through between two looks at the gate ([`DiskCache::set_gate`]):
|
||||
/// a pass over a big cache takes a while, and a `stat` for every file would add to it.
|
||||
pub(crate) const TIDY_GATE_EVERY: usize = 256;
|
||||
|
||||
/// The file that says a folder is a cache, for backup programs and the like (the Cache
|
||||
/// Directory Tagging Specification: the first line is the signature).
|
||||
pub const TAG: &str = "CACHEDIR.TAG";
|
||||
@@ -67,6 +71,9 @@ const TAG_TEXT: &str = "Signature: 8a477f597d28d172789f06886806bc55\n\
|
||||
# This folder holds LightCraft's thumbnail cache. It is safe to delete: LightCraft renders what it needs again.\n\
|
||||
# See https://bford.info/cachedir/\n";
|
||||
|
||||
/// Whether the cache may change its folder now (see [`DiskCache::set_gate`]).
|
||||
pub type WriteGate = Arc<dyn Fn() -> bool + Send + Sync>;
|
||||
|
||||
pub struct DiskCache {
|
||||
dir: PathBuf,
|
||||
/// Bytes the cache may hold (changed in place by [`DiskCache::set_budget`]).
|
||||
@@ -78,6 +85,8 @@ pub struct DiskCache {
|
||||
pub writes: AtomicU64,
|
||||
/// The thumbnails read in this session: a full cache lets them go last ([`Self::prune`]).
|
||||
read: Mutex<std::collections::HashSet<u128>>,
|
||||
/// Asked before anything in the folder is written, renamed or removed (issue #3240).
|
||||
gate: OnceLock<WriteGate>,
|
||||
}
|
||||
|
||||
impl DiskCache {
|
||||
@@ -90,6 +99,7 @@ impl DiskCache {
|
||||
misses: AtomicU64::new(0),
|
||||
writes: AtomicU64::new(0),
|
||||
read: Mutex::new(Default::default()),
|
||||
gate: OnceLock::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +118,28 @@ impl DiskCache {
|
||||
self.budget.store(bytes, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Ask `gate` before this cache writes, renames or removes anything in its folder: a `false`
|
||||
/// leaves the folder as it is (a write is not made and reports `false`, a tidy does nothing).
|
||||
/// The library gives one that says `false` while its path leads to another folder than the one
|
||||
/// it was opened from, so a share mounted over the library neither gets this library's
|
||||
/// thumbnails nor has its own pruned to this library's budget (issue #3240). Reads are not
|
||||
/// gated: a thumbnail is named after what it shows, so another folder's is as good. Set once
|
||||
/// (a second gate is ignored), where the cache is made.
|
||||
pub fn set_gate(&self, gate: WriteGate) {
|
||||
let _ = self.gate.set(gate);
|
||||
}
|
||||
|
||||
/// Whether the folder may be changed now: there is no gate, or it says so.
|
||||
fn writable(&self) -> bool {
|
||||
self.gate.get().is_none_or(|g| g())
|
||||
}
|
||||
|
||||
/// Whether a pass over many files may go on at file number `done`: the gate is looked at every
|
||||
/// [`TIDY_GATE_EVERY`] files, and the pass stops at the first look that says no.
|
||||
fn may_go_on(&self, done: usize) -> bool {
|
||||
done == 0 || !done.is_multiple_of(TIDY_GATE_EVERY) || self.writable()
|
||||
}
|
||||
|
||||
fn path(&self, key: Hash128) -> PathBuf {
|
||||
self.named(key, EXT)
|
||||
}
|
||||
@@ -135,10 +167,11 @@ impl DiskCache {
|
||||
// (taken over by the tidying between the two looks: it is under the new name now)
|
||||
return std::fs::read(&p).ok().map(|bytes| (p, bytes));
|
||||
};
|
||||
// (taken over; if that can't be done it is read where it is, and tried again next time)
|
||||
match std::fs::rename(&old, &p) {
|
||||
Ok(()) => Some((p, bytes)),
|
||||
Err(_) => Some((old, bytes)),
|
||||
// (taken over; if that can't be done, or the gate keeps the folder closed, it is read where
|
||||
// it is, and tried again next time)
|
||||
match self.writable().then(|| std::fs::rename(&old, &p)) {
|
||||
Some(Ok(())) => Some((p, bytes)),
|
||||
_ => Some((old, bytes)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +190,7 @@ impl DiskCache {
|
||||
let now = std::time::SystemTime::now();
|
||||
let unused = std::fs::metadata(&p).and_then(|m| m.modified()).ok().and_then(|at| now.duration_since(at).ok());
|
||||
if unused.is_some_and(|d| d > STALE)
|
||||
&& self.writable()
|
||||
&& let Ok(f) = std::fs::File::options().write(true).open(&p)
|
||||
{
|
||||
let _ = f.set_modified(now);
|
||||
@@ -164,8 +198,10 @@ impl DiskCache {
|
||||
Some(img)
|
||||
}
|
||||
None => {
|
||||
log::warn!("preview cache: dropping unreadable {}", p.display());
|
||||
let _ = std::fs::remove_file(&p);
|
||||
if self.writable() {
|
||||
log::warn!("preview cache: dropping unreadable {}", p.display());
|
||||
let _ = std::fs::remove_file(&p);
|
||||
}
|
||||
self.misses.fetch_add(1, Ordering::Relaxed);
|
||||
None
|
||||
}
|
||||
@@ -198,9 +234,12 @@ impl DiskCache {
|
||||
None
|
||||
}
|
||||
|
||||
/// Write `img` under `key`. Returns whether the file was written (a full or unwritable cache folder
|
||||
/// gives `false`; the cache is unchanged then).
|
||||
/// Write `img` under `key`. Returns whether the file was written (a full or unwritable cache folder,
|
||||
/// or one the gate keeps closed, gives `false`; the cache is unchanged then).
|
||||
pub fn put(&self, key: Hash128, img: &Rgba8) -> bool {
|
||||
if !self.writable() {
|
||||
return false;
|
||||
}
|
||||
let Some(bytes) = encode_jpeg(img) else { return false };
|
||||
let p = self.path(key);
|
||||
let Some(parent) = p.parent() else { return false };
|
||||
@@ -299,11 +338,14 @@ impl DiskCache {
|
||||
pub fn take_over_old(&self, stop: &dyn Fn() -> bool, progress: &dyn Fn(usize, usize)) -> usize {
|
||||
// (listed in full before anything is renamed: a folder that changes while it is listed
|
||||
// lists some of its files twice)
|
||||
if !self.writable() {
|
||||
return 0;
|
||||
}
|
||||
let Some(listed) = self.scan_until(stop) else { return 0 };
|
||||
let old: Vec<(PathBuf, u64)> = listed.into_iter().filter(|f| f.0.extension().is_some_and(|ext| ext == OLD_EXT)).map(|f| (f.0, f.1)).collect();
|
||||
let (mut taken, mut removed, mut blocked) = (0usize, 0u64, false);
|
||||
for (done, (path, len)) in old.iter().enumerate() {
|
||||
if stop() {
|
||||
if stop() || !self.may_go_on(done) {
|
||||
self.forget(removed);
|
||||
return taken;
|
||||
}
|
||||
@@ -328,7 +370,7 @@ impl DiskCache {
|
||||
self.forget(removed);
|
||||
// done, also when the folder holds other things; not when something could not be taken
|
||||
// over (a folder that can't be written: it is tried again at the next open)
|
||||
if !blocked {
|
||||
if !blocked && self.writable() {
|
||||
let _ = std::fs::write(self.dir.join(TIDIED), b"");
|
||||
if self.holds_only_the_cache() {
|
||||
let _ = std::fs::write(self.dir.join(TAG), TAG_TEXT);
|
||||
@@ -373,6 +415,9 @@ impl DiskCache {
|
||||
/// Remove least recently used files until the cache is at most 80 % of its budget: by the
|
||||
/// date of each file, the ones read in this session last.
|
||||
pub fn prune(&self) {
|
||||
if !self.writable() {
|
||||
return;
|
||||
}
|
||||
let mut files = self.scan();
|
||||
let mut total: u64 = files.iter().map(|f| f.1).sum();
|
||||
let target = self.budget() / 5 * 4;
|
||||
@@ -380,8 +425,9 @@ impl DiskCache {
|
||||
let in_use = |p: &Path| key_of(p).is_some_and(|k| read.contains(&k));
|
||||
files.sort_by_cached_key(|f| (in_use(&f.0), f.2));
|
||||
let mut gone = Vec::new();
|
||||
for (p, len, _) in files {
|
||||
if total <= target {
|
||||
for (done, (p, len, _)) in files.into_iter().enumerate() {
|
||||
// (the gate may close midway: a share mounted over the library while a big cache is pruned)
|
||||
if total <= target || !self.may_go_on(done) {
|
||||
break;
|
||||
}
|
||||
if std::fs::remove_file(&p).is_ok() {
|
||||
@@ -412,7 +458,15 @@ impl DiskCache {
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
for (p, _, _) in self.scan() {
|
||||
if !self.writable() {
|
||||
return;
|
||||
}
|
||||
for (done, (p, _, _)) in self.scan().into_iter().enumerate() {
|
||||
if !self.may_go_on(done) {
|
||||
// (the files left are counted again by the next look)
|
||||
*self.total.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
return;
|
||||
}
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
*self.total.lock().unwrap_or_else(|e| e.into_inner()) = Some(0);
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
pub use disk::{DiskCache, decode_jpeg, encode_jpeg, jpeg_dims};
|
||||
pub use disk::{DiskCache, WriteGate, decode_jpeg, encode_jpeg, jpeg_dims};
|
||||
pub use hash::{Hash128, Hasher128, hash_bytes};
|
||||
use lightcraft_raster::Rgba8;
|
||||
pub use lru::{Lru, next_tick};
|
||||
|
||||
@@ -852,3 +852,140 @@ fn a_write_the_pruning_removes_is_not_reported_as_kept() {
|
||||
assert!(roomy.put(hash_bytes(b"fits"), &gradient(64, 64, 9)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The cache's folder as it is: every file with its bytes and its date.
|
||||
fn folder_as_is(dir: &std::path::Path) -> Vec<(String, Vec<u8>, std::time::SystemTime)> {
|
||||
let mut out = Vec::new();
|
||||
for f in files_under(dir) {
|
||||
let p = dir.join(&f);
|
||||
out.push((f, std::fs::read(&p).unwrap(), modified(&p)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Given a cache whose gate says no (the library's path leads to another folder than the one it was
|
||||
/// opened from, issue #3240), when it is asked to write, prune, clear, tidy, or to read a thumbnail
|
||||
/// that it would take over, touch or remove, then its folder is as it was: nothing is written, made,
|
||||
/// renamed or removed, and reads still serve. With the gate open again, all of that works.
|
||||
#[test]
|
||||
fn a_closed_gate_keeps_the_cache_from_changing_its_folder() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let dir = temp_dir("gate");
|
||||
let open = Arc::new(AtomicBool::new(true));
|
||||
let d = DiskCache::new(&dir, 10 << 20);
|
||||
let flag = open.clone();
|
||||
d.set_gate(Arc::new(move || flag.load(Ordering::SeqCst)));
|
||||
|
||||
let (kept, stale, old, junk) = (hash_bytes(b"kept"), hash_bytes(b"stale"), hash_bytes(b"old"), hash_bytes(b"junk"));
|
||||
let path = |k: Hash128, ext: &str| {
|
||||
let hex = k.to_string();
|
||||
dir.join(&hex[..2]).join(format!("{hex}.{ext}"))
|
||||
};
|
||||
assert!(d.put(kept, &gradient(160, 100, 1)));
|
||||
assert!(d.put(stale, &gradient(160, 100, 2)));
|
||||
let jpeg = disk::encode_jpeg(&gradient(160, 100, 3)).unwrap();
|
||||
for (key, ext, bytes) in [(old, "jpg", &jpeg[..]), (junk, "lcthumb", b"not a picture")] {
|
||||
std::fs::create_dir_all(path(key, ext).parent().unwrap()).unwrap();
|
||||
std::fs::write(path(key, ext), bytes).unwrap();
|
||||
}
|
||||
// not used for two months: reading it brings its date forward
|
||||
let long_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(60 * 24 * 3600);
|
||||
std::fs::File::options().write(true).open(path(stale, "lcthumb")).unwrap().set_modified(long_ago).unwrap();
|
||||
let before = folder_as_is(&dir);
|
||||
|
||||
open.store(false, Ordering::SeqCst);
|
||||
assert!(!d.put(hash_bytes(b"new"), &gradient(160, 100, 4)), "not written");
|
||||
assert!(d.get(kept).is_some() && d.get(stale).is_some(), "reads still serve, and touch nothing");
|
||||
assert!(d.get(old).is_some(), "found under the name of before, and not renamed");
|
||||
assert!(d.get(junk).is_none(), "unreadable, and not removed");
|
||||
d.set_budget(1);
|
||||
d.prune();
|
||||
d.clear();
|
||||
assert_eq!(d.take_over_old(&|| false, &|_, _| {}), 0);
|
||||
assert_eq!(folder_as_is(&dir), before, "the folder is as it was");
|
||||
// a folder that isn't there is not made
|
||||
let fresh = temp_dir("gate-fresh").join("thumbs");
|
||||
let nowhere = DiskCache::new(&fresh, 10 << 20);
|
||||
nowhere.set_gate(Arc::new(|| false));
|
||||
assert!(!nowhere.put(kept, &gradient(160, 100, 1)));
|
||||
assert!(!fresh.exists());
|
||||
|
||||
open.store(true, Ordering::SeqCst);
|
||||
d.set_budget(10 << 20);
|
||||
assert_eq!(d.take_over_old(&|| false, &|_, _| {}), 1, "the thumbnail under the name of before is taken over");
|
||||
assert!(d.get(junk).is_none() && !path(junk, "lcthumb").exists(), "an unreadable one goes");
|
||||
assert!(d.put(hash_bytes(b"new"), &gradient(160, 100, 4)));
|
||||
assert!(d.get(stale).is_some() && modified(&path(stale, "lcthumb")) > long_ago, "and one not used for long is touched");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `n` files of the cache's own shape named by the keys `0..n`, all in one shard, holding `bytes`.
|
||||
fn thumbnails_named(dir: &std::path::Path, n: usize, ext: &str, bytes: &[u8]) -> Vec<std::path::PathBuf> {
|
||||
(0..n as u128)
|
||||
.map(|i| {
|
||||
let hex = Hash128((0xab << 120) | i).to_string();
|
||||
let path = dir.join(&hex[..2]).join(format!("{hex}.{ext}"));
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A gate that closes while the cache is pruned or cleared stops the pass at the next look (every
|
||||
/// `TIDY_GATE_EVERY` files), not only at the one before it starts: no more files are removed from
|
||||
/// the folder the library's path leads to now (issue #3240). With the gate open again the rest goes.
|
||||
#[test]
|
||||
fn a_gate_that_closes_during_a_prune_or_a_clear_stops_it() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
let n = disk::TIDY_GATE_EVERY * 2 + 44;
|
||||
for what in ["prune", "clear"] {
|
||||
let dir = temp_dir(&format!("gate-pass-{what}"));
|
||||
let files = thumbnails_named(&dir, n, "lcthumb", b"x");
|
||||
let d = DiskCache::new(&dir, 1);
|
||||
// open for the look before the pass starts and for no other, until it is opened again
|
||||
let (looks, reopened) = (AtomicUsize::new(0), Arc::new(AtomicBool::new(false)));
|
||||
let again = reopened.clone();
|
||||
d.set_gate(Arc::new(move || looks.fetch_add(1, Ordering::SeqCst) < 1 || again.load(Ordering::SeqCst)));
|
||||
let pass = |d: &DiskCache| if what == "prune" { d.prune() } else { d.clear() };
|
||||
|
||||
pass(&d);
|
||||
let left = files.iter().filter(|p| p.exists()).count();
|
||||
assert_eq!(left, n - disk::TIDY_GATE_EVERY, "{what}: stopped at the first look inside the pass");
|
||||
|
||||
reopened.store(true, Ordering::SeqCst);
|
||||
pass(&d);
|
||||
assert_eq!(files.iter().filter(|p| p.exists()).count(), 0, "{what}: with the gate open again the rest goes");
|
||||
assert_eq!(d.known_size(), Some(0), "{what}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same for the takeover of old thumbnails: the gate closed from the progress callback at the
|
||||
/// last file before a look stops it right there, with the files it hadn't got to as they were and the
|
||||
/// folder not marked as tidied, so the rest is done at the next open. (The test above closes the gate
|
||||
/// before the call, which the first look of the takeover catches.)
|
||||
#[test]
|
||||
fn a_gate_that_closes_during_the_takeover_stops_it() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let n = disk::TIDY_GATE_EVERY + 44;
|
||||
let dir = temp_dir("gate-takeover");
|
||||
let jpeg = disk::encode_jpeg(&gradient(32, 20, 3)).unwrap();
|
||||
let old = thumbnails_named(&dir, n, "jpg", &jpeg);
|
||||
let open = Arc::new(AtomicBool::new(true));
|
||||
let d = DiskCache::new(&dir, 100 << 20);
|
||||
let flag = open.clone();
|
||||
d.set_gate(Arc::new(move || flag.load(Ordering::SeqCst)));
|
||||
|
||||
let taken = d.take_over_old(&|| false, &|done, _| {
|
||||
if done == disk::TIDY_GATE_EVERY - 1 {
|
||||
open.store(false, Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
assert_eq!(taken, disk::TIDY_GATE_EVERY, "stopped at the look after the last one it was allowed");
|
||||
let left: Vec<_> = old.iter().filter(|p| p.exists()).collect();
|
||||
assert_eq!(left.len(), n - disk::TIDY_GATE_EVERY, "the others are as they were");
|
||||
assert!(left.iter().all(|p| std::fs::read(p).unwrap() == jpeg && !p.with_extension("lcthumb").exists()));
|
||||
assert!(d.needs_tidying() && !dir.join("CACHEDIR.TAG").exists(), "not finished, so not marked as done");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -18,6 +18,45 @@
|
||||
messages as `CustomEvent`s on the canvas instead of `postMessage` (issue #2270; `docs/web.md`). `?host=parent` wins
|
||||
when a page asks for both.
|
||||
|
||||
### A library is written only to the folder it was opened from
|
||||
- LightCraft wrote a library's files to wherever the library's path led at that moment, not to the folder it had opened.
|
||||
When a share was mounted over the library's folder, or the folder was moved away and another put in its place while
|
||||
the library was open, it wrote into that other folder: it could replace another library's catalog (`catalog.snap`
|
||||
and `catalog.log`) with its own, and closing the library removed the note another program had left in
|
||||
`catalog.lock.owner` to say that it has the library open (issue #3240).
|
||||
- LightCraft now remembers the folder it opened (its device and inode number) and, before every save, checks that the
|
||||
library's path still leads to it. If it doesn't, nothing is written: not the catalog, its log, the library's
|
||||
settings, the lock note or a thumbnail. The not-saved warning says why, names the path and asks you to put the
|
||||
original folder back; your changes are kept in memory, quitting asks first as it does for any unsaved change, and
|
||||
saving goes on by itself once the original folder is at its path again. That holds for photos, albums and presets; a
|
||||
preference that could not be saved is reported where you changed it, and is written with the next preference you
|
||||
save. Opening the library at that path again takes the lock of the folder that is there now, so it is refused while
|
||||
another program has that library open.
|
||||
- Saving keeps working after a drive or share is mounted again. A volume that is mounted again gets a new device
|
||||
number, and some file systems number their folders anew at every mount (FAT and exFAT drives on Linux, sshfs). The
|
||||
folder at the path still counts as the one that was opened when it holds exactly the lock note this session wrote
|
||||
into the folder it opened (the note holds a value no other lock's note has), or when it is the same volume mounted
|
||||
again: the same inode number and the same creation time under another device number (a system that doesn't know
|
||||
when a folder was created can't tell that from another folder). On the same device an inode number is given again
|
||||
to a folder made later, so two creation times that are known and differ are two folders. A copy of the library's
|
||||
folder made while the library was open holds that note too and counts as the library, and so does a clone of its
|
||||
volume; a share mounted over the folder, with another library in it or with nothing, never does. A copy lacks the
|
||||
changes made after it was made: they are written to it by the next snapshot, which holds them all, and until then
|
||||
they are kept in memory and reported as not saved. If neither tells, the folder counts as another one and nothing is
|
||||
written.
|
||||
- Dropping the lock removes the lock note only if it is the one this session wrote, with the bytes it wrote, in the
|
||||
folder it locked or one that holds that note; another program's note is left alone.
|
||||
- Import ▸ Move removes the originals from the card only after the library's catalog is on disk, not just handed over
|
||||
to be written: when the library can't be saved, the originals stay on the card.
|
||||
- On Windows a folder's identity isn't available to the program yet (Rust's standard library offers it only on its
|
||||
nightly builds), so there the check notices a path that no longer leads to a folder, not one that leads to another
|
||||
folder; the lock note is protected there too.
|
||||
- On every system, files outside the library's catalog and settings are still written by path, some of them over what
|
||||
is there: originals copied into the library (always under a new name), Smart Previews, profiles, the face-scan
|
||||
record (`focus-scanned.bin`), the Lightroom import's `Interop` folder, and what is done to the photos stored in the
|
||||
library's `Originals` folder (their sidecars, Save Metadata to File, rename, delete from disk, duplicate and
|
||||
conversion to DNG).
|
||||
|
||||
### Remove Hot Pixels
|
||||
- Detail ▸ Noise Reduction has a new box, Remove Hot Pixels (raws only), on for newly imported raws (issue #1345).
|
||||
At high ISO single photosites read far brighter than all their neighbours and turn into small red, green or blue
|
||||
|
||||
Reference in New Issue
Block a user