Skip to main content

serenade_lock/
filesystem.rs

1//! Disk-backed [`LockStore`].
2
3use std::fs;
4use std::path::{Path, PathBuf};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use crate::{LockError, LockStore, validate_resource};
8
9const MAGIC: &[u8; 4] = b"SLCK";
10const VERSION: u8 = 1;
11const HEADER_LEN: usize = 13; // magic(4) + version(1) + expires_ms(8)
12
13/// Configuration for [`FilesystemLockStore`].
14#[derive(Clone, Debug)]
15pub struct FilesystemLockStoreConfig {
16    directory: PathBuf,
17    prefix: String,
18}
19
20impl FilesystemLockStoreConfig {
21    /// Root directory that will contain the prefix subdirectory.
22    #[must_use]
23    pub fn new(directory: impl Into<PathBuf>) -> Self {
24        Self {
25            directory: directory.into(),
26            prefix: "serenade".to_owned(),
27        }
28    }
29
30    /// Sets the single path-segment prefix (default `serenade`).
31    #[must_use]
32    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
33        self.prefix = prefix.into();
34        self
35    }
36
37    /// Configured root directory.
38    #[must_use]
39    pub fn directory(&self) -> &Path {
40        &self.directory
41    }
42
43    /// Configured prefix segment.
44    #[must_use]
45    pub fn prefix(&self) -> &str {
46        &self.prefix
47    }
48}
49
50/// Disk-backed [`LockStore`] (one file per resource).
51#[derive(Debug)]
52pub struct FilesystemLockStore {
53    root: PathBuf,
54}
55
56impl FilesystemLockStore {
57    /// Opens (creating) `{directory}/{prefix}` for lock files.
58    ///
59    /// # Errors
60    ///
61    /// Returns [`LockError::Store`] when the prefix is invalid or directories cannot be created.
62    pub fn open(config: FilesystemLockStoreConfig) -> Result<Self, LockError> {
63        let FilesystemLockStoreConfig { directory, prefix } = config;
64        validate_prefix(&prefix)?;
65        let root = directory.join(&prefix);
66        fs::create_dir_all(&root).map_err(|error| LockError::Store {
67            message: format!("create {}: {error}", root.display()),
68        })?;
69        Ok(Self { root })
70    }
71
72    fn path_for(&self, resource: &str) -> PathBuf {
73        self.root.join(format!("{}.lock", hex_key(resource)))
74    }
75
76    fn read_entry(&self, resource: &str) -> Result<Option<(u64, String)>, LockError> {
77        let path = self.path_for(resource);
78        match fs::read(&path) {
79            Ok(bytes) => {
80                let Some((expires, token)) = parse_record(&bytes) else {
81                    let _ = fs::remove_file(&path);
82                    return Ok(None);
83                };
84                if is_expired_unix_ms(expires) {
85                    let _ = fs::remove_file(&path);
86                    return Ok(None);
87                }
88                Ok(Some((expires, token)))
89            }
90            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
91            Err(error) => Err(LockError::Store {
92                message: format!("read {}: {error}", path.display()),
93            }),
94        }
95    }
96
97    fn write_entry(
98        &self,
99        resource: &str,
100        token: &str,
101        ttl: Option<Duration>,
102    ) -> Result<(), LockError> {
103        let path = self.path_for(resource);
104        let expires = unix_ms_from_ttl(ttl);
105        let record = encode_record(expires, token.as_bytes());
106        atomic_write(&path, &record)
107    }
108}
109
110impl LockStore for FilesystemLockStore {
111    fn save(&self, resource: &str, token: &str, ttl: Option<Duration>) -> Result<(), LockError> {
112        validate_resource(resource)?;
113        if let Some((_expires, held)) = self.read_entry(resource)?
114            && held != token
115        {
116            return Err(LockError::Conflict {
117                key: resource.to_owned(),
118            });
119        }
120        self.write_entry(resource, token, ttl)
121    }
122
123    fn delete(&self, resource: &str, token: &str) -> Result<(), LockError> {
124        validate_resource(resource)?;
125        let path = self.path_for(resource);
126        match self.read_entry(resource)? {
127            Some((_expires, held)) if held == token => match fs::remove_file(&path) {
128                Ok(()) => Ok(()),
129                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
130                Err(error) => Err(LockError::Store {
131                    message: format!("delete {}: {error}", path.display()),
132                }),
133            },
134            Some(_) | None => Ok(()),
135        }
136    }
137
138    fn exists(&self, resource: &str, token: &str) -> Result<bool, LockError> {
139        validate_resource(resource)?;
140        Ok(matches!(self.read_entry(resource)?, Some((_expires, held)) if held == token))
141    }
142
143    fn put_off_expiration(
144        &self,
145        resource: &str,
146        token: &str,
147        ttl: Option<Duration>,
148    ) -> Result<(), LockError> {
149        validate_resource(resource)?;
150        match self.read_entry(resource)? {
151            Some((_expires, held)) if held == token => self.write_entry(resource, token, ttl),
152            Some(_) | None => Err(LockError::NotHeld {
153                key: resource.to_owned(),
154            }),
155        }
156    }
157}
158
159fn validate_prefix(prefix: &str) -> Result<(), LockError> {
160    if prefix.is_empty()
161        || prefix.contains('/')
162        || prefix.contains('\\')
163        || prefix == "."
164        || prefix == ".."
165    {
166        return Err(LockError::Store {
167            message: "filesystem lock prefix must be a single non-empty path segment".to_owned(),
168        });
169    }
170    Ok(())
171}
172
173fn hex_key(key: &str) -> String {
174    key.as_bytes()
175        .iter()
176        .fold(String::with_capacity(key.len() * 2), |mut out, byte| {
177            out.push(char::from_digit(u32::from(*byte >> 4), 16).unwrap_or('0'));
178            out.push(char::from_digit(u32::from(*byte & 0x0f), 16).unwrap_or('0'));
179            out
180        })
181}
182
183fn encode_record(expires_unix_ms: u64, token: &[u8]) -> Vec<u8> {
184    let mut out = Vec::with_capacity(HEADER_LEN + token.len());
185    out.extend_from_slice(MAGIC);
186    out.push(VERSION);
187    out.extend_from_slice(&expires_unix_ms.to_le_bytes());
188    out.extend_from_slice(token);
189    out
190}
191
192fn parse_record(bytes: &[u8]) -> Option<(u64, String)> {
193    if bytes.len() < HEADER_LEN || &bytes[..4] != MAGIC || bytes[4] != VERSION {
194        return None;
195    }
196    let mut expiry_bytes = [0_u8; 8];
197    expiry_bytes.copy_from_slice(&bytes[5..13]);
198    let expires_unix_ms = u64::from_le_bytes(expiry_bytes);
199    let token = String::from_utf8(bytes[HEADER_LEN..].to_vec()).ok()?;
200    Some((expires_unix_ms, token))
201}
202
203fn is_expired_unix_ms(expires_unix_ms: u64) -> bool {
204    if expires_unix_ms == 0 {
205        return false;
206    }
207    let now_ms = SystemTime::now()
208        .duration_since(UNIX_EPOCH)
209        .map_or(u64::MAX, |now| {
210            u64::try_from(now.as_millis()).unwrap_or(u64::MAX)
211        });
212    now_ms >= expires_unix_ms
213}
214
215fn unix_ms_from_ttl(ttl: Option<Duration>) -> u64 {
216    let Some(ttl) = ttl else {
217        return 0;
218    };
219    let now = SystemTime::now();
220    let now_ms = now.duration_since(UNIX_EPOCH).map_or(0, |duration| {
221        u64::try_from(duration.as_millis()).unwrap_or(0)
222    });
223    now.checked_add(ttl)
224        .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
225        .map_or(now_ms, |duration| {
226            u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
227        })
228}
229
230fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), LockError> {
231    let tmp = path.with_extension("lock.tmp");
232    fs::write(&tmp, bytes).map_err(|error| LockError::Store {
233        message: format!("write {}: {error}", tmp.display()),
234    })?;
235    match fs::rename(&tmp, path) {
236        Ok(()) => Ok(()),
237        Err(error) => {
238            let _ = fs::remove_file(&tmp);
239            Err(LockError::Store {
240                message: format!("rename {} -> {}: {error}", tmp.display(), path.display()),
241            })
242        }
243    }
244}
245
246#[cfg(test)]
247mod atomic_write_tests {
248    use super::atomic_write;
249    use crate::LockError;
250    use std::fs;
251
252    #[test]
253    fn rename_fails_when_destination_is_directory() {
254        let dir = tempfile::tempdir().expect("tempdir");
255        let path = dir.path().join("dest.lock");
256        fs::create_dir(&path).expect("dest is a directory");
257        assert!(matches!(
258            atomic_write(&path, b"SLCK"),
259            Err(LockError::Store { message }) if message.contains("rename")
260        ));
261        assert!(!dir.path().join("dest.lock.tmp").exists());
262    }
263}