Skip to main content

serenade_lock/
factory.rs

1//! [`LockFactory`] builds [`Lock`] handles.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use crate::{Lock, LockError, LockStore, generate_lock_token, validate_resource};
7
8/// Default TTL when [`LockFactory::create_lock`] receives `ttl: None` (Symfony default).
9pub const DEFAULT_LOCK_TTL: Duration = Duration::from_secs(300);
10
11/// Creates [`Lock`] handles against a shared [`LockStore`].
12#[derive(Clone)]
13pub struct LockFactory {
14    store: Arc<dyn LockStore>,
15}
16
17impl LockFactory {
18    /// Wraps `store`.
19    #[must_use]
20    pub fn new(store: Arc<dyn LockStore>) -> Self {
21        Self { store }
22    }
23
24    /// Builds a lock for `resource` without acquiring it.
25    ///
26    /// When `ttl` is `None`, uses [`DEFAULT_LOCK_TTL`]. For no expiry, call
27    /// [`Self::create_lock_forever`].
28    ///
29    /// # Errors
30    ///
31    /// Returns [`LockError::InvalidKey`] or [`LockError::Generation`].
32    pub fn create_lock(
33        &self,
34        resource: impl Into<String>,
35        ttl: Option<Duration>,
36        auto_release: bool,
37    ) -> Result<Lock, LockError> {
38        let ttl = Some(ttl.unwrap_or(DEFAULT_LOCK_TTL));
39        self.build(resource, ttl, auto_release)
40    }
41
42    /// Builds a lock that does not expire until released.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`LockError::InvalidKey`] or [`LockError::Generation`].
47    pub fn create_lock_forever(
48        &self,
49        resource: impl Into<String>,
50        auto_release: bool,
51    ) -> Result<Lock, LockError> {
52        self.build(resource, None, auto_release)
53    }
54
55    fn build(
56        &self,
57        resource: impl Into<String>,
58        ttl: Option<Duration>,
59        auto_release: bool,
60    ) -> Result<Lock, LockError> {
61        let resource = resource.into();
62        validate_resource(&resource)?;
63        let token = generate_lock_token()?;
64        Ok(Lock::new(
65            resource,
66            token,
67            Arc::clone(&self.store),
68            ttl,
69            auto_release,
70        ))
71    }
72}