larastvel_core/cache/
lock.rs1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3use std::time::{Duration, Instant};
4
5use async_trait::async_trait;
6use uuid::Uuid;
7
8use super::CacheError;
9
10#[async_trait]
13pub trait LockStore: Send + Sync + std::fmt::Debug {
14 async fn acquire(&self, key: &str, owner: &str, ttl: Duration) -> Result<bool, CacheError>;
16 async fn release(&self, key: &str, owner: &str) -> Result<bool, CacheError>;
18 async fn force_release(&self, key: &str) -> Result<bool, CacheError>;
20 async fn refresh(&self, key: &str, owner: &str, ttl: Duration) -> Result<bool, CacheError>;
23}
24
25#[derive(Debug, Clone)]
28pub struct Lock {
29 store: Arc<dyn LockStore>,
30 key: String,
31 owner: String,
32 ttl: Duration,
33}
34
35impl Lock {
36 pub fn new(store: Arc<dyn LockStore>, key: &str, ttl: Duration) -> Self {
37 Self {
38 store,
39 key: key.to_string(),
40 owner: Uuid::new_v4().to_string(),
41 ttl,
42 }
43 }
44
45 pub fn owner(&self) -> &str {
47 &self.owner
48 }
49
50 pub async fn get(&self) -> Result<bool, CacheError> {
52 self.store.acquire(&self.key, &self.owner, self.ttl).await
53 }
54
55 pub async fn release(&self) -> Result<bool, CacheError> {
57 self.store.release(&self.key, &self.owner).await
58 }
59
60 pub async fn force_release(&self) -> Result<bool, CacheError> {
62 self.store.force_release(&self.key).await
63 }
64
65 pub async fn refresh(&self) -> Result<bool, CacheError> {
67 self.store.refresh(&self.key, &self.owner, self.ttl).await
68 }
69
70 pub async fn block(&self, timeout: Duration) -> Result<bool, CacheError> {
73 let deadline = Instant::now() + timeout;
74 loop {
75 if self.get().await? {
76 return Ok(true);
77 }
78 if Instant::now() >= deadline {
79 return Ok(false);
80 }
81 tokio::time::sleep(Duration::from_millis(100)).await;
82 }
83 }
84}
85
86#[derive(Debug, Clone, Default)]
90pub struct ArrayLockStore {
91 locks: Arc<Mutex<HashMap<String, (String, Instant)>>>,
92}
93
94impl ArrayLockStore {
95 pub fn new() -> Self {
96 Self::default()
97 }
98}
99
100#[async_trait]
101impl LockStore for ArrayLockStore {
102 async fn acquire(&self, key: &str, owner: &str, ttl: Duration) -> Result<bool, CacheError> {
103 let mut locks = self.locks.lock().unwrap();
104 locks.retain(|_, (_, expiry)| *expiry > Instant::now());
105 match locks.get(key) {
106 Some((existing, _)) if existing != owner => Ok(false),
107 _ => {
108 locks.insert(key.to_string(), (owner.to_string(), Instant::now() + ttl));
109 Ok(true)
110 }
111 }
112 }
113
114 async fn release(&self, key: &str, owner: &str) -> Result<bool, CacheError> {
115 let mut locks = self.locks.lock().unwrap();
116 match locks.get(key) {
117 Some((existing, _)) if existing == owner => {
118 locks.remove(key);
119 Ok(true)
120 }
121 _ => Ok(false),
122 }
123 }
124
125 async fn force_release(&self, key: &str) -> Result<bool, CacheError> {
126 Ok(self.locks.lock().unwrap().remove(key).is_some())
127 }
128
129 async fn refresh(&self, key: &str, owner: &str, ttl: Duration) -> Result<bool, CacheError> {
130 let mut locks = self.locks.lock().unwrap();
131 match locks.get(key) {
132 Some((existing, _)) if existing == owner => {
133 locks.insert(key.to_string(), (owner.to_string(), Instant::now() + ttl));
134 Ok(true)
135 }
136 _ => Ok(false),
137 }
138 }
139}
140
141#[cfg(test)]
146mod tests {
147 use super::*;
148
149 fn store() -> Arc<dyn LockStore> {
150 Arc::new(ArrayLockStore::new())
151 }
152
153 fn lock(store: &Arc<dyn LockStore>, ttl: Duration) -> Lock {
154 Lock::new(store.clone(), "resource", ttl)
155 }
156
157 #[tokio::test]
158 async fn acquire_and_release() {
159 let s = store();
160 let l = lock(&s, Duration::from_secs(60));
161 assert!(l.get().await.unwrap());
162 assert!(l.release().await.unwrap());
163 assert!(!l.release().await.unwrap());
164 }
165
166 #[tokio::test]
167 async fn second_owner_blocked() {
168 let s = store();
169 let first = lock(&s, Duration::from_secs(60));
170 assert!(first.get().await.unwrap());
171 let second = lock(&s, Duration::from_secs(60));
172 assert!(!second.get().await.unwrap());
173 assert!(!second.release().await.unwrap());
175 assert!(first.release().await.unwrap());
176 assert!(second.get().await.unwrap());
177 }
178
179 #[tokio::test]
180 async fn force_release() {
181 let s = store();
182 let first = lock(&s, Duration::from_secs(60));
183 assert!(first.get().await.unwrap());
184 let second = lock(&s, Duration::from_secs(60));
185 assert!(second.force_release().await.unwrap());
186 assert!(second.get().await.unwrap());
187 }
188
189 #[tokio::test]
190 async fn refresh_extends_ttl() {
191 let s = store();
192 let l = lock(&s, Duration::from_millis(200));
193 assert!(l.get().await.unwrap());
194 assert!(l.refresh().await.unwrap());
195 tokio::time::sleep(Duration::from_millis(150)).await;
196 assert!(!lock(&s, Duration::from_secs(60)).get().await.unwrap());
198 }
199
200 #[tokio::test]
201 async fn lock_expires() {
202 let s = store();
203 let l = lock(&s, Duration::from_millis(50));
204 assert!(l.get().await.unwrap());
205 tokio::time::sleep(Duration::from_millis(100)).await;
206 assert!(lock(&s, Duration::from_secs(60)).get().await.unwrap());
207 }
208
209 #[tokio::test]
210 async fn block_waits_for_release() {
211 let s = store();
212 let held = lock(&s, Duration::from_secs(60));
213 assert!(held.get().await.unwrap());
214 let waiter = lock(&s, Duration::from_secs(60));
215 let held_clone = held.clone();
216 let handle = tokio::spawn(async move {
217 tokio::time::sleep(Duration::from_millis(120)).await;
218 held_clone.release().await.unwrap();
219 });
220 assert!(waiter.block(Duration::from_secs(5)).await.unwrap());
221 handle.await.unwrap();
222 }
223
224 #[tokio::test]
225 async fn block_times_out() {
226 let s = store();
227 let held = lock(&s, Duration::from_secs(60));
228 assert!(held.get().await.unwrap());
229 let waiter = lock(&s, Duration::from_secs(60));
230 assert!(!waiter.block(Duration::from_millis(150)).await.unwrap());
231 assert!(held.release().await.unwrap());
232 }
233}