diff --git a/Cargo.lock b/Cargo.lock index 9c3e7ddd..87dcc5e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -392,9 +392,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "linux-raw-sys" @@ -402,6 +402,15 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "lock_api" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" +dependencies = [ + "scopeguard", +] + [[package]] name = "memchr" version = "2.8.3" @@ -432,6 +441,7 @@ name = "origin-platform" version = "0.1.0" dependencies = [ "divan", + "parking_lot", "reflink-copy", "rustix", "tempfile", @@ -463,6 +473,7 @@ dependencies = [ "origin-platform", "origin-shared", "origin-src", + "parking_lot", "serde", "similar", "tempfile", @@ -471,6 +482,28 @@ dependencies = [ "zstd", ] +[[package]] +name = "parking_lot" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" +dependencies = [ + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -501,6 +534,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags", +] + [[package]] name = "reflink-copy" version = "0.1.30" @@ -570,6 +612,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "semver" version = "1.0.28" @@ -660,6 +708,12 @@ dependencies = [ "bstr", ] +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + [[package]] name = "strsim" version = "0.11.1" diff --git a/Cargo.toml b/Cargo.toml index 4c63dd4b..e040bb2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ clap = { version = "4.6.7", features = ["derive"] } divan = "0.1.21" ed25519-dalek = "3.0.0" getrandom = "0.4.3" +parking_lot = "0.13.0" reflink-copy = "0.1.30" # Only in origin-platform. The version and features reflink-copy uses on Linux. rustix = { version = "1.1.6", default-features = false, features = ["fs", "std"] } diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index 30ed0d94..1184ff3d 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -21,6 +21,7 @@ clap.workspace = true getrandom.workspace = true origin-platform.workspace = true origin-shared.workspace = true +parking_lot.workspace = true serde.workspace = true similar.workspace = true thiserror.workspace = true diff --git a/apps/origin-src/src/queue/tests/changes.rs b/apps/origin-src/src/queue/tests/changes.rs index e411f47b..7dadba1c 100644 --- a/apps/origin-src/src/queue/tests/changes.rs +++ b/apps/origin-src/src/queue/tests/changes.rs @@ -1,10 +1,10 @@ //! Tests for landing changes: rebasing, stacks, who may land, and keeping a //! landing that waits. -use std::sync::Mutex; use std::thread; use origin_shared::{Statement, Verdict}; +use parking_lot::Mutex; use super::*; @@ -145,12 +145,12 @@ fn concurrent_landings_serialize() { scope.spawn(move || { for &change in chunk { assert!(matches!(repo.land(change)[..], [Landing::Landed { .. }])); - *landed.lock().unwrap() += 1; + *landed.lock() += 1; } }); } }); - assert_eq!(*landed.lock().unwrap(), changes.len()); + assert_eq!(*landed.lock(), changes.len()); let log = repo.store.log(&TargetName::MAIN).unwrap(); assert_eq!(log.len(), changes.len() + 1); for pair in log.windows(2) { diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index a07e736e..5f439db6 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -16,7 +16,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::sync::Arc; use origin_platform::Native; use origin_shared::api::{ @@ -30,6 +30,7 @@ use origin_shared::{ Base, ChangeId, Head, NodeKey, Object, ObjectId, ObjectKind, Principal, PrincipalName, RecordId, Statement, StatementId, TargetName, }; +use parking_lot::{Condvar, Mutex, MutexGuard}; use crate::annotations::{AnnotateError, Annotations}; use crate::index::Index; @@ -519,10 +520,7 @@ impl Indexes { fn take(&self, most: usize) -> Taken<'_> { let mut state = self.state(); while state.kept.is_empty() && state.taken >= most { - state = self - .returned - .wait(state) - .unwrap_or_else(PoisonError::into_inner); + self.returned.wait(&mut state); } state.taken += 1; Taken { @@ -532,7 +530,7 @@ impl Indexes { } fn state(&self) -> MutexGuard<'_, IndexesState> { - self.state.lock().unwrap_or_else(PoisonError::into_inner) + self.state.lock() } } diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 6320fb0f..e2679668 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -25,13 +25,14 @@ use std::io; use std::num::NonZero; use std::panic; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::Arc; use std::thread; use std::time::{Duration, SystemTime}; use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform, WritableError}; use origin_shared::object::{DecodeError, IdMismatch}; use origin_shared::{EncodedObject, Head, ObjectId, TargetName, TypedId}; +use parking_lot::Mutex; use crate::index::Entry; use crate::oplog::{Actor, Effect}; @@ -528,10 +529,7 @@ impl Batch<'_, P> { .map_err(|source| StoreError::io(&path, source))?; self.write.stage(path, &compressed)?; if let Some(entry) = entry { - self.entries - .lock() - .unwrap_or_else(PoisonError::into_inner) - .push(entry); + self.entries.lock().push(entry); } Ok(true) } @@ -576,10 +574,7 @@ impl Batch<'_, P> { /// collection may have rewritten a pack without the object, and a writer /// must never skip an object that is gone. fn packed(&self, id: ObjectId) -> Result { - let mut read = self - .manifest_read - .lock() - .unwrap_or_else(PoisonError::into_inner); + let mut read = self.manifest_read.lock(); if !*read { self.store.reload_packs()?; *read = true; @@ -605,10 +600,7 @@ impl Batch<'_, P> { /// Fails if an object cannot be renamed into place, a directory cannot be /// synced, or the op log cannot be appended to. pub fn commit(self) -> Result<(), StoreError> { - let entries = self - .entries - .into_inner() - .unwrap_or_else(PoisonError::into_inner); + let entries = self.entries.into_inner(); if entries.is_empty() { return Ok(self.write.commit()?); } @@ -711,9 +703,9 @@ impl StoreError { pub(crate) mod tests { use std::fs::File; use std::slice; - use std::sync::Mutex; use origin_platform::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, ReadAt}; + use parking_lot::Mutex; use origin_shared::{Record, Tree, TreeId}; @@ -739,18 +731,18 @@ pub(crate) mod tests { impl Durability for Recorder { fn sync_file(&self, file: &File) -> io::Result<()> { - self.0.lock().unwrap().push(Synced::File); + self.0.lock().push(Synced::File); Native::default().sync_file(file) } fn sync_dir(&self, dir: &Path) -> io::Result<()> { - self.0.lock().unwrap().push(Synced::Dir(dir.to_owned())); + self.0.lock().push(Synced::Dir(dir.to_owned())); Native::default().sync_dir(dir) } fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { let files: Vec<_> = files.into_iter().collect(); - self.0.lock().unwrap().push(Synced::Batch(files.len())); + self.0.lock().push(Synced::Batch(files.len())); Native::default().sync_batch(files) } } @@ -778,13 +770,13 @@ pub(crate) mod tests { store.init().unwrap(); let blob = EncodedObject::blob(b"hello"); store.write_all(slice::from_ref(&blob)).unwrap(); - store.platform.0.lock().unwrap().clear(); + store.platform.0.lock().clear(); // Its writer may not have synced it yet, if another one wrote it. assert_eq!(store.write_all(slice::from_ref(&blob)).unwrap(), 0); let shard = store.path(blob.id()).parent().unwrap().to_owned(); assert_eq!( - store.platform.0.into_inner().unwrap(), + store.platform.0.into_inner(), [Synced::Batch(0), Synced::Dir(shard)] ); } @@ -796,7 +788,7 @@ pub(crate) mod tests { store.init().unwrap(); let blob = EncodedObject::blob(b"hello"); store.write_all(slice::from_ref(&blob)).unwrap(); - store.platform.0.lock().unwrap().clear(); + store.platform.0.lock().clear(); let batch = store.batch(); assert!(batch.depend(blob.id()).unwrap()); @@ -804,7 +796,7 @@ pub(crate) mod tests { batch.commit().unwrap(); let shard = store.path(blob.id()).parent().unwrap().to_owned(); assert_eq!( - store.platform.0.into_inner().unwrap(), + store.platform.0.into_inner(), [Synced::Batch(0), Synced::Dir(shard)] ); } diff --git a/apps/origin-src/src/store/packs.rs b/apps/origin-src/src/store/packs.rs index f8b08434..2eadef67 100644 --- a/apps/origin-src/src/store/packs.rs +++ b/apps/origin-src/src/store/packs.rs @@ -41,11 +41,12 @@ use std::fmt; use std::fs::{self, File}; use std::io::{self, Read}; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, PoisonError, RwLock}; +use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use origin_platform::{LockMode, LockedFile, Platform, ReadAt}; use origin_shared::{Digest, ObjectId}; +use parking_lot::{Mutex, RwLock}; use super::{Store, StoreError}; @@ -73,7 +74,7 @@ impl Packs { /// The pack holding `id` among those loaded, and where it is. pub(super) fn find(&self, id: ObjectId) -> Option<(Arc, Location)> { - let manifest = self.manifest.read().unwrap_or_else(PoisonError::into_inner); + let manifest = self.manifest.read(); manifest .packs .iter() @@ -81,13 +82,13 @@ impl Packs { } fn loaded(&self) -> Vec> { - let manifest = self.manifest.read().unwrap_or_else(PoisonError::into_inner); + let manifest = self.manifest.read(); manifest.packs.clone() } /// Whether the manifest is due to be read again. fn stale(&self) -> bool { - let read_at = self.read_at.lock().unwrap_or_else(PoisonError::into_inner); + let read_at = self.read_at.lock(); read_at.is_none_or(|at| at.elapsed() >= Self::RELOAD_AFTER) } } @@ -342,31 +343,17 @@ impl Store

{ let path = dir.join(Self::MANIFEST); let mut missing_from = None; loop { - *self - .packs - .read_at - .lock() - .unwrap_or_else(PoisonError::into_inner) = Some(Instant::now()); + *self.packs.read_at.lock() = Some(Instant::now()); let bytes = match fs::read(&path) { Ok(bytes) => bytes, Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(), Err(source) => return Err(StoreError::io(&path, source)), }; let current = |manifest: &Manifest| manifest.bytes.as_ref() == Some(&bytes); - if current( - &self - .packs - .manifest - .read() - .unwrap_or_else(PoisonError::into_inner), - ) { + if current(&self.packs.manifest.read()) { return Ok(()); } - let mut manifest = self - .packs - .manifest - .write() - .unwrap_or_else(PoisonError::into_inner); + let mut manifest = self.packs.manifest.write(); if current(&manifest) { return Ok(()); } @@ -738,12 +725,12 @@ impl Store

{ #[cfg(test)] mod tests { use std::slice; - use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread; use origin_platform::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Native, Op}; use origin_shared::EncodedObject; + use parking_lot::Mutex; use super::super::tests::{Recorder, Synced, store}; use super::*; @@ -880,7 +867,7 @@ mod tests { |store: &Store| -> Vec<_> { store.packs.loaded().iter().map(|pack| pack.id).collect() }; assert_readable(&other, &first); assert_ne!(ids(&other), ids(&store), "still reading the retired pack"); - *other.packs.read_at.lock().unwrap() = Instant::now().checked_sub(Packs::RELOAD_AFTER); + *other.packs.read_at.lock() = Instant::now().checked_sub(Packs::RELOAD_AFTER); assert_readable(&other, &first); assert_eq!(ids(&other), ids(&store)); } @@ -910,13 +897,13 @@ mod tests { let objects = objects(0, 10); store.write_all(&objects).unwrap(); store.compact().unwrap(); - store.platform.0.lock().unwrap().clear(); + store.platform.0.lock().clear(); // The compactor may not have synced the manifest naming it yet. assert_eq!(store.write_all(&objects[..1]).unwrap(), 0); let packs = store.packs_dir(); assert_eq!( - store.platform.0.into_inner().unwrap(), + store.platform.0.into_inner(), [Synced::Batch(0), Synced::Dir(packs)] ); } @@ -1010,13 +997,13 @@ mod tests { impl Crashing { /// Fails the batch sync after the next `batches`. fn crash_after(&self, batches: usize) { - *self.0.lock().unwrap() = Some(batches); + *self.0.lock() = Some(batches); } } impl Durability for Crashing { fn sync_batch<'f>(&self, files: impl IntoIterator) -> Result<(), Error> { - let mut left = self.0.lock().unwrap(); + let mut left = self.0.lock(); match *left { Some(0) => { *left = None; diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index e5b152da..1297aedb 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -398,11 +398,11 @@ impl Store

{ #[cfg(test)] mod tests { - use std::sync::Mutex; use std::thread; use origin_platform::Native; use origin_shared::{AcceptanceBody, NodeKey, Tree, TreeId}; + use parking_lot::Mutex; use super::*; use crate::store::tests::{Recorder, Synced}; @@ -524,7 +524,7 @@ mod tests { loop { let head = store.head(&main).unwrap(); match store.append(&main, &acceptance(&main, head)) { - Ok(id) => break landed.lock().unwrap().push(id), + Ok(id) => break landed.lock().push(id), Err(StoreError::Conflict { .. }) => {} Err(error) => panic!("{error}"), } @@ -535,7 +535,7 @@ mod tests { }); let log = store.log(&main).unwrap(); assert_eq!(log.len(), 24); - let mut landed = landed.into_inner().unwrap(); + let mut landed = landed.into_inner(); landed.sort(); let mut sorted = log.clone(); sorted.sort(); @@ -606,14 +606,14 @@ mod tests { let log = store.target_files(main.id()).log(); let mut file = fs::OpenOptions::new().append(true).open(log).unwrap(); writeln!(file, "{}", unsynced.encode().id()).unwrap(); - store.platform.0.lock().unwrap().clear(); + store.platform.0.lock().clear(); assert!(store.append(&main, &unsynced).is_err(), "it's there now"); let targets = store.targets_dir(); let target = targets.join(main.id().to_hex()); let shard = &unsynced.encode().id().to_hex()[..2]; assert_eq!( - store.platform.0.into_inner().unwrap(), + store.platform.0.into_inner(), [ Synced::Batch(0), Synced::Dir(dir.path().join(".origin/objects/loose").join(shard)), @@ -634,14 +634,14 @@ mod tests { store.init().unwrap(); let main = TargetName::MAIN; land(&store, &main, 1); - store.platform.0.lock().unwrap().clear(); + store.platform.0.lock().clear(); let id = land(&store, &main, 1)[0]; let hex = id.to_hex(); let targets = store.targets_dir(); let target = targets.join(main.id().to_hex()); assert_eq!( - store.platform.0.into_inner().unwrap(), + store.platform.0.into_inner(), [ // The acceptance and its op log entry, which costs no sync // of its own. diff --git a/apps/origin-src/src/worktree.rs b/apps/origin-src/src/worktree.rs index 3cc95b8c..8db856cb 100644 --- a/apps/origin-src/src/worktree.rs +++ b/apps/origin-src/src/worktree.rs @@ -20,8 +20,8 @@ use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; use std::panic; use std::path::{Path, PathBuf}; +use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Mutex, OnceLock}; use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; @@ -30,6 +30,7 @@ use origin_shared::object::{DecodeError, Reader}; use origin_shared::{ EncodedObject, EntryKind, EntryName, ObjectId, Record, RepoPath, Tree, TreeEntry, TreeId, }; +use parking_lot::Mutex; use crate::store::{Store, StoreError}; use crate::tree::FileChange; @@ -860,10 +861,7 @@ impl<'a, P: Platform> Worktree<'a, P> { }; local.push((index, map(item)?)); } - results - .lock() - .expect("no worker panics holding the lock") - .extend(local); + results.lock().extend(local); Ok(()) }) }) @@ -872,9 +870,7 @@ impl<'a, P: Platform> Worktree<'a, P> { .into_iter() .try_for_each(|handle| handle.join().expect("snapshot threads do not panic")) })?; - let mut results = results - .into_inner() - .expect("no worker panics holding the lock"); + let mut results = results.into_inner(); results.sort_unstable_by_key(|(index, _)| *index); Ok(results.into_iter().map(|(_, result)| result).collect()) } diff --git a/crates/origin-platform/Cargo.toml b/crates/origin-platform/Cargo.toml index 596531f6..b64502d7 100644 --- a/crates/origin-platform/Cargo.toml +++ b/crates/origin-platform/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true repository.workspace = true [dependencies] +parking_lot.workspace = true reflink-copy.workspace = true rustix.workspace = true thiserror.workspace = true diff --git a/crates/origin-platform/src/durability.rs b/crates/origin-platform/src/durability.rs index befef1ad..5459d602 100644 --- a/crates/origin-platform/src/durability.rs +++ b/crates/origin-platform/src/durability.rs @@ -7,9 +7,10 @@ use std::panic; use std::path::{Path, PathBuf}; use std::process; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, PoisonError}; use std::thread; +use parking_lot::Mutex; + use crate::{Error, Op}; /// Flushes written data to stable storage, so it survives a crash or a power @@ -161,7 +162,7 @@ impl<'a, P: Durability> DurableWrite<'a, P> { let _ = fs::remove_file(&temp); return Err(error); } - let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); + let mut staged = self.staged.lock(); staged.dirs.insert(Self::parent(&path).to_owned()); staged.dirs.extend(relied_on); staged.files.push((temp, path)); @@ -172,7 +173,7 @@ impl<'a, P: Durability> DurableWrite<'a, P> { /// staged in it: for a file another write published, which this one /// relies on, and may not have synced yet. pub fn sync_dir_with(&self, dir: impl Into) { - let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); + let mut staged = self.staged.lock(); staged.dirs.insert(dir.into()); } @@ -180,7 +181,7 @@ impl<'a, P: Durability> DurableWrite<'a, P> { /// batch: [`DurableWrite::commit`] syncs it with the staged files, before /// publishing any of them. pub fn sync_with(&self, path: impl Into) { - let mut staged = self.staged.lock().unwrap_or_else(PoisonError::into_inner); + let mut staged = self.staged.lock(); staged.in_place.push(path.into()); } @@ -248,10 +249,7 @@ impl<'a, P: Durability> DurableWrite<'a, P> { /// or if a file cannot be renamed or a directory cannot be synced. Files /// renamed before such a failure are visible but may not be durable. pub fn commit(mut self) -> Result<(), Error> { - let staged = self - .staged - .get_mut() - .unwrap_or_else(PoisonError::into_inner); + let staged = self.staged.get_mut(); let temps = staged.files.iter().map(|(temp, _)| temp.as_path()); self.platform .sync_batch(temps.chain(staged.in_place.iter().map(PathBuf::as_path)))?; @@ -300,10 +298,7 @@ impl<'a, P: Durability> DurableWrite<'a, P> { impl

Drop for DurableWrite<'_, P> { /// Removes the temporary files that were not published. fn drop(&mut self) { - let staged = self - .staged - .get_mut() - .unwrap_or_else(PoisonError::into_inner); + let staged = self.staged.get_mut(); for (temp, _) in &staged.files { // Best effort: a leftover is garbage that readers skip. After a // failed rename, some of these are already published. @@ -372,11 +367,11 @@ mod tests { impl Recorder { fn record(&self, call: Call) { - self.calls.lock().unwrap().push(call); + self.calls.lock().push(call); } fn take(&self) -> Vec { - std::mem::take(&mut self.calls.lock().unwrap()) + std::mem::take(&mut self.calls.lock()) } }