Skip to main content

serenade_lock/
lock.rs

1//! User-facing [`Lock`] handle.
2
3use std::sync::{Arc, Mutex};
4use std::time::Duration;
5
6use crate::{LockError, LockStore};
7
8/// Named lock bound to one owner token and a [`LockStore`].
9pub struct Lock {
10    resource: String,
11    token: String,
12    store: Arc<dyn LockStore>,
13    ttl: Option<Duration>,
14    auto_release: bool,
15    acquired: Mutex<bool>,
16}
17
18impl Lock {
19    pub(crate) fn new(
20        resource: String,
21        token: String,
22        store: Arc<dyn LockStore>,
23        ttl: Option<Duration>,
24        auto_release: bool,
25    ) -> Self {
26        Self {
27            resource,
28            token,
29            store,
30            ttl,
31            auto_release,
32            acquired: Mutex::new(false),
33        }
34    }
35
36    /// Resource name.
37    #[must_use]
38    pub fn resource(&self) -> &str {
39        &self.resource
40    }
41
42    /// Owner token.
43    #[must_use]
44    pub fn token(&self) -> &str {
45        &self.token
46    }
47
48    /// Default TTL used on acquire / refresh when callers pass `None`.
49    #[must_use]
50    pub const fn ttl(&self) -> Option<Duration> {
51        self.ttl
52    }
53
54    /// Tries to acquire without blocking.
55    ///
56    /// Returns `Ok(true)` when acquired (or already held by this token), `Ok(false)` on conflict.
57    ///
58    /// # Errors
59    ///
60    /// Propagates store failures other than conflict.
61    ///
62    /// # Panics
63    ///
64    /// Panics when the internal acquired flag mutex is poisoned.
65    pub fn acquire(&self) -> Result<bool, LockError> {
66        match self.store.save(&self.resource, &self.token, self.ttl) {
67            Ok(()) => {
68                *self
69                    .acquired
70                    .lock()
71                    .expect("serenade-lock acquired flag poisoned") = true;
72                Ok(true)
73            }
74            Err(LockError::Conflict { .. }) => Ok(false),
75            Err(err) => Err(err),
76        }
77    }
78
79    /// Releases ownership when held by this token.
80    ///
81    /// # Errors
82    ///
83    /// Propagates store failures.
84    ///
85    /// # Panics
86    ///
87    /// Panics when the internal acquired flag mutex is poisoned.
88    pub fn release(&self) -> Result<(), LockError> {
89        self.store.delete(&self.resource, &self.token)?;
90        *self
91            .acquired
92            .lock()
93            .expect("serenade-lock acquired flag poisoned") = false;
94        Ok(())
95    }
96
97    /// Extends TTL. `ttl: None` uses the lock default TTL (which may also be `None` = forever).
98    ///
99    /// # Errors
100    ///
101    /// Returns [`LockError::NotHeld`] when this token does not own the resource.
102    ///
103    /// # Panics
104    ///
105    /// Panics when the internal acquired flag mutex is poisoned.
106    pub fn refresh(&self, ttl: Option<Duration>) -> Result<(), LockError> {
107        let ttl = ttl.or(self.ttl);
108        self.store
109            .put_off_expiration(&self.resource, &self.token, ttl)?;
110        *self
111            .acquired
112            .lock()
113            .expect("serenade-lock acquired flag poisoned") = true;
114        Ok(())
115    }
116
117    /// Store-backed ownership check.
118    ///
119    /// # Errors
120    ///
121    /// Propagates store failures.
122    pub fn is_acquired(&self) -> Result<bool, LockError> {
123        self.store.exists(&self.resource, &self.token)
124    }
125}
126
127impl Drop for Lock {
128    fn drop(&mut self) {
129        if !self.auto_release {
130            return;
131        }
132        let mut acquired = self
133            .acquired
134            .lock()
135            .unwrap_or_else(std::sync::PoisonError::into_inner);
136        if !*acquired {
137            return;
138        }
139        let _ = self.store.delete(&self.resource, &self.token);
140        *acquired = false;
141    }
142}