Skip to main content

lean_ctx/server/
bounded_lock.rs

1use std::sync::Arc;
2use std::time::Duration;
3use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
4
5const BASE_READ_TIMEOUT: Duration = Duration::from_secs(10);
6const BASE_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
7
8/// Spin interval between `try_*` attempts. Kept short enough for responsiveness
9/// but long enough to avoid busy-spinning on Windows where thread scheduling
10/// quanta are ~15ms.
11const SPIN_INTERVAL: Duration = Duration::from_millis(20);
12
13/// Determines how an operation handles a bounded-lock timeout.
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15pub enum LockFailBehavior {
16    /// Return a [`LockTimeoutError`] when the operation cannot safely continue.
17    ReturnError,
18    /// Return the wrapper's default value (`Ok(None)`) when the operation is optional.
19    #[default]
20    ReturnDefault,
21    /// Wait through one additional timeout window before applying the default value.
22    RetryOnce,
23}
24
25/// Details of a lock acquisition timeout returned by [`LockFailBehavior::ReturnError`].
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct LockTimeoutError {
28    /// Whether the timed-out acquisition was for a read or write guard.
29    pub operation: &'static str,
30    /// Caller-provided description of the operation that needed the lock.
31    pub context: String,
32    /// Timeout applied to the final acquisition attempt.
33    pub timeout: Duration,
34}
35
36impl std::fmt::Display for LockTimeoutError {
37    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(
39            formatter,
40            "bounded_lock: {} timeout ({}ms) for {}",
41            self.operation,
42            self.timeout.as_millis(),
43            self.context
44        )
45    }
46}
47
48impl std::error::Error for LockTimeoutError {}
49
50/// Acquire a read lock via a non-blocking spin loop with an adaptive timeout.
51///
52/// Unlike the previous `Handle::block_on` approach, this never parks a blocking
53/// thread waiting for the async runtime to make progress — eliminating the
54/// stall-under-load anti-pattern on Windows (#1018). The loop yields the thread
55/// between attempts so it does not starve other work on the blocking pool.
56///
57/// Returns `None` on timeout, preserving the historical default behavior.
58pub fn read<T: Send + Sync + 'static>(
59    lock: &Arc<RwLock<T>>,
60    context: &str,
61) -> Option<OwnedRwLockReadGuard<T>> {
62    read_with_behavior(lock, context, LockFailBehavior::default())
63        .ok()
64        .flatten()
65}
66
67/// Acquire a read lock within an explicit hard budget.
68///
69/// Use this on latency-critical request paths where adaptive I/O recovery must
70/// not turn a best-effort session update into a multi-second user-visible wait.
71pub fn read_for<T: Send + Sync + 'static>(
72    lock: &Arc<RwLock<T>>,
73    context: &str,
74    timeout: Duration,
75) -> Option<OwnedRwLockReadGuard<T>> {
76    acquire_with_behavior(
77        lock,
78        context,
79        "read",
80        timeout,
81        LockFailBehavior::ReturnDefault,
82        |lock| lock.clone().try_read_owned().ok(),
83    )
84    .ok()
85    .flatten()
86}
87
88/// Acquire a read lock with explicit timeout behavior for this operation.
89pub fn read_with_behavior<T: Send + Sync + 'static>(
90    lock: &Arc<RwLock<T>>,
91    context: &str,
92    behavior: LockFailBehavior,
93) -> Result<Option<OwnedRwLockReadGuard<T>>, LockTimeoutError> {
94    let timeout = crate::core::io_health::adaptive_timeout(BASE_READ_TIMEOUT);
95    acquire_with_behavior(lock, context, "read", timeout, behavior, |lock| {
96        lock.clone().try_read_owned().ok()
97    })
98}
99
100/// Acquire a write lock with explicit timeout behavior for this operation.
101pub fn write_with_behavior<T: Send + Sync + 'static>(
102    lock: &Arc<RwLock<T>>,
103    context: &str,
104    behavior: LockFailBehavior,
105) -> Result<Option<OwnedRwLockWriteGuard<T>>, LockTimeoutError> {
106    let timeout = crate::core::io_health::adaptive_timeout(BASE_WRITE_TIMEOUT);
107    acquire_with_behavior(lock, context, "write", timeout, behavior, |lock| {
108        lock.clone().try_write_owned().ok()
109    })
110}
111
112fn acquire_with_behavior<T, Guard, Acquire>(
113    lock: &Arc<RwLock<T>>,
114    context: &str,
115    operation: &'static str,
116    timeout: Duration,
117    behavior: LockFailBehavior,
118    acquire: Acquire,
119) -> Result<Option<Guard>, LockTimeoutError>
120where
121    Acquire: Fn(&Arc<RwLock<T>>) -> Option<Guard>,
122{
123    let attempts = if behavior == LockFailBehavior::RetryOnce {
124        2
125    } else {
126        1
127    };
128
129    for attempt in 1..=attempts {
130        let deadline = std::time::Instant::now() + timeout;
131
132        loop {
133            if let Some(guard) = acquire(lock) {
134                return Ok(Some(guard));
135            }
136            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
137            if !remaining.is_zero() {
138                std::thread::sleep(remaining.min(SPIN_INTERVAL));
139                continue;
140            }
141
142            crate::core::io_health::record_freeze();
143            if attempt < attempts {
144                tracing::warn!(
145                    "bounded_lock: {operation} timeout ({}ms) for {context}; retrying once",
146                    timeout.as_millis()
147                );
148                break;
149            }
150
151            let error = LockTimeoutError {
152                operation,
153                context: context.to_owned(),
154                timeout,
155            };
156            tracing::warn!("{error}; degrading gracefully");
157            return match behavior {
158                LockFailBehavior::ReturnError => Err(error),
159                LockFailBehavior::ReturnDefault | LockFailBehavior::RetryOnce => Ok(None),
160            };
161        }
162    }
163
164    unreachable!("RetryOnce returns after its second acquisition attempt")
165}
166
167/// Acquire a write lock via a non-blocking spin loop with an adaptive timeout.
168/// See `read()` for design rationale (#1018).
169///
170/// Returns `None` on timeout, preserving the historical default behavior.
171pub fn write<T: Send + Sync + 'static>(
172    lock: &Arc<RwLock<T>>,
173    context: &str,
174) -> Option<OwnedRwLockWriteGuard<T>> {
175    write_with_behavior(lock, context, LockFailBehavior::default())
176        .ok()
177        .flatten()
178}
179
180/// Acquire a write lock within an explicit hard budget.
181///
182/// This is the write counterpart to [`read_for`]. A timeout must degrade the
183/// optional bookkeeping, never keep an interactive tool request queued.
184pub fn write_for<T: Send + Sync + 'static>(
185    lock: &Arc<RwLock<T>>,
186    context: &str,
187    timeout: Duration,
188) -> Option<OwnedRwLockWriteGuard<T>> {
189    acquire_with_behavior(
190        lock,
191        context,
192        "write",
193        timeout,
194        LockFailBehavior::ReturnDefault,
195        |lock| lock.clone().try_write_owned().ok(),
196    )
197    .ok()
198    .flatten()
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use std::sync::atomic::{AtomicUsize, Ordering};
205
206    #[test]
207    fn read_succeeds_on_uncontested_lock() {
208        let lock = Arc::new(RwLock::new(42u32));
209        let guard = read(&lock, "test").expect("uncontested read must succeed");
210        assert_eq!(*guard, 42);
211    }
212
213    #[test]
214    fn write_succeeds_on_uncontested_lock() {
215        let lock = Arc::new(RwLock::new(0u32));
216        let mut guard = write(&lock, "test").expect("uncontested write must succeed");
217        *guard = 7;
218        assert_eq!(*guard, 7);
219    }
220
221    #[test]
222    fn multiple_readers_concurrent() {
223        let lock = Arc::new(RwLock::new(99u32));
224        let g1 = read(&lock, "r1").expect("first reader");
225        let g2 = read(&lock, "r2").expect("second reader");
226        assert_eq!(*g1, 99);
227        assert_eq!(*g2, 99);
228    }
229
230    #[test]
231    fn write_excludes_readers() {
232        let lock = Arc::new(RwLock::new(0u32));
233        let _hold = lock.clone().try_write_owned().unwrap();
234        assert!(lock.clone().try_read_owned().is_err());
235    }
236
237    #[test]
238    fn explicit_budget_never_waits_for_adaptive_default() {
239        let lock = Arc::new(RwLock::new(()));
240        let _hold = lock.clone().try_write_owned().expect("hold write lock");
241        assert!(read_for(&lock, "interactive read", Duration::ZERO).is_none());
242        assert!(write_for(&lock, "interactive write", Duration::ZERO).is_none());
243    }
244
245    #[test]
246    fn return_error_reports_lock_timeout() {
247        let lock = Arc::new(RwLock::new(()));
248        let result: Result<Option<()>, _> = acquire_with_behavior(
249            &lock,
250            "required operation",
251            "read",
252            Duration::ZERO,
253            LockFailBehavior::ReturnError,
254            |_| None,
255        );
256
257        let error = result.expect_err("ReturnError must expose the timeout");
258        assert_eq!(error.operation, "read");
259        assert_eq!(error.context, "required operation");
260    }
261
262    #[test]
263    fn return_default_suppresses_lock_timeout() {
264        let lock = Arc::new(RwLock::new(()));
265        let result: Result<Option<()>, _> = acquire_with_behavior(
266            &lock,
267            "optional operation",
268            "read",
269            Duration::ZERO,
270            LockFailBehavior::ReturnDefault,
271            |_| None,
272        );
273
274        assert_eq!(result, Ok(None));
275    }
276
277    #[test]
278    fn retry_once_makes_two_acquisition_attempts() {
279        let lock = Arc::new(RwLock::new(()));
280        let attempts = AtomicUsize::new(0);
281        let result: Result<Option<()>, _> = acquire_with_behavior(
282            &lock,
283            "retryable operation",
284            "read",
285            Duration::ZERO,
286            LockFailBehavior::RetryOnce,
287            |_| {
288                attempts.fetch_add(1, Ordering::Relaxed);
289                None
290            },
291        );
292
293        assert_eq!(result, Ok(None));
294        assert_eq!(attempts.load(Ordering::Relaxed), 2);
295    }
296}