Skip to main content

pixie_pi/tools/
file_mutex.rs

1//! Per-file mutation lock (`core/tools/file-mutation-queue.ts`).
2//!
3//! Concurrent write/edit calls to the *same* file must be serialized; this
4//! hands out one async mutex per canonical path.
5
6use 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
20/// Acquire the per-file mutex, canonicalizing the path. Falls back to the
21/// literal path if canonicalization fails (e.g. file does not yet exist).
22async 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
30/// Run `f` while holding the per-file lock for `path`.
31pub 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    // Actually acquire the per-file mutex: `lock_for` only *hands out* the
37    // shared mutex for this path; without this `.lock().await` two concurrent
38    // edits to the same file would race (lost update).
39    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        // Many tasks run critical sections on the same path; they must not
52        // overlap. Before the fix `with_file_lock` never acquired the mutex, so
53        // every task entered its section at once and `max_in_flight` was > 1.
54        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                    // Yield points so concurrent (buggy) runs would interleave.
68                    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}