Skip to main content

aft_base/
lock_diagnostics.rs

1//! Records the current holder's source line and acquisition time using atomics,
2//! so watchdog diagnostics never need to lock the observed mutex.
3
4use std::ops::{Deref, DerefMut};
5use std::panic::Location;
6use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10pub struct LockDiagnostics {
11    site_file: &'static str,
12    origin: Instant,
13    held_since_ms_plus_one: AtomicU64,
14    line: AtomicUsize,
15}
16
17impl LockDiagnostics {
18    pub fn new(site_file: &'static str) -> Arc<Self> {
19        Arc::new(Self {
20            site_file,
21            origin: Instant::now(),
22            held_since_ms_plus_one: AtomicU64::new(0),
23            line: AtomicUsize::new(0),
24        })
25    }
26
27    #[track_caller]
28    pub fn hold(&self) -> LockHold<'_> {
29        self.line
30            .store(Location::caller().line() as usize, Ordering::Relaxed);
31        self.held_since_ms_plus_one
32            .store(self.now_ms().saturating_add(1), Ordering::Release);
33        LockHold(self)
34    }
35
36    fn now_ms(&self) -> u64 {
37        u64::try_from(self.origin.elapsed().as_millis()).unwrap_or(u64::MAX)
38    }
39
40    pub fn snapshot(&self) -> String {
41        let since = self.held_since_ms_plus_one.load(Ordering::Acquire);
42        if since == 0 {
43            return "holder=none".to_string();
44        }
45        format!(
46            "holder={}:{} held_for_ms={}",
47            self.site_file,
48            self.line.load(Ordering::Relaxed),
49            self.now_ms().saturating_sub(since - 1),
50        )
51    }
52}
53
54pub struct LockHold<'a>(&'a LockDiagnostics);
55
56impl Drop for LockHold<'_> {
57    fn drop(&mut self) {
58        self.0.held_since_ms_plus_one.store(0, Ordering::Release);
59    }
60}
61
62#[rustfmt::skip]
63test_support_visibility! {
64/// Records every acquisition, including timed and nonblocking probes. The
65/// evidence guard drops before the mutex guard unlocks, so a previous holder
66/// cannot clear a subsequent holder's record.
67pub(crate) struct TrackedMutex<T> {
68    mutex: parking_lot::Mutex<T>,
69    diagnostics: Arc<LockDiagnostics>,
70}
71}
72
73impl<T> TrackedMutex<T> {
74    pub(crate) fn new(value: T, site_file: &'static str) -> Self {
75        Self {
76            mutex: parking_lot::Mutex::new(value),
77            diagnostics: LockDiagnostics::new(site_file),
78        }
79    }
80
81    pub(crate) fn diagnostics(&self) -> Arc<LockDiagnostics> {
82        Arc::clone(&self.diagnostics)
83    }
84
85    #[rustfmt::skip]
86    test_support_visibility! {
87
88    #[track_caller]
89    pub(crate) fn lock(&self) -> TrackedGuard<'_, T> {
90        let guard = self.mutex.lock();
91        TrackedGuard {
92            _hold: self.diagnostics.hold(),
93            guard,
94        }
95    }
96    }
97
98    #[track_caller]
99    pub(crate) fn try_lock(&self) -> Option<TrackedGuard<'_, T>> {
100        let guard = self.mutex.try_lock()?;
101        Some(TrackedGuard {
102            _hold: self.diagnostics.hold(),
103            guard,
104        })
105    }
106
107    #[track_caller]
108    pub(crate) fn try_lock_for(&self, timeout: Duration) -> Option<TrackedGuard<'_, T>> {
109        let guard = self.mutex.try_lock_for(timeout)?;
110        Some(TrackedGuard {
111            _hold: self.diagnostics.hold(),
112            guard,
113        })
114    }
115}
116
117#[rustfmt::skip]
118test_support_visibility! {
119pub(crate) struct TrackedGuard<'a, T> {
120    _hold: LockHold<'a>,
121    guard: parking_lot::MutexGuard<'a, T>,
122}
123}
124
125impl<T> Deref for TrackedGuard<'_, T> {
126    type Target = T;
127    fn deref(&self) -> &T {
128        &self.guard
129    }
130}
131
132impl<T> DerefMut for TrackedGuard<'_, T> {
133    fn deref_mut(&mut self) -> &mut T {
134        &mut self.guard
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn holder_evidence_survives_failed_probe_and_clears_on_release() {
144        let mutex = TrackedMutex::new(0, file!());
145        let diagnostics = mutex.diagnostics();
146        assert_eq!(diagnostics.snapshot(), "holder=none");
147        let line = line!() + 1;
148        let held = mutex.lock();
149        assert!(diagnostics
150            .snapshot()
151            .contains(&format!("holder={}:{line} held_for_ms=", file!())));
152        assert!(mutex.try_lock().is_none());
153        assert!(diagnostics
154            .snapshot()
155            .contains(&format!("holder={}:{line} held_for_ms=", file!())));
156        drop(held);
157        assert_eq!(diagnostics.snapshot(), "holder=none");
158        let _held = mutex.try_lock_for(Duration::from_millis(1)).unwrap();
159        assert!(diagnostics.snapshot().contains("held_for_ms="));
160    }
161}