1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
//! Locks, so one thing happens at a time for a key, across every process
//! that shares the cache, as Laravel's `Cache::lock` and Rails'
//! `with_advisory_lock`:
//!
//! ```glacier
//! lock "import:#{feed.id}", wait: 5.seconds() do
//! Importer.run(feed)!
//! end
//! ```
//!
//! The lock is a cache key ([`cache::add`](crate::cache::add)), held until
//! the body finishes, or until `ttl` passes if the process dies holding
//! it. With `[cache] store = "database"` it's shared by every server; with
//! the memory store, by one process.
use std::future::Future;
use chrono::TimeDelta;
use crate::error::{Error, Result};
use crate::jobs::Delay;
/// How long a lock is held at most, unless `ttl` says otherwise.
const DEFAULT_TTL: TimeDelta = TimeDelta::minutes(1);
/// How often a waiting caller tries again.
const POLL: std::time::Duration = std::time::Duration::from_millis(100);
/// A lock on a key; see the [module docs](self).
#[must_use = "a lock does nothing until `run`"]
pub struct Lock {
key: String,
wait: TimeDelta,
ttl: TimeDelta,
/// How many may hold it at once: 1 for a lock, more for a funnel.
limit: usize,
}
impl Lock {
/// A lock on `key`, not waiting for it, held for a minute at most.
pub fn new(key: impl Into<String>) -> Self {
Self {
key: key.into(),
wait: TimeDelta::zero(),
ttl: DEFAULT_TTL,
limit: 1,
}
}
/// Waits up to `wait` for another holder to finish, rather than
/// failing at once.
pub fn wait(mut self, wait: impl Delay) -> Self {
self.wait = wait.delay();
self
}
/// Lets up to `limit` callers hold it at once, as Laravel's
/// `Redis::funnel`: `funnel "openai", limit: 3 do … end` in
/// `.glacier`, for a service that takes only so many requests at a
/// time.
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit.max(1);
self
}
/// The longest the lock is held: past it, another caller can take it,
/// in case this one's process died. Longer than the work takes.
pub fn ttl(mut self, ttl: impl Delay) -> Self {
self.ttl = ttl.delay();
self
}
/// Runs `work` holding the lock, and lets it go after.
///
/// # Errors
///
/// `409 Conflict` when another caller still holds the lock after
/// `wait`; `work`'s own error; or the cache's.
pub async fn run<T, F: Future<Output = Result<T>>>(self, work: F) -> Result<T> {
// One key per place: `lock:x` for a lock, `lock:x:0`… for a funnel.
let slots: Vec<String> = if self.limit == 1 {
vec![format!("glacier:lock:{}", self.key)]
} else {
(0..self.limit)
.map(|slot| format!("glacier:lock:{}:{slot}", self.key))
.collect()
};
let token = crate::random::token();
let started = std::time::Instant::now();
let wait = self.wait.to_std().unwrap_or_default();
let key = 'taken: loop {
for key in &slots {
if crate::cache::add(key, &token, self.ttl).await? {
break 'taken key.clone();
}
}
if started.elapsed() >= wait {
return Err(Error::new(
http::StatusCode::CONFLICT,
format!("`{}` is locked", self.key),
));
}
tokio::time::sleep(POLL.min(wait.saturating_sub(started.elapsed()))).await;
};
let result = work.await;
// Only this holder's lock: past its ttl another may hold it now.
crate::cache::delete_if(&key, &token).await?;
result
}
/// Whether someone holds the lock on `key` now.
///
/// # Errors
///
/// When the cache can't be read.
pub async fn held(key: &str) -> Result<bool> {
Ok(crate::cache::read::<String>(&format!("glacier:lock:{key}"))
.await?
.is_some())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn one_holder_at_a_time() {
crate::cache::with_test_store(async {
let inside = Lock::new("import:1")
.run(async {
assert!(Lock::held("import:1").await.unwrap());
// Another caller can't take it, and says why.
let other = Lock::new("import:1").run(async { Ok(()) }).await;
assert_eq!(other.unwrap_err().status(), http::StatusCode::CONFLICT);
// A different key is a different lock.
Lock::new("import:2").run(async { Ok(()) }).await.unwrap();
Ok(7)
})
.await
.unwrap();
assert_eq!(inside, 7);
assert!(!Lock::held("import:1").await.unwrap(), "let go after");
// The body's error comes out, and the lock is let go.
let failed: Result<()> = Lock::new("import:1")
.run(async { Err(Error::internal("no")) })
.await;
assert!(failed.is_err());
assert!(!Lock::held("import:1").await.unwrap());
})
.await;
}
#[tokio::test]
async fn a_funnel_lets_some_through_at_once() {
crate::cache::with_test_store(async {
let inside = Lock::new("api").limit(2).run(async {
Lock::new("api")
.limit(2)
.run(async {
// Two hold it; a third waits in vain.
let third = Lock::new("api").limit(2).run(async { Ok(()) }).await;
assert_eq!(third.unwrap_err().status(), http::StatusCode::CONFLICT);
Ok(())
})
.await?;
Ok(1)
});
assert_eq!(inside.await.unwrap(), 1);
Lock::new("api")
.limit(2)
.run(async { Ok(()) })
.await
.unwrap();
})
.await;
}
#[tokio::test]
async fn waiting_callers_take_it_in_turn() {
crate::cache::with_test_store(async {
let first = Lock::new("report").run(async {
tokio::time::sleep(std::time::Duration::from_millis(150)).await;
Ok(1)
});
let second = async {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
Lock::new("report")
.wait(std::time::Duration::from_secs(2))
.run(async { Ok(2) })
.await
};
let (a, b) = tokio::join!(first, second);
assert_eq!((a.unwrap(), b.unwrap()), (1, 2));
})
.await;
}
}