Skip to main content

aurelin_framework/cache/
lock.rs

1use 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/// An owner-scoped atomic cache lock.
12#[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    /// Attempt to acquire this lock immediately.
30    pub async fn acquire(&self) -> Result<bool, Error> {
31        self.store.acquire_lock(&self.key, &self.owner, self.ttl).await
32    }
33
34    /// Wait up to `timeout` for this lock to become available.
35    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    /// Release this lock if its stored owner still matches.
53    pub async fn release(&self) -> Result<bool, Error> {
54        self.store.release_lock(&self.key, &self.owner).await
55    }
56
57    /// Release the named lock regardless of its current owner.
58    pub async fn force_release(&self) -> Result<(), Error> {
59        self.store.force_release_lock(&self.key).await
60    }
61
62    /// Refresh the lock using another signed-second lifetime.
63    ///
64    /// Zero or negative seconds make an owned lock indefinite.
65    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    /// Return the opaque owner token used by this handle.
71    pub fn owner(&self) -> &str {
72        &self.owner
73    }
74
75    /// Determine whether this handle still owns the stored lock.
76    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    /// Determine whether any owner currently holds the lock.
81    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}