1use std::sync::Arc;
3use std::time::Duration;
4use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
5
6const BASE_READ_TIMEOUT: Duration = Duration::from_secs(10);
7const BASE_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
8
9const SPIN_INTERVAL: Duration = Duration::from_millis(20);
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub enum LockFailBehavior {
17 ReturnError,
19 #[default]
21 ReturnDefault,
22 RetryOnce,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct LockTimeoutError {
29 pub operation: &'static str,
31 pub context: String,
33 pub timeout: Duration,
35}
36
37impl std::fmt::Display for LockTimeoutError {
38 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 write!(
40 formatter,
41 "bounded_lock: {} timeout ({}ms) for {}",
42 self.operation,
43 self.timeout.as_millis(),
44 self.context
45 )
46 }
47}
48
49impl std::error::Error for LockTimeoutError {}
50
51pub fn read<T: Send + Sync + 'static>(
60 lock: &Arc<RwLock<T>>,
61 context: &str,
62) -> Option<OwnedRwLockReadGuard<T>> {
63 read_with_behavior(lock, context, LockFailBehavior::default())
64 .ok()
65 .flatten()
66}
67
68pub fn read_for<T: Send + Sync + 'static>(
73 lock: &Arc<RwLock<T>>,
74 context: &str,
75 timeout: Duration,
76) -> Option<OwnedRwLockReadGuard<T>> {
77 read_within(lock, context, timeout, LockFailBehavior::ReturnDefault)
78 .ok()
79 .flatten()
80}
81
82pub fn read_with_behavior<T: Send + Sync + 'static>(
84 lock: &Arc<RwLock<T>>,
85 context: &str,
86 behavior: LockFailBehavior,
87) -> Result<Option<OwnedRwLockReadGuard<T>>, LockTimeoutError> {
88 read_within(lock, context, read_timeout(), behavior)
89}
90
91pub fn write_with_behavior<T: Send + Sync + 'static>(
93 lock: &Arc<RwLock<T>>,
94 context: &str,
95 behavior: LockFailBehavior,
96) -> Result<Option<OwnedRwLockWriteGuard<T>>, LockTimeoutError> {
97 write_within(lock, context, write_timeout(), behavior)
98}
99
100pub fn read_timeout() -> Duration {
103 crate::core::io_health::adaptive_timeout(BASE_READ_TIMEOUT)
104}
105
106pub fn write_timeout() -> Duration {
108 crate::core::io_health::adaptive_timeout(BASE_WRITE_TIMEOUT)
109}
110
111pub fn read_adaptive<T: Send + Sync + 'static>(
115 lock: &Arc<RwLock<T>>,
116 context: &str,
117 base: Duration,
118) -> Option<OwnedRwLockReadGuard<T>> {
119 let timeout = crate::core::io_health::adaptive_timeout(base);
120 read_within(lock, context, timeout, LockFailBehavior::default())
121 .ok()
122 .flatten()
123}
124
125pub fn write_adaptive<T: Send + Sync + 'static>(
127 lock: &Arc<RwLock<T>>,
128 context: &str,
129 base: Duration,
130) -> Option<OwnedRwLockWriteGuard<T>> {
131 let timeout = crate::core::io_health::adaptive_timeout(base);
132 write_within(lock, context, timeout, LockFailBehavior::default())
133 .ok()
134 .flatten()
135}
136
137fn read_within<T: Send + Sync + 'static>(
138 lock: &Arc<RwLock<T>>,
139 context: &str,
140 timeout: Duration,
141 behavior: LockFailBehavior,
142) -> Result<Option<OwnedRwLockReadGuard<T>>, LockTimeoutError> {
143 acquire_with_behavior(lock, context, "read", timeout, behavior, |lock| {
144 lock.clone().try_read_owned().ok()
145 })
146}
147
148fn write_within<T: Send + Sync + 'static>(
149 lock: &Arc<RwLock<T>>,
150 context: &str,
151 timeout: Duration,
152 behavior: LockFailBehavior,
153) -> Result<Option<OwnedRwLockWriteGuard<T>>, LockTimeoutError> {
154 acquire_with_behavior(lock, context, "write", timeout, behavior, |lock| {
155 lock.clone().try_write_owned().ok()
156 })
157}
158
159fn acquire_with_behavior<T, Guard, Acquire>(
160 lock: &Arc<RwLock<T>>,
161 context: &str,
162 operation: &'static str,
163 timeout: Duration,
164 behavior: LockFailBehavior,
165 acquire: Acquire,
166) -> Result<Option<Guard>, LockTimeoutError>
167where
168 Acquire: Fn(&Arc<RwLock<T>>) -> Option<Guard>,
169{
170 let attempts = if behavior == LockFailBehavior::RetryOnce {
171 2
172 } else {
173 1
174 };
175
176 for attempt in 1..=attempts {
177 let deadline = std::time::Instant::now() + timeout;
178
179 loop {
180 if let Some(guard) = acquire(lock) {
181 return Ok(Some(guard));
182 }
183 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
184 if !remaining.is_zero() {
185 std::thread::sleep(remaining.min(SPIN_INTERVAL));
186 continue;
187 }
188
189 crate::core::io_health::record_freeze();
190 if attempt < attempts {
191 tracing::warn!(
192 "bounded_lock: {operation} timeout ({}ms) for {context}; retrying once",
193 timeout.as_millis()
194 );
195 break;
196 }
197
198 let error = LockTimeoutError {
199 operation,
200 context: context.to_owned(),
201 timeout,
202 };
203 tracing::warn!("{error}; degrading gracefully");
204 return match behavior {
205 LockFailBehavior::ReturnError => Err(error),
206 LockFailBehavior::ReturnDefault | LockFailBehavior::RetryOnce => Ok(None),
207 };
208 }
209 }
210
211 unreachable!("RetryOnce returns after its second acquisition attempt")
212}
213
214pub fn write<T: Send + Sync + 'static>(
219 lock: &Arc<RwLock<T>>,
220 context: &str,
221) -> Option<OwnedRwLockWriteGuard<T>> {
222 write_with_behavior(lock, context, LockFailBehavior::default())
223 .ok()
224 .flatten()
225}
226
227pub fn write_for<T: Send + Sync + 'static>(
232 lock: &Arc<RwLock<T>>,
233 context: &str,
234 timeout: Duration,
235) -> Option<OwnedRwLockWriteGuard<T>> {
236 write_within(lock, context, timeout, LockFailBehavior::ReturnDefault)
237 .ok()
238 .flatten()
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use std::sync::atomic::{AtomicUsize, Ordering};
245
246 #[test]
247 fn read_succeeds_on_uncontested_lock() {
248 let lock = Arc::new(RwLock::new(42u32));
249 let guard = read(&lock, "test").expect("uncontested read must succeed");
250 assert_eq!(*guard, 42);
251 }
252
253 #[test]
254 fn write_succeeds_on_uncontested_lock() {
255 let lock = Arc::new(RwLock::new(0u32));
256 let mut guard = write(&lock, "test").expect("uncontested write must succeed");
257 *guard = 7;
258 assert_eq!(*guard, 7);
259 }
260
261 #[test]
262 fn multiple_readers_concurrent() {
263 let lock = Arc::new(RwLock::new(99u32));
264 let g1 = read(&lock, "r1").expect("first reader");
265 let g2 = read(&lock, "r2").expect("second reader");
266 assert_eq!(*g1, 99);
267 assert_eq!(*g2, 99);
268 }
269
270 #[test]
271 fn write_excludes_readers() {
272 let lock = Arc::new(RwLock::new(0u32));
273 let _hold = lock.clone().try_write_owned().unwrap();
274 assert!(lock.clone().try_read_owned().is_err());
275 }
276
277 #[test]
278 fn explicit_budget_never_waits_for_adaptive_default() {
279 let lock = Arc::new(RwLock::new(()));
280 let _hold = lock.clone().try_write_owned().expect("hold write lock");
281 assert!(read_for(&lock, "interactive read", Duration::ZERO).is_none());
282 assert!(write_for(&lock, "interactive write", Duration::ZERO).is_none());
283 }
284
285 #[test]
286 fn return_error_reports_lock_timeout() {
287 let lock = Arc::new(RwLock::new(()));
288 let result: Result<Option<()>, _> = acquire_with_behavior(
289 &lock,
290 "required operation",
291 "read",
292 Duration::ZERO,
293 LockFailBehavior::ReturnError,
294 |_| None,
295 );
296
297 let error = result.expect_err("ReturnError must expose the timeout");
298 assert_eq!(error.operation, "read");
299 assert_eq!(error.context, "required operation");
300 }
301
302 #[test]
303 fn return_default_suppresses_lock_timeout() {
304 let lock = Arc::new(RwLock::new(()));
305 let result: Result<Option<()>, _> = acquire_with_behavior(
306 &lock,
307 "optional operation",
308 "read",
309 Duration::ZERO,
310 LockFailBehavior::ReturnDefault,
311 |_| None,
312 );
313
314 assert_eq!(result, Ok(None));
315 }
316
317 #[test]
318 fn retry_once_makes_two_acquisition_attempts() {
319 let lock = Arc::new(RwLock::new(()));
320 let attempts = AtomicUsize::new(0);
321 let result: Result<Option<()>, _> = acquire_with_behavior(
322 &lock,
323 "retryable operation",
324 "read",
325 Duration::ZERO,
326 LockFailBehavior::RetryOnce,
327 |_| {
328 attempts.fetch_add(1, Ordering::Relaxed);
329 None
330 },
331 );
332
333 assert_eq!(result, Ok(None));
334 assert_eq!(attempts.load(Ordering::Relaxed), 2);
335 }
336}