@@ -11,6 +11,8 @@ use once_cell::sync::OnceCell;
11
11
pub struct ProtectedSubsystems ;
12
12
impl ProtectedSubsystems {
13
13
pub const NEXUS : & ' static str = "nexus" ;
14
+ pub const POOL : & ' static str = "pool" ;
15
+ pub const REPLICA : & ' static str = "replica" ;
14
16
}
15
17
16
18
/// Configuration parameters for initialization of the Lock manager.
@@ -41,6 +43,7 @@ impl ResourceLockManagerConfig {
41
43
}
42
44
43
45
/// Resource subsystem that holds locks for all resources withing this system.
46
+ #[ derive( Debug ) ]
44
47
pub struct ResourceSubsystem {
45
48
id : String ,
46
49
object_locks : Vec < Mutex < LockStats > > ,
@@ -67,22 +70,23 @@ impl ResourceSubsystem {
67
70
pub async fn lock (
68
71
& self ,
69
72
wait_timeout : Option < Duration > ,
73
+ try_lock : bool ,
70
74
) -> Option < ResourceLockGuard < ' _ > > {
71
- acquire_lock ( & self . subsystem_lock , wait_timeout) . await
75
+ acquire_lock ( & self . subsystem_lock , wait_timeout, try_lock ) . await
72
76
}
73
77
74
78
/// Lock subsystem resource by its ID and obtain a lock guard.
75
79
pub async fn lock_resource < T : AsRef < str > > (
76
80
& self ,
77
81
id : T ,
78
82
wait_timeout : Option < Duration > ,
83
+ try_lock : bool ,
79
84
) -> Option < ResourceLockGuard < ' _ > > {
80
85
// Calculate hash of the object to get the mutex index.
81
86
let mut hasher = DefaultHasher :: new ( ) ;
82
87
id. as_ref ( ) . hash ( & mut hasher) ;
83
88
let mutex_id = hasher. finish ( ) as usize % self . object_locks . len ( ) ;
84
-
85
- acquire_lock ( & self . object_locks [ mutex_id] , wait_timeout) . await
89
+ acquire_lock ( & self . object_locks [ mutex_id] , wait_timeout, try_lock) . await
86
90
}
87
91
}
88
92
@@ -122,14 +126,21 @@ static LOCK_MANAGER: OnceCell<ResourceLockManager> = OnceCell::new();
122
126
async fn acquire_lock (
123
127
lock : & Mutex < LockStats > ,
124
128
wait_timeout : Option < Duration > ,
129
+ try_lock : bool ,
125
130
) -> Option < ResourceLockGuard < ' _ > > {
126
131
let mut lock_guard = if let Some ( d) = wait_timeout {
127
132
match tokio:: time:: timeout ( d, lock. lock ( ) ) . await {
128
133
Err ( _) => return None ,
129
134
Ok ( g) => g,
130
135
}
136
+ } else if try_lock {
137
+ // No timeout, try for taking lock immediately.
138
+ match lock. try_lock ( ) {
139
+ Some ( l) => l,
140
+ None => return None ,
141
+ }
131
142
} else {
132
- // No timeout, wait for the lock indefinitely.
143
+ // No timeout, wait indefinitely.
133
144
lock. lock ( ) . await
134
145
} ;
135
146
@@ -162,8 +173,9 @@ impl ResourceLockManager {
162
173
pub async fn lock (
163
174
& self ,
164
175
wait_timeout : Option < Duration > ,
176
+ try_lock : bool ,
165
177
) -> Option < ResourceLockGuard < ' _ > > {
166
- acquire_lock ( & self . mgr_lock , wait_timeout) . await
178
+ acquire_lock ( & self . mgr_lock , wait_timeout, try_lock ) . await
167
179
}
168
180
169
181
/// Get resource subsystem by its id.
0 commit comments