bark/lock_manager/mod.rs
1//! Named locks usable across async tasks, threads, processes, or browser
2//! tabs — depending on the backend you pick.
3//!
4//! # What it is
5//!
6//! bark needs to coordinate access to a shared dataset (e.g. a wallet
7//! database) so that two callers don't trample each other. The
8//! [`LockManager`] trait is where you plug in *how that coordination is
9//! enforced* on the target platform.
10//!
11//! Pick a manager whose enforcement scope matches the reach of the
12//! dataset bark is opening:
13//!
14//! - A wallet that only ever runs in a single process? An in-memory
15//! manager is enough.
16//! - A wallet on disk that another process might also open? You need a
17//! cross-process file-based manager.
18//! - A wallet running in the browser, possibly opened in multiple tabs?
19//! You need the Web Locks backend.
20//!
21//! Pick the wrong scope and bark will silently allow concurrent access.
22//! The rest of this page is the picking guide.
23//!
24//! # Platform support
25//!
26//! | Backend | Linux | macOS | iOS | Android | Windows | Web (wasm32) |
27//! |----------------------------------------------------------|:-----:|:-----:|:---:|:-------:|:-------:|:------------:|
28//! | [`MemoryLockManager`](memory::MemoryLockManager) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
29//! | [`FlockPidLockManager`](pid_flock::FlockPidLockManager) | ✓ | ✓ | | ✓ | ✓ | |
30//! | [`FcntlPidLockManager`](pid_fcntl::FcntlPidLockManager) | ✓ | ✓ | ✓ | ✓ | | |
31//! | [`WebLockManager`](web_locks::WebLockManager) | | | | | | ✓ |
32//!
33//! # Safety scope
34//!
35//! Each backend prevents concurrent access by callers under a different
36//! scope. Pick the one that matches the threat you actually have:
37//!
38//! | Backend | Same async runtime | Same OS process | Across processes | Across machines (NFS/SMB) | Across browser tabs |
39//! |------------------|:------------------:|:---------------:|:----------------:|:-------------------------:|:-------------------:|
40//! | `Memory` | ✓ | ✓ | | | |
41//! | `FlockPidLock` | ✓ | ✓ | refuses 2nd | ⚠ | |
42//! | `FcntlPidLock` | ✓ | ✓ | refuses 2nd | ✓ (POSIX-compliant NFS) | |
43//! | `WebLocks` | ✓ | (n/a) | (n/a) | (n/a) | ✓ |
44//!
45//! ⚠ `FlockPidLock` uses `flock(2)` on Unix, whose behavior over networked
46//! filesystems is implementation-defined; use `FcntlPidLock` there.
47//!
48//! # Picking a backend
49//!
50//! - **Don't want to think about it?** Call [`platform_default`] —
51//! it returns the sensible PidLock-family backend for your build
52//! target (wasm gets Web Locks). Override with a specific backend
53//! only when you have a non-default deployment shape (e.g.
54//! multi-process access to the same datadir).
55//! - **Single-process apps and tests** —
56//! [`MemoryLockManager`](memory::MemoryLockManager) is the safe
57//! default: every instance in the process shares one key map, so two
58//! callers cannot accidentally end up with disjoint lock universes.
59//! - **Single-process-per-datadir CLIs / daemons** — pick a `PidLock`
60//! variant: [`FlockPidLockManager`](pid_flock::FlockPidLockManager)
61//! on Linux/macOS/Android/Windows desktops, or
62//! [`FcntlPidLockManager`](pid_fcntl::FcntlPidLockManager) when the
63//! datadir may live on networked storage. One OS-level lock on
64//! `<datadir>/LOCK` guarantees single-process exclusivity; per-key
65//! locking is in-memory.
66//! - **Web (wasm32)** — only [`WebLockManager`](web_locks::WebLockManager)
67//! (which delegates to `navigator.locks`) is available. Prevents
68//! concurrent access across same-origin tabs in the same browser;
69//! gives no guarantees across different browsers or incognito
70//! sessions.
71//!
72//! # What callers must guarantee
73//!
74//! - **Use one backend per dataset, forever.** Two distinct managers do
75//! not exclude each other; mixing backends or directories on the same
76//! data is silently unsafe.
77//! - **Use the same lock directory in every instance** for a given
78//! dataset.
79
80mod key;
81mod internal_memory;
82pub mod memory;
83#[cfg(target_arch = "wasm32")]
84pub mod web_locks;
85#[cfg(all(any(unix, windows), not(target_arch = "wasm32")))]
86pub mod pid_flock;
87#[cfg(all(any(unix), not(target_arch = "wasm32")))]
88pub mod pid_fcntl;
89
90use std::time::Duration;
91use std::path::PathBuf;
92use anyhow::bail;
93
94const POLL_INTERVAL: Duration = Duration::from_millis(50);
95
96/// Errors from constructing a pid-lock-based [`LockManager`]
97/// ([`pid_flock::FlockPidLockManager`] or [`pid_fcntl::FcntlPidLockManager`]).
98///
99/// Pattern-match on this when you want to surface "another process is
100/// already using this datadir" differently from setup-failure cases.
101#[derive(thiserror::Error, Debug)]
102pub enum PidLockError {
103 /// Another instance — same process or otherwise — already holds
104 /// the pid lock for this datadir. The `pid` is the value that
105 /// instance wrote into the LOCK file (best-effort; may be absent
106 /// or stale).
107 #[error("another process is already using datadir {datadir}{}",
108 match pid {
109 Some(p) => format!(" (holder PID: {})", p),
110 None => String::new(),
111 })]
112 AlreadyHeld {
113 datadir: PathBuf,
114 pid: Option<u32>,
115 },
116
117 /// Anything else that went wrong setting up the datadir or
118 /// opening the lock file (filesystem permission, ENOENT, etc.).
119 #[error("failed to set up datadir {datadir}")]
120 SetupFailed {
121 datadir: PathBuf,
122 #[source]
123 source: anyhow::Error,
124 },
125}
126
127/// A handle that holds a named lock until dropped.
128///
129/// Trait objects are returned from [`LockManager`] methods so callers do
130/// not need to spell the backend's concrete guard type.
131pub trait LockGuard: Send + Sync + std::fmt::Debug {}
132
133/// Acquire and release named locks.
134///
135/// Implementations only need to provide [`try_lock`](Self::try_lock); the
136/// default [`lock`](Self::lock) polls it under a [`tokio::time::timeout`].
137#[async_trait::async_trait]
138pub trait LockManager: Send + Sync + std::fmt::Debug {
139 /// Try to acquire the named lock without waiting. Returns `None` if
140 /// it is already held, the key is rejected by [`validate_key`], or
141 /// the backend cannot acquire the lock for any other reason.
142 async fn try_lock(&self, key: &str) -> Option<Box<dyn LockGuard>>;
143
144 /// Acquire the named lock, polling [`try_lock`](Self::try_lock) until
145 /// it succeeds or `timeout` elapses.
146 ///
147 /// `timeout` is mandatory to make accidental deadlocks impossible at
148 /// the API level. Pass [`Duration::MAX`] if you really want to wait
149 /// indefinitely.
150 async fn lock(&self, key: &str, timeout: Duration)
151 -> anyhow::Result<Box<dyn LockGuard>>
152 {
153 let result = tokio::time::timeout(timeout, async {
154 loop {
155 if let Some(g) = self.try_lock(key).await {
156 return g;
157 }
158 tokio::time::sleep(POLL_INTERVAL).await;
159 }
160 }).await;
161 match result {
162 Ok(g) => Ok(g),
163 Err(_) => bail!("timed out acquiring lock {:?} after {:?}", key, timeout),
164 }
165 }
166}
167
168/// Return the recommended [`LockManager`] backend for the current
169/// build target. Most platforms will result a `LockManager` that
170/// can only be instantiated once.
171pub fn platform_default(datadir: impl Into<PathBuf>) -> anyhow::Result<Box<dyn LockManager>> {
172 #[cfg(target_arch = "wasm32")]
173 {
174 // Use navigator.locks via WebLockManager. An in-memory variant
175 // wouldn't be safe — the user can open the app in multiple
176 // tabs, each a separate wasm instance. navigator.locks is the
177 // only cross-tab coordination primitive in the browser.
178 // `datadir` is ignored.
179 let _ = datadir;
180 return Ok(Box::new(web_locks::WebLockManager::new()));
181 }
182
183 #[cfg(all(unix, not(target_arch = "wasm32")))]
184 {
185 // Use fcntl: it has wider support than flock across the unix
186 // family.
187 //
188 // We pick a PidLock variant over per-key fcntl files because:
189 // 1. It doesn't pollute the datadir with `<key>.lock` files.
190 // 2. It's faster — one OS-level lock at construction, then
191 // in-memory locking per key (no syscall per try_lock).
192 // 3. It avoids cross-process footguns like notifications not
193 // firing when a second process is doing the work.
194 return Ok(Box::new(pid_fcntl::FcntlPidLockManager::new(datadir)?));
195 }
196
197 #[cfg(all(windows, not(target_arch = "wasm32")))]
198 {
199 // Use std::fs::File::try_lock (LockFileEx under the hood):
200 // fcntl doesn't exist on Windows, and LockFileEx is the
201 // direct equivalent.
202 //
203 // We pick a PidLock variant over per-key file locks because:
204 // 1. It doesn't pollute the datadir with `<key>.lock` files.
205 // 2. It's faster — one OS-level lock at construction, then
206 // in-memory locking per key (no syscall per try_lock).
207 // 3. It avoids cross-process footguns like notifications not
208 // firing when a second process is doing the work.
209 return Ok(Box::new(pid_flock::FlockPidLockManager::new(datadir)?));
210 }
211
212 #[cfg(not(any(target_arch = "wasm32", unix, windows)))]
213 panic!("lock_manager::platform_default: no default backend for this target");
214}
215
216// The shared test harness uses `tokio::spawn` / `tokio::sync::Barrier`
217// / `tokio::time::timeout`, all of which require the `rt` feature that
218// is desktop-only. The web_locks backend has its own wasm-bindgen-test
219// suite in its module.
220#[cfg(all(test, not(target_arch = "wasm32")))]
221mod test {
222 use super::*;
223
224 use std::path::PathBuf;
225 use std::fs;
226 use std::sync::Arc;
227
228 const TEST_TIMEOUT: Duration = Duration::from_secs(5);
229
230 struct TestBackend {
231 name: &'static str,
232 mgr: Arc<dyn LockManager>,
233 // `None` for backends that don't use a directory (Memory).
234 dir: Option<PathBuf>,
235 }
236
237 impl Drop for TestBackend {
238 fn drop(&mut self) {
239 if let Some(d) = &self.dir {
240 let _ = fs::remove_dir_all(d);
241 }
242 }
243 }
244
245 fn tmp_dir() -> PathBuf {
246 let dir = std::env::temp_dir()
247 .join(format!("bark-lock-test-{}", rand::random::<u64>()));
248 fs::create_dir_all(&dir).unwrap();
249 dir
250 }
251
252 /// Every backend available on this target.
253 fn managers() -> Vec<TestBackend> {
254 let mut v = Vec::new();
255
256 v.push(TestBackend {
257 name: "InternalMemory",
258 mgr: Arc::new(internal_memory::InternalMemoryLockManager::new()),
259 dir: None,
260 });
261
262 v.push(TestBackend {
263 name: "Memory",
264 mgr: Arc::new(memory::MemoryLockManager::new()),
265 dir: None,
266 });
267
268 #[cfg(all(any(unix, windows), not(target_arch = "wasm32")))]
269 {
270 let dir = tmp_dir();
271 v.push(TestBackend {
272 name: "FlockPidLock",
273 mgr: Arc::new(pid_flock::FlockPidLockManager::new(&dir).unwrap()),
274 dir: Some(dir),
275 });
276 }
277
278 #[cfg(all(unix, not(target_arch = "wasm32")))]
279 {
280 let dir = tmp_dir();
281 v.push(TestBackend {
282 name: "FcntlPidLock",
283 mgr: Arc::new(pid_fcntl::FcntlPidLockManager::new(&dir).unwrap()),
284 dir: Some(dir),
285 });
286 }
287
288 #[cfg(target_arch = "wasm32")]
289 {
290 v.push(TestBackend {
291 name: "Web",
292 mgr: Arc::new(web_locks::WebLockManager::new()),
293 dir: None,
294 });
295 }
296
297 v
298 }
299
300 #[tokio::test]
301 async fn acquire_and_release() {
302 for tb in managers() {
303 let g = tb.mgr.lock("bark.ln_receive.1", TEST_TIMEOUT).await.unwrap();
304 drop(g);
305 let _g2 = tb.mgr.lock("bark.ln_receive.1", TEST_TIMEOUT).await.unwrap();
306 }
307 }
308
309 #[tokio::test]
310 async fn try_lock_returns_none_when_held() {
311 for tb in managers() {
312 let g = tb.mgr.lock("k", TEST_TIMEOUT).await.unwrap();
313 let busy = tb.mgr.try_lock("k").await;
314 assert!(busy.is_none(), "{}: second try_lock should be blocked", tb.name);
315 drop(g);
316 let g2 = tb.mgr.try_lock("k").await;
317 assert!(g2.is_some(), "{}: try_lock should succeed after release", tb.name);
318 }
319 }
320
321 #[tokio::test]
322 async fn distinct_keys_dont_block() {
323 for tb in managers() {
324 let _g1 = tb.mgr.lock("a", TEST_TIMEOUT).await.unwrap();
325 let _g2 = tb.mgr.lock("b", TEST_TIMEOUT).await.unwrap();
326 }
327 }
328
329 #[tokio::test]
330 async fn lock_returns_timeout_error() {
331 for tb in managers() {
332 let _held = tb.mgr.lock("k", TEST_TIMEOUT).await.unwrap();
333
334 // Acquire from another task so holding `_held` doesn't block
335 // the test on its own memory-mutex wait.
336 let mgr = Arc::clone(&tb.mgr);
337 let result = tokio::spawn(async move {
338 mgr.lock("k", Duration::from_millis(150)).await
339 }).await.unwrap();
340
341 assert!(result.is_err(), "{}: expected timeout, got {:?}", tb.name, result);
342 assert!(result.unwrap_err().to_string().contains("timed out"));
343 }
344 }
345
346 #[tokio::test]
347 async fn waiter_unblocks_after_drop() {
348 for tb in managers() {
349 let g = tb.mgr.lock("k", TEST_TIMEOUT).await.unwrap();
350
351 let mgr = Arc::clone(&tb.mgr);
352 let waiter = tokio::spawn(async move {
353 mgr.lock("k", TEST_TIMEOUT).await.unwrap()
354 });
355
356 tokio::time::sleep(Duration::from_millis(150)).await;
357 drop(g);
358
359 let result = tokio::time::timeout(Duration::from_secs(2), waiter).await;
360 assert!(result.is_ok(), "{}: waiter should succeed after holder dropped", tb.name);
361 }
362 }
363
364 #[tokio::test]
365 async fn ten_concurrent_try_lock_only_one_wins() {
366 // Asserts that `try_lock` is atomic under contention: when N
367 // callers race for the same key, exactly one observes it as free.
368 //
369 // Force 10 tasks to call try_lock at the same point via a barrier.
370 // Whichever the executor polls first will hold the guard for
371 // 100 ms; that is long enough for the other 9 tasks to be polled
372 // and observe the lock as held.
373 use tokio::sync::Barrier;
374 const N: usize = 10;
375
376 for tb in managers() {
377 let barrier = Arc::new(Barrier::new(N));
378 let mut handles = Vec::with_capacity(N);
379
380 for _ in 0..N {
381 let mgr = Arc::clone(&tb.mgr);
382 let barrier = Arc::clone(&barrier);
383 handles.push(tokio::spawn(async move {
384 barrier.wait().await;
385 let guard = mgr.try_lock("contested").await;
386 let acquired = guard.is_some();
387 if acquired {
388 tokio::time::sleep(Duration::from_millis(100)).await;
389 }
390 acquired
391 }));
392 }
393
394 let mut successes = 0usize;
395 for h in handles {
396 successes += h.await.unwrap() as usize;
397 }
398 assert_eq!(
399 successes, 1,
400 "{}: expected exactly 1 successful try_lock out of {}, got {}",
401 tb.name, N, successes,
402 );
403 }
404 }
405
406 #[tokio::test]
407 async fn reject_bad_keys() {
408 for tb in managers() {
409 // Empty.
410 assert!(tb.mgr.try_lock("").await.is_none(), "{}: empty", tb.name);
411 // Disallowed character (path separator).
412 assert!(tb.mgr.try_lock("a/b").await.is_none(), "{}: slash", tb.name);
413 // Disallowed character (angle bracket).
414 assert!(tb.mgr.try_lock("a<b>").await.is_none(), "{}: angle", tb.name);
415 // Disallowed start (dot).
416 assert!(tb.mgr.try_lock(".abc").await.is_none(), "{}: leading dot", tb.name);
417 // Disallowed start (underscore).
418 assert!(tb.mgr.try_lock("_abc").await.is_none(), "{}: leading underscore", tb.name);
419 // Disallowed end (dash).
420 assert!(tb.mgr.try_lock("abc-").await.is_none(), "{}: trailing dash", tb.name);
421 // Disallowed end (dot).
422 assert!(tb.mgr.try_lock("abc.").await.is_none(), "{}: trailing dot", tb.name);
423 // Path-traversal sentinels.
424 assert!(tb.mgr.try_lock(".").await.is_none(), "{}: dot", tb.name);
425 assert!(tb.mgr.try_lock("..").await.is_none(), "{}: dotdot", tb.name);
426
427 // Allowed: bark's actual key shapes.
428 assert!(tb.mgr.try_lock("bark.lightning.send.42").await.is_some(),
429 "{}: bark.lightning.send.42 should be valid", tb.name);
430 // Allowed: digit start (hex wallet fingerprint).
431 assert!(tb.mgr.try_lock("01abcdef.round.7").await.is_some(),
432 "{}: 01abcdef.round.7 should be valid", tb.name);
433 }
434 }
435
436 #[test]
437 fn managers_covers_every_compiled_backend() {
438 // If a backend is dropped from `managers()`, this assertion goes red.
439 let names: Vec<_> = managers().iter().map(|tb| tb.name).collect();
440 assert!(names.contains(&"Memory"), "missing Memory: {:?}", names);
441 #[cfg(target_arch = "wasm32")]
442 assert!(names.contains(&"Web"), "missing Web: {:?}", names);
443 }
444
445 #[tokio::test]
446 async fn platform_default_returns_a_working_manager() {
447 let dir = tmp_dir();
448 let mgr = super::platform_default(&dir)
449 .expect("platform_default should construct a manager");
450 let g = mgr.try_lock("bark.platform.default.test").await;
451 assert!(g.is_some(), "platform_default's manager should grant a fresh lock");
452 drop(g);
453 let _ = fs::remove_dir_all(&dir);
454 }
455}