|
| 1 | +//! File locking abstractions to make directory locks easy and safe. |
| 2 | +//! |
| 3 | +//! Directory structures are typically represented by a struct containing the directory path, |
| 4 | +//! which then has methods for getting files or directories within it. This struct should implement |
| 5 | +//! `PathsAccess`, and then instead of passing it around directly, it should be stored in a |
| 6 | +//! [`DirectoryStructureLock`]. This ensures that paths cannot be accessed without holding the appropriate |
| 7 | +//! lock. |
| 8 | +//! |
| 9 | +//! Temporary locks can be acquired using the `with_read` and `with_write` methods, which take |
| 10 | +//! async closures. For locks that should be stored in a structure, `into_read` and `into_write` can be used |
| 11 | +//! to convert the lock into an owned guard. |
| 12 | +//! |
| 13 | +//! When making low-level functions that might be composed into higher-level operations, these functions should |
| 14 | +//! typically take `LRead<&T>` or `LWrite<&T>` parameters, rather than `&T`. This makes sure the composed function |
| 15 | +//! will demand the right kind of lock, when writes are hidden in what looks at first glance like a read operation. |
| 16 | +
|
| 17 | +use crate::{fs, prelude::*}; |
| 18 | +use snafu::{ResultExt, Snafu}; |
| 19 | +use std::{fs::File, io, ops::Deref}; |
| 20 | +use tokio::{sync::RwLock, task::spawn_blocking}; |
| 21 | + |
| 22 | +/// Directory lock ensuring safe concurrency around filesystem operations. |
| 23 | +pub struct DirectoryStructureLock<T: PathsAccess> { |
| 24 | + paths_access: T, |
| 25 | + lock_file: RwLock<File>, |
| 26 | + lock_path: PathBuf, |
| 27 | +} |
| 28 | + |
| 29 | +/// A directory structure, typically with methods to access specific paths within it. |
| 30 | +/// |
| 31 | +/// One file within it is selected as the file for advisory locks. |
| 32 | +pub trait PathsAccess: Send + Sync + 'static { |
| 33 | + /// Path to the canonical file for locking the directory structure. Usually `$dir/.lock`. |
| 34 | + fn lock_file(&self) -> PathBuf; |
| 35 | +} |
| 36 | + |
| 37 | +impl<T: PathsAccess> DirectoryStructureLock<T> { |
| 38 | + /// Creates a new lock, implicitly calling [`fs::create_dir_all`] on the parent. |
| 39 | + pub fn open_or_create(paths_access: T) -> Result<Self, LockError> { |
| 40 | + let lock_path = paths_access.lock_file(); |
| 41 | + fs::create_dir_all(lock_path.parent().unwrap())?; |
| 42 | + let lock_file = |
| 43 | + File::create(&lock_path).context(OpenLockFileFailedSnafu { path: &lock_path })?; |
| 44 | + Ok(Self { |
| 45 | + paths_access, |
| 46 | + lock_file: RwLock::const_new(lock_file), |
| 47 | + lock_path, |
| 48 | + }) |
| 49 | + } |
| 50 | + |
| 51 | + /// Converts the lock structure into an owned read-lock. |
| 52 | + pub async fn into_read(self) -> Result<DirectoryStructureGuardOwned<LRead<T>>, LockError> { |
| 53 | + spawn_blocking(move || { |
| 54 | + let lock_file = self.lock_file.into_inner(); |
| 55 | + lock_file.lock_shared().context(LockFailedSnafu { |
| 56 | + lock_path: self.lock_path, |
| 57 | + })?; |
| 58 | + Ok(DirectoryStructureGuardOwned { |
| 59 | + paths_access: LRead(self.paths_access), |
| 60 | + guard: lock_file, |
| 61 | + }) |
| 62 | + }) |
| 63 | + .await |
| 64 | + .unwrap() |
| 65 | + } |
| 66 | + |
| 67 | + /// Converts the lock structure into an owned write-lock. |
| 68 | + pub async fn into_write(self) -> Result<DirectoryStructureGuardOwned<LWrite<T>>, LockError> { |
| 69 | + spawn_blocking(move || { |
| 70 | + let lock_file = self.lock_file.into_inner(); |
| 71 | + lock_file.lock().context(LockFailedSnafu { |
| 72 | + lock_path: self.lock_path, |
| 73 | + })?; |
| 74 | + Ok(DirectoryStructureGuardOwned { |
| 75 | + paths_access: LWrite(self.paths_access), |
| 76 | + guard: lock_file, |
| 77 | + }) |
| 78 | + }) |
| 79 | + .await |
| 80 | + .unwrap() |
| 81 | + } |
| 82 | + |
| 83 | + /// Accesses the directory structure under a read lock. |
| 84 | + pub async fn with_read<R>(&self, f: impl AsyncFnOnce(LRead<&T>) -> R) -> Result<R, LockError> { |
| 85 | + let guard = self.lock_file.read().await; |
| 86 | + let lock_file = guard.try_clone().context(HandleCloneFailedSnafu { |
| 87 | + path: &self.lock_path, |
| 88 | + })?; |
| 89 | + spawn_blocking(move || lock_file.lock_shared()) |
| 90 | + .await |
| 91 | + .unwrap() |
| 92 | + .context(LockFailedSnafu { |
| 93 | + lock_path: &self.lock_path, |
| 94 | + })?; |
| 95 | + let ret = f(LRead(&self.paths_access)).await; |
| 96 | + guard.unlock().context(LockFailedSnafu { |
| 97 | + lock_path: &self.lock_path, |
| 98 | + })?; |
| 99 | + Ok(ret) |
| 100 | + } |
| 101 | + |
| 102 | + /// Accesses the directory structure under a write lock. |
| 103 | + pub async fn with_write<R>( |
| 104 | + &self, |
| 105 | + f: impl AsyncFnOnce(LWrite<&T>) -> R, |
| 106 | + ) -> Result<R, LockError> { |
| 107 | + let guard = self.lock_file.write().await; |
| 108 | + let lock_file = guard.try_clone().context(HandleCloneFailedSnafu { |
| 109 | + path: &self.lock_path, |
| 110 | + })?; |
| 111 | + spawn_blocking(move || lock_file.lock()) |
| 112 | + .await |
| 113 | + .unwrap() |
| 114 | + .context(LockFailedSnafu { |
| 115 | + lock_path: &self.lock_path, |
| 116 | + })?; |
| 117 | + let ret = f(LWrite(&self.paths_access)).await; |
| 118 | + guard.unlock().context(LockFailedSnafu { |
| 119 | + lock_path: &self.lock_path, |
| 120 | + })?; |
| 121 | + Ok(ret) |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +#[derive(Debug, Snafu)] |
| 126 | +pub enum LockError { |
| 127 | + #[snafu(transparent)] |
| 128 | + CreateDirFailed { source: crate::fs::Error }, |
| 129 | + #[snafu(display("failed to create or open lock file '{path}'"))] |
| 130 | + OpenLockFileFailed { source: io::Error, path: PathBuf }, |
| 131 | + #[snafu(display("failed to lock the file '{lock_path}'"))] |
| 132 | + LockFailed { |
| 133 | + source: io::Error, |
| 134 | + lock_path: PathBuf, |
| 135 | + }, |
| 136 | + #[snafu(display("failed to clone lock file handle '{path}'"))] |
| 137 | + HandleCloneFailed { source: io::Error, path: PathBuf }, |
| 138 | +} |
| 139 | + |
| 140 | +/// File lock guard. Do not use as a temporary in an expression - if you are making a temporary lock, use `with_*`. |
| 141 | +#[clippy::has_significant_drop] |
| 142 | +pub struct DirectoryStructureGuardOwned<T> { |
| 143 | + paths_access: T, |
| 144 | + guard: File, |
| 145 | +} |
| 146 | + |
| 147 | +impl<T> Deref for DirectoryStructureGuardOwned<T> { |
| 148 | + type Target = T; |
| 149 | + |
| 150 | + fn deref(&self) -> &Self::Target { |
| 151 | + &self.paths_access |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +impl<T> Drop for DirectoryStructureGuardOwned<T> { |
| 156 | + fn drop(&mut self) { |
| 157 | + _ = self.guard.unlock(); |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +pub struct LRead<T>(T); |
| 162 | +pub struct LWrite<T>(T); |
| 163 | + |
| 164 | +impl<T> Deref for LRead<T> { |
| 165 | + type Target = T; |
| 166 | + |
| 167 | + fn deref(&self) -> &Self::Target { |
| 168 | + &self.0 |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +impl<T> Deref for LWrite<T> { |
| 173 | + type Target = T; |
| 174 | + |
| 175 | + fn deref(&self) -> &Self::Target { |
| 176 | + &self.0 |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +impl<'a, T> LWrite<&'a T> { |
| 181 | + pub fn read(&self) -> LRead<&'a T> { |
| 182 | + LRead(self.0) |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +impl<T> LWrite<T> { |
| 187 | + pub fn as_ref(&self) -> LWrite<&T> { |
| 188 | + LWrite(&self.0) |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +impl<T> LRead<T> { |
| 193 | + pub fn as_ref(&self) -> LRead<&T> { |
| 194 | + LRead(&self.0) |
| 195 | + } |
| 196 | +} |
0 commit comments