Skip to main content

rainier_cache/
lock.rs

1//! Atomic locks — [`LockManager`], [`Lock`] and [`LockGuard`].
2//!
3//! Laravel's `Cache::lock('name', 10)`, and the machinery behind
4//! `withoutOverlapping()` and `onOneServer()`.
5//!
6//! ```
7//! # use rainier_cache::{LockManager, MemoryCache};
8//! # use std::sync::Arc;
9//! # use std::time::Duration;
10//! # #[tokio::main] async fn main() -> rainier_support::Result<()> {
11//! let locks = LockManager::new(Arc::new(MemoryCache::new()));
12//!
13//! let outcome = locks
14//!     .lock("reports:nightly", Duration::from_secs(600))
15//!     .run(async {
16//!         // …exactly one caller reaches here.
17//!         Ok::<_, rainier_support::Error>("built")
18//!     })
19//!     .await?;
20//!
21//! assert_eq!(outcome, Some("built"));
22//! # Ok(()) }
23//! ```
24//!
25//! # What makes it a lock
26//!
27//! Three things, and leaving out any one of them produces something that looks
28//! like a lock and is not.
29//!
30//! **An atomic acquire.** [`Cache::add`] is "store only if absent", decided by
31//! the store rather than by the caller. A `has` followed by a `put` lets two
32//! processes both observe the key absent and both write.
33//!
34//! **An owner token.** Every acquire mints a random one and stores it as the
35//! value. Release is [`Cache::forget_if`], not `forget` — see below.
36//!
37//! **A TTL.** The holder can die. A lock with no expiry, taken by a process
38//! that is then `kill -9`ed, is a task that never runs again until somebody
39//! notices and deletes a key by hand.
40//!
41//! ## Why release compares the token
42//!
43//! The bug this avoids is worth spelling out, because it is invisible until it
44//! is a production incident:
45//!
46//! ```text
47//! t=0    A acquires `nightly`, ttl 60s          A holds it
48//! t=0    A begins work
49//! t=61   A is still stalled — GC, a slow query, a suspended VM
50//! t=61   the key expires                        nobody holds it
51//! t=62   B acquires `nightly`                   B holds it
52//! t=63   A finishes and releases
53//!          - with `forget`:     A deletes B's lock. C can now acquire while
54//!                               B is still running. Two copies.
55//!          - with `forget_if`:  A's token no longer matches. Nothing happens.
56//! ```
57//!
58//! `forget_if` cannot make A's overrun safe — B is already running — but it
59//! stops one overrun becoming an unbounded number.
60//!
61//! ## The guarantee, stated honestly
62//!
63//! This is a **lease**, not a mutex. If a holder overruns its TTL, another
64//! process will take the lock and both will run. No lock built on a TTL can
65//! prevent that, including Redlock; the standard advice applies:
66//!
67//! - Set the TTL comfortably longer than the work takes.
68//! - [`extend`](LockGuard::extend) it from long-running work, so the TTL tracks
69//!   progress rather than a guess made at the start.
70//! - Where correctness genuinely cannot tolerate two runs, make the work
71//!   idempotent or fence it with a token the *downstream* system checks. A lock
72//!   is a coordination hint, not a correctness proof.
73//!
74//! And the obvious one: a lock in a [`MemoryCache`](crate::MemoryCache) is
75//! per-process, so `on_one_server` across three servers holding three memory
76//! caches is three servers all believing they are the one.
77//! [`LockManager::is_shared`] answers that question.
78
79use std::sync::Arc;
80use std::time::Duration;
81
82use rainier_support::{Error, Result};
83
84use crate::cache::Cache;
85
86/// How long to wait between attempts when blocking for a lock.
87const POLL_INTERVAL: Duration = Duration::from_millis(100);
88
89/// Mints [`Lock`]s against a cache.
90///
91/// Bind one in the container and resolve it; a lock taken through a different
92/// cache is a different lock.
93pub struct LockManager {
94    cache: Arc<dyn Cache>,
95    prefix: String,
96}
97
98impl LockManager {
99    /// Locks in `cache`, under the `lock:` prefix.
100    pub fn new(cache: Arc<dyn Cache>) -> Self {
101        Self { cache, prefix: "lock:".to_string() }
102    }
103
104    /// Locks under a different prefix.
105    ///
106    /// Worth changing when the cache is shared with something else that might
107    /// pick the same names.
108    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
109        self.prefix = prefix.into();
110        self
111    }
112
113    /// A lock called `name`, held for at most `ttl`.
114    pub fn lock(&self, name: impl Into<String>, ttl: Duration) -> Lock {
115        Lock {
116            cache: Arc::clone(&self.cache),
117            key: format!("{}{}", self.prefix, name.into()),
118            ttl,
119            wait: None,
120        }
121    }
122
123    /// Whether locks taken here are visible to other processes.
124    ///
125    /// `false` for an in-process cache, which means `on_one_server` is not
126    /// doing what its name says. Worth asserting at boot rather than
127    /// discovering from a report that ran twice.
128    ///
129    /// ```
130    /// # use rainier_cache::{LockManager, MemoryCache};
131    /// # use std::sync::Arc;
132    /// let locks = LockManager::new(Arc::new(MemoryCache::new()));
133    /// assert!(!locks.is_shared());
134    /// ```
135    pub fn is_shared(&self) -> bool {
136        self.cache.name() != "memory"
137    }
138
139    /// The cache underneath.
140    pub fn cache(&self) -> &Arc<dyn Cache> {
141        &self.cache
142    }
143}
144
145impl std::fmt::Debug for LockManager {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.debug_struct("LockManager")
148            .field("cache", &self.cache.name())
149            .field("prefix", &self.prefix)
150            .finish()
151    }
152}
153
154/// A named lock, not yet held.
155///
156/// Built by [`LockManager::lock`]. Nothing is taken until
157/// [`acquire`](Self::acquire) or [`run`](Self::run).
158pub struct Lock {
159    cache: Arc<dyn Cache>,
160    key: String,
161    ttl: Duration,
162    wait: Option<Duration>,
163}
164
165impl Lock {
166    /// Wait up to `wait` for the lock instead of giving up immediately.
167    ///
168    /// Polls. That is deliberate: the alternative is a pub/sub channel per lock
169    /// name, which is a lot of moving parts to shave a hundred milliseconds off
170    /// a path that is by definition contended and by definition rare.
171    ///
172    /// Use it for "this must happen, just not twice at once". Leave it off for
173    /// "if somebody else is already doing this, I have nothing to do" — which
174    /// is the scheduler's case, and why `without_overlapping` does not wait.
175    pub fn wait_for(mut self, wait: Duration) -> Self {
176        self.wait = Some(wait);
177        self
178    }
179
180    /// Take the lock, or return `None` if somebody else holds it.
181    pub async fn acquire(&self) -> Result<Option<LockGuard>> {
182        let deadline = self.wait.map(|wait| std::time::Instant::now() + wait);
183
184        loop {
185            let owner = mint_owner();
186
187            if self.cache.add(&self.key, owner.as_bytes(), Some(self.ttl)).await? {
188                return Ok(Some(LockGuard {
189                    cache: Arc::clone(&self.cache),
190                    key: self.key.clone(),
191                    owner,
192                    released: false,
193                }));
194            }
195
196            match deadline {
197                Some(deadline) if std::time::Instant::now() + POLL_INTERVAL < deadline => {
198                    tokio::time::sleep(POLL_INTERVAL).await;
199                }
200                _ => return Ok(None),
201            }
202        }
203    }
204
205    /// Run `work` while holding the lock, or return `None` without running it.
206    ///
207    /// The lock is released whether `work` succeeds or fails — a task that
208    /// errors must not hold its lock until the TTL expires, or one bad night
209    /// skips the next hour of runs too.
210    ///
211    /// ```
212    /// # use rainier_cache::{LockManager, MemoryCache};
213    /// # use std::sync::Arc;
214    /// # use std::time::Duration;
215    /// # #[tokio::main] async fn main() -> rainier_support::Result<()> {
216    /// # let locks = LockManager::new(Arc::new(MemoryCache::new()));
217    /// let lock = locks.lock("import", Duration::from_secs(60));
218    ///
219    /// match lock.run(async { Ok::<_, rainier_support::Error>(42) }).await? {
220    ///     Some(value) => assert_eq!(value, 42),
221    ///     None => unreachable!("nobody else holds it"),
222    /// }
223    /// # Ok(()) }
224    /// ```
225    pub async fn run<T, F>(&self, work: F) -> Result<Option<T>>
226    where
227        F: std::future::Future<Output = Result<T>>,
228    {
229        let Some(guard) = self.acquire().await? else {
230            return Ok(None);
231        };
232
233        let outcome = work.await;
234
235        // Released before the result is inspected, so an `Err` does not skip
236        // the release on its way out.
237        guard.release().await?;
238        outcome.map(Some)
239    }
240
241    /// Take the lock over from whoever holds it.
242    ///
243    /// An escape hatch for an operator, not for code. The holder does not find
244    /// out, and if it is still running you now have two.
245    pub async fn force_release(&self) -> Result<bool> {
246        self.cache.forget(&self.key).await
247    }
248
249    /// Whether anybody holds it.
250    ///
251    /// Racy by nature — true the moment you ask and false the moment after —
252    /// so it is for a status page, not for deciding whether to acquire.
253    pub async fn is_held(&self) -> Result<bool> {
254        self.cache.has(&self.key).await
255    }
256
257    /// The cache key, for diagnostics.
258    pub fn key(&self) -> &str {
259        &self.key
260    }
261}
262
263impl std::fmt::Debug for Lock {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        f.debug_struct("Lock").field("key", &self.key).field("ttl", &self.ttl).finish()
266    }
267}
268
269/// A held lock.
270///
271/// # This does not release on drop
272///
273/// Releasing means a round trip to the cache, and `Drop` cannot await. The
274/// options were a blocking call inside `Drop` (which deadlocks a single-threaded
275/// runtime), spawning a task (which needs a runtime handle that may be shutting
276/// down), or being explicit.
277///
278/// Explicit, then — with the TTL as the safety net. A guard that is dropped
279/// without [`release`](Self::release) holds its lock until it expires, which is
280/// late rather than forever. Prefer [`Lock::run`], which cannot forget.
281#[must_use = "a dropped guard holds its lock until the TTL expires; call `release`"]
282pub struct LockGuard {
283    cache: Arc<dyn Cache>,
284    key: String,
285    owner: String,
286    released: bool,
287}
288
289impl LockGuard {
290    /// Release it. `true` if it was still ours to release.
291    ///
292    /// `false` means the TTL expired while we were working and somebody else
293    /// has since taken it — so the work overran, and *two copies have been
294    /// running*. Worth logging where it matters; it is the signal that the TTL
295    /// is too short.
296    pub async fn release(mut self) -> Result<bool> {
297        self.released = true;
298        self.cache.forget_if(&self.key, self.owner.as_bytes()).await
299    }
300
301    /// Push the expiry out to `ttl` from now. `true` if it was still ours.
302    ///
303    /// For work that is still going and does not know how long it has left. A
304    /// `false` here is the same bad news as from `release`, and arrives early
305    /// enough to abandon the work rather than finish it alongside a second
306    /// copy.
307    ///
308    /// Implemented as a re-`put` rather than a bare `EXPIRE`, so it works on
309    /// every driver — including the ones with no separate expiry command.
310    pub async fn extend(&self, ttl: Duration) -> Result<bool> {
311        // Check-then-write, and the gap is real: the lock could expire between
312        // reading and writing, and this would resurrect it under our name while
313        // another holder has it. Narrow, and the alternative is a per-driver
314        // conditional-set primitive for a path that is already a best-effort
315        // heartbeat. `release` is the one that has to be exact, and it is.
316        match self.cache.get(&self.key).await? {
317            Some(current) if current == self.owner.as_bytes() => {
318                self.cache.put(&self.key, self.owner.as_bytes(), Some(ttl)).await?;
319                Ok(true)
320            }
321            _ => Ok(false),
322        }
323    }
324
325    /// Give up the guard **without** releasing the lock, so it stands until the
326    /// TTL expires.
327    ///
328    /// Deliberate abandonment, not a leak — and distinct from dropping the
329    /// guard, which logs a warning on the assumption you forgot.
330    ///
331    /// The case it exists for is a claim that has to outlive the work: the
332    /// scheduler's `on_one_server` takes a lock for the current minute so the
333    /// *other* machines find it taken, and releasing it when the run finishes
334    /// would let a machine whose clock is a second behind claim the same
335    /// minute and run it again.
336    pub fn keep(mut self) {
337        self.released = true;
338    }
339
340    /// Whether we still hold it.
341    pub async fn is_still_held(&self) -> Result<bool> {
342        Ok(self.cache.get(&self.key).await?.as_deref() == Some(self.owner.as_bytes()))
343    }
344
345    /// The random token identifying this holder.
346    pub fn owner(&self) -> &str {
347        &self.owner
348    }
349
350    /// The cache key.
351    pub fn key(&self) -> &str {
352        &self.key
353    }
354}
355
356impl Drop for LockGuard {
357    fn drop(&mut self) {
358        if !self.released {
359            // Not an error — the TTL covers it — but it is nearly always a
360            // missing `release`, and the symptom otherwise is a task that
361            // mysteriously does not run for the next few minutes.
362            tracing::debug!(
363                key = %self.key,
364                "a lock guard was dropped without being released; it will expire on its TTL"
365            );
366        }
367    }
368}
369
370impl std::fmt::Debug for LockGuard {
371    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372        f.debug_struct("LockGuard").field("key", &self.key).finish()
373    }
374}
375
376/// A random token identifying one holder.
377///
378/// Two sources mixed, because either alone has a failure mode: a timestamp
379/// collides when two processes acquire in the same nanosecond, and a process id
380/// collides across machines. Together with the address of a fresh allocation
381/// they are enough — this identifies a holder, it does not authenticate one.
382fn mint_owner() -> String {
383    use std::collections::hash_map::RandomState;
384    use std::hash::{BuildHasher, Hasher};
385
386    // `RandomState` is seeded per process from the OS, and hashing a
387    // monotonically-changing value gives a different token per call.
388    let mut hasher = RandomState::new().build_hasher();
389    hasher.write_u128(
390        std::time::SystemTime::now()
391            .duration_since(std::time::UNIX_EPOCH)
392            .map(|d| d.as_nanos())
393            .unwrap_or_default(),
394    );
395    hasher.write_usize(&hasher as *const _ as usize);
396
397    format!("{:016x}{:016x}", hasher.finish(), std::process::id())
398}
399
400/// The error a caller gets when a lock is required rather than optional.
401pub fn contended(name: &str) -> Error {
402    Error::internal(format!("`{name}` is already running elsewhere"))
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use crate::MemoryCache;
409
410    fn locks() -> LockManager {
411        LockManager::new(Arc::new(MemoryCache::new()))
412    }
413
414    #[tokio::test]
415    async fn exactly_one_caller_gets_the_lock() {
416        let locks = locks();
417
418        let first = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap();
419        let second = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap();
420
421        assert!(first.is_some());
422        assert!(second.is_none());
423    }
424
425    #[tokio::test]
426    async fn releasing_lets_the_next_caller_in() {
427        let locks = locks();
428
429        let guard = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
430        assert!(guard.release().await.unwrap());
431
432        assert!(locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().is_some());
433    }
434
435    #[tokio::test]
436    async fn a_release_after_the_lock_moved_on_does_not_take_it_from_the_new_holder() {
437        // The bug the owner token exists for. A holder that overran has already
438        // lost the lock; its release must be a no-op, not a theft.
439        let locks = locks();
440        let cache = Arc::clone(locks.cache());
441
442        let stale = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
443
444        // Simulate the TTL passing and somebody else taking it.
445        cache.forget("lock:job").await.unwrap();
446        let fresh = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
447
448        // The stale holder releases. It must not remove the fresh holder's lock.
449        assert!(!stale.release().await.unwrap(), "the stale release should be a no-op");
450        assert!(fresh.is_still_held().await.unwrap(), "the new holder should still hold it");
451
452        // And a third caller must still be locked out.
453        assert!(locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().is_none());
454    }
455
456    #[tokio::test]
457    async fn two_holders_get_different_tokens() {
458        let locks = locks();
459
460        let first = locks.lock("a", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
461        let second = locks.lock("b", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
462
463        assert_ne!(first.owner(), second.owner());
464    }
465
466    #[tokio::test]
467    async fn an_expired_lock_is_available_again() {
468        let locks = locks();
469
470        let _held = locks.lock("job", Duration::from_millis(30)).acquire().await.unwrap().unwrap();
471        assert!(locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().is_none());
472
473        tokio::time::sleep(Duration::from_millis(60)).await;
474
475        assert!(
476            locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().is_some(),
477            "the TTL is what stops a dead holder locking a task out forever"
478        );
479    }
480
481    #[tokio::test]
482    async fn run_releases_on_success() {
483        let locks = locks();
484        let lock = locks.lock("job", Duration::from_secs(60));
485
486        assert_eq!(lock.run(async { Ok(7) }).await.unwrap(), Some(7));
487        assert!(!lock.is_held().await.unwrap());
488    }
489
490    #[tokio::test]
491    async fn run_releases_on_failure_too() {
492        // A task that errors must not hold its lock until the TTL: one bad run
493        // would skip every scheduled run until then.
494        let locks = locks();
495        let lock = locks.lock("job", Duration::from_secs(3600));
496
497        let outcome: Result<Option<()>> = lock.run(async { Err(Error::internal("boom")) }).await;
498
499        assert!(outcome.is_err());
500        assert!(!lock.is_held().await.unwrap(), "the lock should have been released");
501    }
502
503    #[tokio::test]
504    async fn run_skips_the_work_when_somebody_else_holds_it() {
505        use std::sync::atomic::{AtomicBool, Ordering};
506
507        let locks = locks();
508        let _held = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
509
510        let ran = AtomicBool::new(false);
511        let outcome = locks
512            .lock("job", Duration::from_secs(60))
513            .run(async {
514                ran.store(true, Ordering::SeqCst);
515                Ok(())
516            })
517            .await
518            .unwrap();
519
520        assert!(outcome.is_none());
521        assert!(!ran.load(Ordering::SeqCst), "the work must not run");
522    }
523
524    #[tokio::test]
525    async fn waiting_gets_the_lock_once_it_is_released() {
526        let locks = locks();
527        let guard = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
528
529        let cache = Arc::clone(locks.cache());
530        tokio::spawn(async move {
531            tokio::time::sleep(Duration::from_millis(50)).await;
532            guard.release().await.unwrap();
533            drop(cache);
534        });
535
536        let waited = locks
537            .lock("job", Duration::from_secs(60))
538            .wait_for(Duration::from_secs(2))
539            .acquire()
540            .await
541            .unwrap();
542
543        assert!(waited.is_some(), "waiting should have outlasted the holder");
544    }
545
546    #[tokio::test]
547    async fn waiting_gives_up_at_the_deadline() {
548        let locks = locks();
549        let _held = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
550
551        let started = std::time::Instant::now();
552        let waited = locks
553            .lock("job", Duration::from_secs(60))
554            .wait_for(Duration::from_millis(250))
555            .acquire()
556            .await
557            .unwrap();
558
559        assert!(waited.is_none());
560        assert!(started.elapsed() < Duration::from_secs(2), "it should not wait forever");
561    }
562
563    #[tokio::test]
564    async fn extending_keeps_a_long_job_from_losing_its_lock() {
565        let locks = locks();
566        let guard = locks.lock("job", Duration::from_millis(50)).acquire().await.unwrap().unwrap();
567
568        assert!(guard.extend(Duration::from_secs(60)).await.unwrap());
569
570        tokio::time::sleep(Duration::from_millis(80)).await;
571        assert!(
572            locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().is_none(),
573            "the original TTL would have expired by now"
574        );
575    }
576
577    #[tokio::test]
578    async fn extending_a_lock_that_moved_on_says_so() {
579        let locks = locks();
580        let guard = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
581
582        locks.lock("job", Duration::from_secs(60)).force_release().await.unwrap();
583        let _other = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
584
585        assert!(!guard.extend(Duration::from_secs(60)).await.unwrap());
586        assert!(!guard.is_still_held().await.unwrap());
587    }
588
589    #[tokio::test]
590    async fn keep_leaves_the_lock_standing_until_the_ttl() {
591        let locks = locks();
592
593        locks.lock("minute", Duration::from_millis(60)).acquire().await.unwrap().unwrap().keep();
594
595        assert!(
596            locks.lock("minute", Duration::from_secs(60)).acquire().await.unwrap().is_none(),
597            "the claim should still stand"
598        );
599
600        tokio::time::sleep(Duration::from_millis(90)).await;
601        assert!(
602            locks.lock("minute", Duration::from_secs(60)).acquire().await.unwrap().is_some(),
603            "and expire on its own"
604        );
605    }
606
607    #[tokio::test]
608    async fn a_memory_cache_is_not_a_shared_lock_and_admits_it() {
609        // The check worth making at boot: `on_one_server` over a per-process
610        // cache is every server believing it is the one.
611        assert!(!locks().is_shared());
612    }
613
614    #[tokio::test]
615    async fn different_names_do_not_contend() {
616        let locks = locks();
617
618        let a = locks.lock("a", Duration::from_secs(60)).acquire().await.unwrap();
619        let b = locks.lock("b", Duration::from_secs(60)).acquire().await.unwrap();
620
621        assert!(a.is_some() && b.is_some());
622    }
623
624    #[tokio::test]
625    async fn the_prefix_keeps_locks_out_of_the_caches_own_namespace() {
626        let locks = locks();
627        let guard = locks.lock("job", Duration::from_secs(60)).acquire().await.unwrap().unwrap();
628
629        assert_eq!(guard.key(), "lock:job");
630        assert!(Arc::clone(locks.cache()).has("lock:job").await.unwrap());
631        assert!(!Arc::clone(locks.cache()).has("job").await.unwrap());
632    }
633}