1use std::sync::Arc;
4use std::time::Duration;
5
6use crate::{Lock, LockError, LockStore, generate_lock_token, validate_resource};
7
8pub const DEFAULT_LOCK_TTL: Duration = Duration::from_secs(300);
10
11#[derive(Clone)]
13pub struct LockFactory {
14 store: Arc<dyn LockStore>,
15}
16
17impl LockFactory {
18 #[must_use]
20 pub fn new(store: Arc<dyn LockStore>) -> Self {
21 Self { store }
22 }
23
24 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 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}