pixie_pi/tools/
file_mutex.rs1use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, OnceLock};
9
10use tokio::sync::Mutex;
11
12type PathLocks = std::sync::Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>;
13
14static LOCKS: OnceLock<PathLocks> = OnceLock::new();
15
16fn locks() -> &'static PathLocks {
17 LOCKS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
18}
19
20async fn lock_for(path: &Path) -> Arc<Mutex<()>> {
23 let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
24 let mut map = locks().lock().unwrap();
25 map.entry(key)
26 .or_insert_with(|| Arc::new(Mutex::new(())))
27 .clone()
28}
29
30pub async fn with_file_lock<F, R>(path: &Path, f: F) -> R
32where
33 F: std::future::Future<Output = R>,
34{
35 let lock = lock_for(path).await;
36 let _guard = lock.lock().await;
40 f.await
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46 use std::sync::atomic::{AtomicUsize, Ordering};
47 use std::sync::Arc;
48
49 #[tokio::test]
50 async fn serializes_concurrent_access_to_the_same_path() {
51 let path: PathBuf = std::env::temp_dir().join("pi-file-mutex-test-fixed.bin");
55 let in_flight = Arc::new(AtomicUsize::new(0));
56 let max_in_flight = Arc::new(AtomicUsize::new(0));
57
58 let mut handles = Vec::new();
59 for _ in 0..8 {
60 let path = path.clone();
61 let in_flight = in_flight.clone();
62 let max_in_flight = max_in_flight.clone();
63 handles.push(tokio::spawn(async move {
64 with_file_lock(&path, async {
65 let n = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
66 max_in_flight.fetch_max(n, Ordering::SeqCst);
67 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
69 in_flight.fetch_sub(1, Ordering::SeqCst);
70 })
71 .await;
72 }));
73 }
74 for h in handles {
75 let _ = h.await;
76 }
77
78 assert_eq!(
79 max_in_flight.load(Ordering::SeqCst),
80 1,
81 "concurrent same-file critical sections overlapped"
82 );
83 }
84}