Skip to main content

serenade_lock/
memory.rs

1//! Process-local [`LockStore`].
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5use std::time::{Duration, Instant};
6
7use crate::{LockError, LockStore, validate_resource};
8
9#[derive(Debug)]
10struct Entry {
11    token: String,
12    expires_at: Option<Instant>,
13}
14
15impl Entry {
16    fn is_expired(&self, now: Instant) -> bool {
17        self.expires_at.is_some_and(|at| at <= now)
18    }
19}
20
21/// In-process lock store backed by a [`Mutex`] + [`HashMap`].
22#[derive(Debug, Default)]
23pub struct InMemoryLockStore {
24    inner: Mutex<HashMap<String, Entry>>,
25}
26
27impl InMemoryLockStore {
28    /// Empty store.
29    #[must_use]
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    fn with_map<T>(&self, f: impl FnOnce(&mut HashMap<String, Entry>) -> T) -> T {
35        let mut guard = self
36            .inner
37            .lock()
38            .expect("serenade-lock InMemoryLockStore mutex poisoned");
39        f(&mut guard)
40    }
41}
42
43impl LockStore for InMemoryLockStore {
44    fn save(&self, resource: &str, token: &str, ttl: Option<Duration>) -> Result<(), LockError> {
45        validate_resource(resource)?;
46        let now = Instant::now();
47        self.with_map(|map| {
48            if let Some(entry) = map.get(resource)
49                && !entry.is_expired(now)
50                && entry.token != token
51            {
52                return Err(LockError::Conflict {
53                    key: resource.to_owned(),
54                });
55            }
56            map.insert(
57                resource.to_owned(),
58                Entry {
59                    token: token.to_owned(),
60                    expires_at: ttl.map(|duration| now + duration),
61                },
62            );
63            Ok(())
64        })
65    }
66
67    fn delete(&self, resource: &str, token: &str) -> Result<(), LockError> {
68        validate_resource(resource)?;
69        let now = Instant::now();
70        self.with_map(|map| {
71            match map.get(resource) {
72                Some(entry) if entry.is_expired(now) => {
73                    map.remove(resource);
74                }
75                Some(entry) if entry.token == token => {
76                    map.remove(resource);
77                }
78                Some(_) | None => {}
79            }
80            Ok(())
81        })
82    }
83
84    fn exists(&self, resource: &str, token: &str) -> Result<bool, LockError> {
85        validate_resource(resource)?;
86        let now = Instant::now();
87        self.with_map(|map| {
88            let Some(entry) = map.get(resource) else {
89                return Ok(false);
90            };
91            if entry.is_expired(now) {
92                map.remove(resource);
93                return Ok(false);
94            }
95            Ok(entry.token == token)
96        })
97    }
98
99    fn put_off_expiration(
100        &self,
101        resource: &str,
102        token: &str,
103        ttl: Option<Duration>,
104    ) -> Result<(), LockError> {
105        validate_resource(resource)?;
106        let now = Instant::now();
107        self.with_map(|map| {
108            let Some(entry) = map.get_mut(resource) else {
109                return Err(LockError::NotHeld {
110                    key: resource.to_owned(),
111                });
112            };
113            if entry.is_expired(now) {
114                map.remove(resource);
115                return Err(LockError::NotHeld {
116                    key: resource.to_owned(),
117                });
118            }
119            if entry.token != token {
120                return Err(LockError::NotHeld {
121                    key: resource.to_owned(),
122                });
123            }
124            entry.expires_at = ttl.map(|duration| now + duration);
125            Ok(())
126        })
127    }
128}