aurelin_framework/cache/
lock.rs1use std::{sync::Arc, time::Duration};
2
3use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
4use rand::RngCore;
5use tokio::time::{Instant, sleep};
6
7use super::{Error, Store};
8
9const RETRY_DELAY: Duration = Duration::from_millis(250);
10
11#[derive(Clone)]
13pub struct Lock {
14 store: Arc<dyn Store>,
15 key: String,
16 owner: String,
17 ttl: Option<Duration>,
18}
19
20impl Lock {
21 pub(super) fn new(store: Arc<dyn Store>, key: String, seconds: i64) -> Self {
22 Self { store, key, owner: random_owner(), ttl: positive_duration(seconds) }
23 }
24
25 pub(super) fn restored(store: Arc<dyn Store>, key: String, owner: String) -> Self {
26 Self { store, key, owner, ttl: None }
27 }
28
29 pub async fn acquire(&self) -> Result<bool, Error> {
31 self.store.acquire_lock(&self.key, &self.owner, self.ttl).await
32 }
33
34 pub async fn block(&self, timeout: Duration) -> Result<(), Error> {
36 let deadline = Instant::now() + timeout;
37
38 loop {
39 if self.acquire().await? {
40 return Ok(());
41 }
42
43 let now = Instant::now();
44 if now >= deadline {
45 return Err(Error::LockTimeout(timeout));
46 }
47
48 sleep(RETRY_DELAY.min(deadline.saturating_duration_since(now))).await;
49 }
50 }
51
52 pub async fn release(&self) -> Result<bool, Error> {
54 self.store.release_lock(&self.key, &self.owner).await
55 }
56
57 pub async fn force_release(&self) -> Result<(), Error> {
59 self.store.force_release_lock(&self.key).await
60 }
61
62 pub async fn refresh(&self, seconds: Option<i64>) -> Result<bool, Error> {
66 let ttl = seconds.map_or(self.ttl, positive_duration);
67 self.store.refresh_lock(&self.key, &self.owner, ttl).await
68 }
69
70 pub fn owner(&self) -> &str {
72 &self.owner
73 }
74
75 pub async fn is_owned(&self) -> Result<bool, Error> {
77 Ok(self.store.lock_owner(&self.key).await?.as_deref() == Some(&self.owner))
78 }
79
80 pub async fn is_locked(&self) -> Result<bool, Error> {
82 Ok(self.store.lock_owner(&self.key).await?.is_some())
83 }
84}
85
86fn positive_duration(seconds: i64) -> Option<Duration> {
87 u64::try_from(seconds).ok().filter(|seconds| *seconds > 0).map(Duration::from_secs)
88}
89
90fn random_owner() -> String {
91 let mut bytes = [0_u8; 32];
92 rand::rng().fill_bytes(&mut bytes);
93 URL_SAFE_NO_PAD.encode(bytes)
94}