Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Merge PR #5421: fix(format): serialise directory bundle saves with a bundle-wide lock

aiongg2c2269ff0b13
diff --cc crates/format/src/store.rs
index 83e6d3fad,374ae587a..b8d08e642
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@@ -383,24 -369,51 +387,55 @@@ pub const DEFAULT_REVERIFY_BUDGET: u64
/// [`Self::set_reverify_budget`]). Over enough saves every object is read again, and a damaged
/// one is rewritten.
pub struct PcraftWriter {
- hash_cache: HashMap<usize, (Weak<Tile>, Hash)>,
+ hash_cache: TileHashCache,
+ blob_hash_cache: BlobHashCache,
/// Compressed objects by bundle path (ZIP mode).
compressed: HashMap<String, Arc<Vec<u8>>>,
+ compressed_budget: usize,
verified_directory: Option<DirectoryVerificationCache>,
reverify_budget: u64,
+ /// How long [`Self::save_dir`] waits for another save of the bundle ([`SAVE_LOCK_WAIT`]).
+ lock_wait: std::time::Duration,
}
impl Default for PcraftWriter {
fn default() -> Self {
Self {
hash_cache: HashMap::new(),
+ blob_hash_cache: HashMap::new(),
compressed: HashMap::new(),
+ compressed_budget: usize::MAX,
verified_directory: None,
reverify_budget: DEFAULT_REVERIFY_BUDGET,
+ lock_wait: SAVE_LOCK_WAIT,
+ }
+ }
+ }
+
+ /// Hold `dir`'s [`SAVE_LOCK`] for a directory save, so two writers (two stores, or two
+ /// processes) can't interleave: each lists the existing objects, writes its own, publishes its
+ /// manifest and removes what that manifest doesn't reference. Interleaved, one writer's cleanup
+ /// could remove an object the other's winning manifest needs (#4957). The lock is the OS's
+ /// advisory file lock, released when the returned file is dropped or the process ends, so a
+ /// crash leaves no stale lock. Another save holding it is waited for up to `wait`; after that the
+ /// save fails without writing anything. A file system without file locks (some network shares)
+ /// saves unlocked, as before.
+ fn lock_bundle(dir: &Path, wait: std::time::Duration) -> Result<Option<std::fs::File>> {
+ let path = dir.join(SAVE_LOCK);
+ validate_bundle_file(dir, &path)?;
+ let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path)?;
+ let start = std::time::Instant::now();
+ loop {
+ match file.try_lock() {
+ Ok(()) => return Ok(Some(file)),
+ Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < wait => std::thread::sleep(std::time::Duration::from_millis(20)),
+ Err(std::fs::TryLockError::WouldBlock) => {
+ return Err(FormatError::Io(std::io::Error::new(
+ std::io::ErrorKind::WouldBlock,
+ format!("another save of {} is in progress; nothing was written", dir.display()),
+ )));
+ }
+ Err(std::fs::TryLockError::Error(_)) => return Ok(None),
}
}
}
@@@ -756,18 -769,16 +791,24 @@@ impl PcraftWriter
self.reverify_budget = bytes;
}
+ /// Cap compressed payload capacity retained between ZIP saves. Clears the previous payload
+ /// cache; tile hashes remain reusable. The default is unbounded; `0` retains no payloads.
+ pub fn set_compressed_cache_budget(&mut self, bytes: usize) {
+ self.compressed_budget = bytes;
+ self.compressed.clear();
+ }
+
+ /// How long a directory save waits for another save of the same bundle to finish before
+ /// failing without writing anything (10 s by default; see [`Self::save_dir`]).
+ pub fn set_lock_wait(&mut self, wait: std::time::Duration) {
+ self.lock_wait = wait;
+ }
+
fn prepare(&mut self, doc: &Document, opts: &SaveOptions) -> Result<Prepared> {
self.hash_cache.retain(|_, (w, _)| w.strong_count() > 0);
+ self.blob_hash_cache.retain(|_, (w, _)| w.strong_count() > 0);
convert::check_nesting(&doc.layers)?;
- let mut c = Collect { hash_cache: Some(&mut self.hash_cache), ..Default::default() };
+ let mut c = Collect { hash_cache: Some(&mut self.hash_cache), blob_hash_cache: Some(&mut self.blob_hash_cache), ..Default::default() };
let document = convert::doc_m(doc, &mut c);
let mut previews = Vec::new();
if let Some(t) = &opts.thumbnail {