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
use std::time::Duration;
use tokio::time::timeout;
use crate::{Result, DEFAULT_TIMEOUT_DURATION};
#[derive(Debug)]
pub struct Mutex<T> {
inner: tokio::sync::Mutex<T>,
timeout: Duration,
}
impl<T> Mutex<T> {
pub fn new(value: T) -> Self {
Self { inner: tokio::sync::Mutex::new(value), timeout: DEFAULT_TIMEOUT_DURATION }
}
pub fn new_with_timeout(value: T, timeout: Duration) -> Self {
Self { inner: tokio::sync::Mutex::new(value), timeout }
}
pub async fn lock(&self) -> tokio::sync::MutexGuard<'_, T> {
let guard = match timeout(self.timeout, self.inner.lock()).await {
Ok(guard) => guard,
Err(_) => panic!(
"Timed out while waiting for `read` lock after {} seconds.",
self.timeout.as_secs()
),
};
guard
}
pub async fn lock_err(&self) -> Result<tokio::sync::MutexGuard<'_, T>> {
let guard = timeout(self.timeout, self.inner.lock())
.await
.map_err(|_| crate::Error::LockTimeout(self.timeout.as_secs()))?;
Ok(guard)
}
}
impl<T> std::ops::Deref for Mutex<T> {
type Target = tokio::sync::Mutex<T>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: Default> Default for Mutex<T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> From<T> for Mutex<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}