1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#![allow(
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::cast_sign_loss,
reason = "M175: lock-timing diagnostics — millisecond accumulators bounded by lock_warn_threshold_ms"
)]
//! Lock timing diagnostics for hot-path synchronization primitives.
//!
//! `TimedGuard<G>` wraps any lock guard (Mutex, `RwLock` read/write) and logs
//! a warning if the guard is held longer than a configurable threshold.
//! When the threshold is `Duration::MAX` (disabled), `Instant::now()` is
//! never called — zero overhead on the hot path.
use std::ops::{Deref, DerefMut};
use std::time::{Duration, Instant};
use tracing::warn;
/// Settings for lock timing diagnostics.
#[derive(Debug, Clone, Copy)]
pub(crate) struct LockTimingSettings {
/// How long a lock can be held before a warning is emitted.
/// `Duration::MAX` means disabled (no timing overhead).
pub warn_threshold: Duration,
}
impl LockTimingSettings {
/// Create settings from the user-facing millisecond value.
///
/// A value of `0` disables timing entirely (`Duration::MAX`).
pub fn from_ms(ms: u64) -> Self {
Self {
warn_threshold: if ms == 0 {
Duration::MAX
} else {
Duration::from_millis(ms)
},
}
}
/// Whether timing is enabled (threshold is not MAX).
#[inline]
pub fn is_enabled(&self) -> bool {
self.warn_threshold != Duration::MAX
}
}
impl Default for LockTimingSettings {
fn default() -> Self {
Self::from_ms(50)
}
}
/// A lock guard wrapper that warns when held too long.
///
/// Transparent via `Deref`/`DerefMut` — callers interact with the inner
/// guard as usual. On `Drop`, if the guard was held longer than the
/// threshold, a warning is emitted with the caller's label.
pub(crate) struct TimedGuard<G> {
guard: G,
/// `None` when timing is disabled (threshold == `Duration::MAX`).
acquired_at: Option<Instant>,
threshold: Duration,
label: &'static str,
}
impl<G> TimedGuard<G> {
/// Wrap a lock guard with timing diagnostics.
///
/// When `settings.warn_threshold == Duration::MAX`, the `Instant::now()`
/// call is skipped entirely — zero overhead.
#[inline]
pub fn new(guard: G, settings: &LockTimingSettings, label: &'static str) -> Self {
let acquired_at = if settings.is_enabled() {
Some(Instant::now())
} else {
None
};
Self {
guard,
acquired_at,
threshold: settings.warn_threshold,
label,
}
}
}
impl<G: Deref> Deref for TimedGuard<G> {
type Target = G::Target;
#[inline]
fn deref(&self) -> &Self::Target {
&self.guard
}
}
impl<G: DerefMut> DerefMut for TimedGuard<G> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.guard
}
}
impl<G> Drop for TimedGuard<G> {
fn drop(&mut self) {
if let Some(acquired_at) = self.acquired_at {
let held = acquired_at.elapsed();
if held > self.threshold {
warn!(
lock = self.label,
held_ms = held.as_millis() as u64,
threshold_ms = self.threshold.as_millis() as u64,
"lock held longer than threshold"
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use parking_lot::Mutex;
#[test]
fn timed_guard_deref_deref_mut() {
let m = Mutex::new(42u32);
let settings = LockTimingSettings::from_ms(100);
// Read via Deref
{
let guard = TimedGuard::new(m.lock(), &settings, "test_mutex");
assert_eq!(*guard, 42);
}
// Write via DerefMut
{
let mut guard = TimedGuard::new(m.lock(), &settings, "test_mutex");
*guard = 99;
}
assert_eq!(*m.lock(), 99);
}
#[test]
fn timed_guard_warns_on_slow_lock() {
// We can't easily capture tracing output in a unit test, but we can
// verify the timing logic works without panicking.
let m = Mutex::new(());
let settings = LockTimingSettings::from_ms(1); // 1ms threshold
let guard = TimedGuard::new(m.lock(), &settings, "slow_test");
assert!(guard.acquired_at.is_some());
std::thread::sleep(Duration::from_millis(5));
drop(guard); // Should emit warning (1ms threshold, 5ms held)
}
#[test]
fn timed_guard_no_warn_under_threshold() {
let m = Mutex::new(());
let settings = LockTimingSettings::from_ms(1000); // 1s threshold
let guard = TimedGuard::new(m.lock(), &settings, "fast_test");
assert!(guard.acquired_at.is_some());
drop(guard); // Should NOT warn (held < 1s)
}
#[test]
fn timed_guard_disabled_when_zero() {
let m = Mutex::new(());
let settings = LockTimingSettings::from_ms(0); // Disabled
assert!(!settings.is_enabled());
assert_eq!(settings.warn_threshold, Duration::MAX);
let guard = TimedGuard::new(m.lock(), &settings, "disabled_test");
assert!(guard.acquired_at.is_none()); // No Instant::now() called
drop(guard);
}
}