Skip to main content

ojak_redis/
breakers.rs

1//! Circuit breakers in Redis, as Stoplight keeps Mastodon's.
2
3use ojak::deliverer::{Admission, BreakerFuture, BreakerStore, CircuitBreaker, Probe};
4use redis::aio::ConnectionLike;
5use std::fmt;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9/// How long Stoplight keeps a light's metadata after it last changed.
10const TTL_SECS: u64 = 7 * 24 * 60 * 60;
11
12/// The script that releases a probe's lock only while it is still the one
13/// that took it, so that a lock that lapsed and was taken by another probe
14/// stays that probe's.
15const COMPARE_DELETE: &str = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
16
17/// How a probe's lock is released.
18#[derive(Clone, Debug, Default, Eq, PartialEq)]
19pub enum ProbeRelease {
20    /// With `EVAL` and the compare-and-delete script.
21    #[default]
22    Eval,
23    /// With `FCALL` of a function the operator installed, taking the key and
24    /// the lock's token and deleting the key only if it holds the token: for
25    /// a Redis user that may call it and may not send scripts of its own. A
26    /// call that fails falls back to [`ProbeRelease::Eval`].
27    Function(String),
28}
29
30/// A [`BreakerStore`] in Redis, which the deliverers of every process
31/// sharing it count their failures in, and let one probe through between, as
32/// Mastodon's Sidekiq processes share their Stoplights.
33///
34/// A breaker is three keys, after the prefix the application gives, for each
35/// destination its [`CircuitBreaker`] is kept for:
36/// `stoplight:<key>:failures`, the failures in a row while it is closed;
37/// `stoplight:<key>:recovery_after`, when an open breaker turns half-open,
38/// in milliseconds since the epoch; and `stoplight:<key>:probe`, the lock
39/// the probe through a half-open one holds, for at most the cool-off. Each
40/// lasts a week after it last changed, as Stoplight's metadata does.
41///
42/// A breaker Redis cannot be asked about lets the delivery through. A probe
43/// whose outcome is never recorded — its delivery was dropped mid-way —
44/// keeps its lock until the cool-off lapses, and the next delivery probes.
45///
46/// The commands sent are `GET`, `SET` (with `NX`, `PX` and `EX`), `DEL`,
47/// `INCRBY`, `EXPIRE`, and `EVAL` or `FCALL` as [`ProbeRelease`] says.
48#[derive(Clone)]
49pub struct RedisBreakers<C> {
50    connection: C,
51    prefix: String,
52    release: ProbeRelease,
53}
54
55impl<C> fmt::Debug for RedisBreakers<C> {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_struct("RedisBreakers")
58            .field("prefix", &self.prefix)
59            .field("release", &self.release)
60            .finish_non_exhaustive()
61    }
62}
63
64/// The lock a probe holds.
65struct ProbeLock {
66    key: String,
67    token: String,
68}
69
70impl<C> RedisBreakers<C> {
71    /// Breakers over `connection`, every key of which starts with `prefix`,
72    /// separator included: `"tenant-a:"`, or `""` for none.
73    pub fn new(connection: C, prefix: impl Into<String>) -> Self {
74        Self {
75            connection,
76            prefix: prefix.into(),
77            release: ProbeRelease::default(),
78        }
79    }
80
81    /// Release probes' locks as `release` says.
82    #[must_use]
83    pub fn release_with(mut self, release: ProbeRelease) -> Self {
84        self.release = release;
85        self
86    }
87
88    /// The Redis key `part` of the breaker for `key` is kept under.
89    #[must_use]
90    pub fn redis_key(&self, key: &str, part: &str) -> String {
91        format!("{}stoplight:{key}:{part}", self.prefix)
92    }
93}
94
95impl<C> RedisBreakers<C>
96where
97    C: ConnectionLike + Clone + Send + Sync + 'static,
98{
99    /// `Light#run`'s choice of strategy: closed (green) lets the delivery
100    /// through; open (red) holds it until the cool-off has passed; half-open
101    /// (yellow) lets it through as the probe if it takes the probe's lock,
102    /// which starts the count of failures again, and holds it otherwise.
103    pub async fn admit(&self, breaker: &CircuitBreaker, key: &str) -> Admission {
104        let mut connection = self.connection.clone();
105        let recovery_after: redis::RedisResult<Option<u64>> = redis::cmd("GET")
106            .arg(self.redis_key(key, "recovery_after"))
107            .query_async(&mut connection)
108            .await;
109        let Ok(Some(recovery_after)) = recovery_after else {
110            return Admission::Pass;
111        };
112        let now = now_millis();
113        if now < recovery_after {
114            return Admission::Held(Duration::from_millis(recovery_after - now));
115        }
116        let lock = ProbeLock {
117            key: self.redis_key(key, "probe"),
118            token: token(),
119        };
120        let taken: redis::RedisResult<Option<String>> = redis::cmd("SET")
121            .arg(&lock.key)
122            .arg(&lock.token)
123            .arg("NX")
124            .arg("PX")
125            .arg(millis(breaker.cool_off).max(1))
126            .query_async(&mut connection)
127            .await;
128        if !matches!(taken, Ok(Some(_))) {
129            return Admission::Held(breaker.cool_off);
130        }
131        // `YellowRunStrategy#enter_recovery`: `metrics_store.clear`.
132        let _: redis::RedisResult<()> = redis::cmd("DEL")
133            .arg(self.redis_key(key, "failures"))
134            .query_async(&mut connection)
135            .await;
136        Admission::Probe(Probe::new(lock))
137    }
138
139    /// `Tracker::Request` for a delivery let through closed, and
140    /// `Tracker::RecoveryProbe` for the probe, whose lock is released after.
141    ///
142    /// # Errors
143    ///
144    /// When Redis cannot be reached.
145    pub async fn record(
146        &self,
147        breaker: &CircuitBreaker,
148        key: &str,
149        failed: bool,
150        probe: Option<Probe>,
151    ) -> redis::RedisResult<()> {
152        let mut connection = self.connection.clone();
153        let failures = self.redis_key(key, "failures");
154        let recovery = self.redis_key(key, "recovery_after");
155        let reopen = || {
156            let mut command = redis::cmd("SET");
157            command
158                .arg(&recovery)
159                .arg(now_millis().saturating_add(millis(breaker.cool_off)))
160                .arg("EX")
161                .arg(TTL_SECS);
162            command
163        };
164        let recorded = match (probe.is_some(), failed) {
165            // The probe failed: red for another cool-off.
166            (true, true) => reopen().query_async(&mut connection).await,
167            // The probe succeeded: green.
168            (true, false) => {
169                redis::cmd("DEL")
170                    .arg(&recovery)
171                    .query_async(&mut connection)
172                    .await
173            }
174            // A success starts the count of failures again, and only that.
175            (false, false) => {
176                redis::pipe()
177                    .cmd("DEL")
178                    .arg(&failures)
179                    .ignore()
180                    .cmd("EXPIRE")
181                    .arg(&recovery)
182                    .arg(TTL_SECS)
183                    .ignore()
184                    .query_async(&mut connection)
185                    .await
186            }
187            (false, true) => {
188                let counted: redis::RedisResult<(u32,)> = redis::pipe()
189                    .cmd("INCRBY")
190                    .arg(&failures)
191                    .arg(1)
192                    .cmd("EXPIRE")
193                    .arg(&failures)
194                    .arg(TTL_SECS)
195                    .ignore()
196                    .query_async(&mut connection)
197                    .await;
198                match counted {
199                    Ok((count,)) if count >= breaker.threshold.max(1) => {
200                        reopen().query_async(&mut connection).await
201                    }
202                    Ok(_) => Ok(()),
203                    Err(error) => Err(error),
204                }
205            }
206        };
207        if let Some(lock) = probe
208            .as_ref()
209            .and_then(|probe| probe.guard().downcast_ref::<ProbeLock>())
210        {
211            self.release(lock).await;
212        }
213        recorded
214    }
215
216    async fn release(&self, lock: &ProbeLock) {
217        let mut connection = self.connection.clone();
218        if let ProbeRelease::Function(function) = &self.release {
219            let released: redis::RedisResult<i64> = redis::cmd("FCALL")
220                .arg(function)
221                .arg(1)
222                .arg(&lock.key)
223                .arg(&lock.token)
224                .query_async(&mut connection)
225                .await;
226            if released.is_ok() {
227                return;
228            }
229        }
230        let _: redis::RedisResult<i64> = redis::cmd("EVAL")
231            .arg(COMPARE_DELETE)
232            .arg(1)
233            .arg(&lock.key)
234            .arg(&lock.token)
235            .query_async(&mut connection)
236            .await;
237    }
238}
239
240impl<C> BreakerStore for RedisBreakers<C>
241where
242    C: ConnectionLike + Clone + Send + Sync + 'static,
243{
244    fn admit<'a>(
245        &'a self,
246        breaker: &'a CircuitBreaker,
247        key: &'a str,
248    ) -> BreakerFuture<'a, Admission> {
249        Box::pin(RedisBreakers::admit(self, breaker, key))
250    }
251
252    fn record<'a>(
253        &'a self,
254        breaker: &'a CircuitBreaker,
255        key: &'a str,
256        failed: bool,
257        probe: Option<Probe>,
258    ) -> BreakerFuture<'a, ()> {
259        Box::pin(async move {
260            let _ = RedisBreakers::record(self, breaker, key, failed, probe).await;
261        })
262    }
263}
264
265fn millis(duration: Duration) -> u64 {
266    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
267}
268
269fn now_millis() -> u64 {
270    SystemTime::now()
271        .duration_since(UNIX_EPOCH)
272        .map_or(0, millis)
273}
274
275/// A token no other lock holds: this process, the time, and a count.
276fn token() -> String {
277    static COUNT: AtomicU64 = AtomicU64::new(0);
278    let nanos = SystemTime::now()
279        .duration_since(UNIX_EPOCH)
280        .map_or(0, |since| since.as_nanos());
281    format!(
282        "{}-{nanos}-{}",
283        std::process::id(),
284        COUNT.fetch_add(1, Ordering::Relaxed)
285    )
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[test]
293    fn a_breakers_keys_are_stoplights_after_the_prefix() {
294        let breakers = RedisBreakers::new((), "tenant-a:");
295        assert_eq!(
296            breakers.redis_key("https://b.example/inbox", "failures"),
297            "tenant-a:stoplight:https://b.example/inbox:failures"
298        );
299        assert_eq!(
300            RedisBreakers::new((), "").redis_key("k", "recovery_after"),
301            "stoplight:k:recovery_after"
302        );
303    }
304
305    #[test]
306    fn tokens_differ() {
307        assert_ne!(token(), token());
308    }
309}