agentmux_srv_core/backend/storage/
timed_mutex.rs1use std::ops::{Deref, DerefMut};
14use std::panic::Location;
15use std::sync::atomic::{AtomicU64, Ordering};
16use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult};
17use std::time::{Duration, Instant};
18
19pub const SLOW: Duration = Duration::from_millis(250);
21const LOG_EVERY: Duration = Duration::from_millis(500);
23
24pub struct TimedMutex<T> {
26 inner: Mutex<T>,
27 store: &'static str,
28}
29
30pub struct TimedGuard<'a, T> {
32 guard: MutexGuard<'a, T>,
33 store: &'static str,
34 site: &'static Location<'static>,
35 waited: Duration,
36 got: Instant,
37}
38
39impl<T> TimedMutex<T> {
40 pub fn new(value: T, store: &'static str) -> Self {
41 Self {
42 inner: Mutex::new(value),
43 store,
44 }
45 }
46
47 #[track_caller]
49 pub fn lock(&self) -> LockResult<TimedGuard<'_, T>> {
50 let site = Location::caller();
51 let asked = Instant::now();
52 match self.inner.lock() {
53 Ok(guard) => Ok(self.wrap(guard, site, asked)),
54 Err(poisoned) => Err(PoisonError::new(self.wrap(
55 poisoned.into_inner(),
56 site,
57 asked,
58 ))),
59 }
60 }
61
62 #[track_caller]
64 pub fn try_lock(&self) -> TryLockResult<TimedGuard<'_, T>> {
65 let site = Location::caller();
66 let asked = Instant::now();
67 match self.inner.try_lock() {
68 Ok(guard) => Ok(self.wrap(guard, site, asked)),
69 Err(TryLockError::Poisoned(p)) => Err(TryLockError::Poisoned(PoisonError::new(
70 self.wrap(p.into_inner(), site, asked),
71 ))),
72 Err(TryLockError::WouldBlock) => Err(TryLockError::WouldBlock),
73 }
74 }
75
76 fn wrap<'a>(
77 &self,
78 guard: MutexGuard<'a, T>,
79 site: &'static Location<'static>,
80 asked: Instant,
81 ) -> TimedGuard<'a, T> {
82 let got = Instant::now();
83 TimedGuard {
84 guard,
85 store: self.store,
86 site,
87 waited: got.duration_since(asked),
88 got,
89 }
90 }
91}
92
93impl<T> TimedGuard<'_, T> {
94 pub fn waited(&self) -> Duration {
96 self.waited
97 }
98}
99
100impl<T> Deref for TimedGuard<'_, T> {
101 type Target = T;
102 fn deref(&self) -> &T {
103 &self.guard
104 }
105}
106
107impl<T> DerefMut for TimedGuard<'_, T> {
108 fn deref_mut(&mut self) -> &mut T {
109 &mut self.guard
110 }
111}
112
113impl<T> Drop for TimedGuard<'_, T> {
114 fn drop(&mut self) {
115 let held = self.got.elapsed();
116 if self.waited < SLOW && held < SLOW {
117 return;
118 }
119 if let Some(suppressed) = SPACER.admit(epoch_ms()) {
120 tracing::warn!(
121 store = self.store,
122 site = %self.site,
123 waited_ms = self.waited.as_millis() as u64,
124 held_ms = held.as_millis() as u64,
125 on_worker = crate::backend::thread_roles::on_worker(),
126 suppressed,
127 "store lock: a wait or a hold was slow"
128 );
129 }
130 }
131}
132
133struct Spacer {
135 last_ms: AtomicU64,
137 left_out: AtomicU64,
138}
139
140impl Spacer {
141 const fn new() -> Self {
142 Self {
143 last_ms: AtomicU64::new(0),
144 left_out: AtomicU64::new(0),
145 }
146 }
147
148 fn admit(&self, now_ms: u64) -> Option<u64> {
150 let last = self.last_ms.load(Ordering::Acquire);
151 let due = last == 0 || now_ms.saturating_sub(last) >= LOG_EVERY.as_millis() as u64;
152 if due
153 && self
154 .last_ms
155 .compare_exchange(last, now_ms, Ordering::AcqRel, Ordering::Acquire)
156 .is_ok()
157 {
158 return Some(self.left_out.swap(0, Ordering::AcqRel));
159 }
160 self.left_out.fetch_add(1, Ordering::AcqRel);
161 None
162 }
163}
164
165static SPACER: Spacer = Spacer::new();
166
167fn epoch_ms() -> u64 {
169 static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
170 EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use std::sync::Arc;
177
178 #[test]
179 fn it_locks_and_derefs_like_a_mutex() {
180 let m = TimedMutex::new(5, "test");
181 *m.lock().unwrap() += 1;
182 assert_eq!(*m.lock().unwrap(), 6);
183 let held = m.lock().unwrap();
184 assert!(matches!(m.try_lock(), Err(TryLockError::WouldBlock)));
185 drop(held);
186 assert!(m.try_lock().is_ok());
187 }
188
189 #[test]
190 fn a_poisoned_lock_still_gives_its_value() {
191 let m = Arc::new(TimedMutex::new(1, "test"));
192 let m2 = m.clone();
193 let _ = std::thread::spawn(move || {
194 let _g = m2.lock().unwrap();
195 panic!("poison it");
196 })
197 .join();
198 let value = *m.lock().unwrap_or_else(|e| e.into_inner());
199 assert_eq!(value, 1);
200 }
201
202 #[test]
203 fn a_caller_that_waits_for_a_held_lock_measures_the_wait() {
204 let m = Arc::new(TimedMutex::new((), "test"));
205 let (held_tx, held_rx) = std::sync::mpsc::channel();
206 let holder = {
207 let m = m.clone();
208 std::thread::spawn(move || {
209 let _g = m.lock().unwrap();
210 held_tx.send(()).unwrap();
211 std::thread::sleep(Duration::from_millis(400));
212 })
213 };
214 held_rx.recv().unwrap();
215 let guard = m.lock().unwrap();
216 assert!(guard.waited() >= SLOW, "waited only {:?}", guard.waited());
217 drop(guard);
218 holder.join().unwrap();
219 }
220
221 #[test]
222 fn lines_are_spaced_and_the_ones_left_out_are_counted() {
223 let spacer = Spacer::new();
224 assert_eq!(spacer.admit(1_000), Some(0));
225 assert_eq!(spacer.admit(1_100), None);
226 assert_eq!(spacer.admit(1_200), None);
227 assert_eq!(spacer.admit(1_600), Some(2));
228 assert_eq!(spacer.admit(1_700), None);
229 assert_eq!(spacer.admit(2_100), Some(1));
230 }
231}