Skip to main content

ojak_redis/
lib.rs

1//! A Redis backend for Ojak's key-value store, [`RedisKvStore`].
2//!
3//! What Ojak keeps in its store — the IDs of activities already processed
4//! and forwarded, remote keys, fetched JSON-LD contexts — is then shared by
5//! every process using the same Redis, as a Mastodon server's Redis is shared
6//! by its web and Sidekiq processes: an activity two processes receive at
7//! once is processed by one of them.
8//!
9//! A key is its segments joined by `:`, after a prefix the application
10//! gives, the way Redis keys are conventionally named, so that
11//! `["jsonld", "context", iri]` is `jsonld:context:<iri>`, the key Mastodon
12//! names that cache entry by. The prefix is put before the key as it is: an
13//! application sharing one Redis between several instances gives each its own
14//! prefix, such as `"tenant-a:"`, and each a Redis user whose ACL reaches only
15//! keys under it (`~tenant-a:*`). Joining is not escaped, so two keys whose
16//! segments join to one string are one key; Ojak's own keys never contain `:`
17//! but in their last segment, which is what keeps them apart.
18//!
19//! A value is stored as its JSON text, and a TTL as Redis's own expiry, so
20//! an expired entry is gone without anything sweeping it. The commands sent
21//! are `GET`, `SET` (with `PX` and `NX`) and `DEL`, which is all a Redis user
22//! for this store needs to be granted.
23//!
24//! The deliverer's circuit breakers can be kept here too, with
25//! [`RedisBreakers`], under the same kind of prefix, so that every process
26//! delivering for an application counts the same failures.
27
28mod breakers;
29
30pub use breakers::{ProbeRelease, RedisBreakers};
31
32use ojak::kv::{KvError, KvStore};
33use redis::aio::ConnectionLike;
34use serde_json::Value;
35use std::fmt;
36use std::time::Duration;
37
38/// A [`KvStore`] in Redis.
39///
40/// `C` is the connection the commands go over: a
41/// `redis::aio::ConnectionManager`, which reconnects by itself, or a
42/// `redis::aio::MultiplexedConnection`. It is cloned for each command, which
43/// for both is a handle on one shared connection.
44#[derive(Clone)]
45pub struct RedisKvStore<C> {
46    connection: C,
47    prefix: String,
48}
49
50impl<C> fmt::Debug for RedisKvStore<C> {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.debug_struct("RedisKvStore")
53            .field("prefix", &self.prefix)
54            .finish_non_exhaustive()
55    }
56}
57
58impl<C> RedisKvStore<C> {
59    /// A store over `connection`, every key of which starts with `prefix`,
60    /// separator included: `"tenant-a:"`, or `""` for none.
61    pub fn new(connection: C, prefix: impl Into<String>) -> Self {
62        Self {
63            connection,
64            prefix: prefix.into(),
65        }
66    }
67
68    /// The Redis key `key` is stored under.
69    #[must_use]
70    pub fn redis_key(&self, key: &[&str]) -> String {
71        let mut joined = self.prefix.clone();
72        for (n, segment) in key.iter().enumerate() {
73            if n > 0 {
74                joined.push(':');
75            }
76            joined.push_str(segment);
77        }
78        joined
79    }
80}
81
82fn error(error: redis::RedisError) -> KvError {
83    KvError(error.to_string())
84}
85
86fn encode(value: &Value) -> Result<String, KvError> {
87    serde_json::to_string(value).map_err(|error| KvError(error.to_string()))
88}
89
90/// A TTL in Redis's milliseconds, at least one: `PX 0` is an error, and an
91/// entry asked to last less than a millisecond lasts one.
92fn milliseconds(ttl: Duration) -> u64 {
93    u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1)
94}
95
96/// `SET key value [NX] [PX ttl]`.
97fn set_command(key: String, value: String, ttl: Option<Duration>, only_new: bool) -> redis::Cmd {
98    let mut command = redis::cmd("SET");
99    command.arg(key).arg(value);
100    if only_new {
101        command.arg("NX");
102    }
103    if let Some(ttl) = ttl {
104        command.arg("PX").arg(milliseconds(ttl));
105    }
106    command
107}
108
109impl<C> KvStore for RedisKvStore<C>
110where
111    C: ConnectionLike + Clone + Send + Sync + 'static,
112{
113    async fn get(&self, key: &[&str]) -> Result<Option<Value>, KvError> {
114        let mut connection = self.connection.clone();
115        let text: Option<String> = redis::cmd("GET")
116            .arg(self.redis_key(key))
117            .query_async(&mut connection)
118            .await
119            .map_err(error)?;
120        text.map(|text| serde_json::from_str(&text).map_err(|error| KvError(error.to_string())))
121            .transpose()
122    }
123
124    async fn set(&self, key: &[&str], value: Value, ttl: Option<Duration>) -> Result<(), KvError> {
125        let mut connection = self.connection.clone();
126        set_command(self.redis_key(key), encode(&value)?, ttl, false)
127            .query_async::<()>(&mut connection)
128            .await
129            .map_err(error)
130    }
131
132    async fn insert(
133        &self,
134        key: &[&str],
135        value: Value,
136        ttl: Option<Duration>,
137    ) -> Result<bool, KvError> {
138        // `SET … NX` is one command, so of any number at once, from any
139        // number of processes, exactly one puts, and Redis answers it `OK`.
140        let mut connection = self.connection.clone();
141        let put: Option<String> = set_command(self.redis_key(key), encode(&value)?, ttl, true)
142            .query_async(&mut connection)
143            .await
144            .map_err(error)?;
145        Ok(put.is_some())
146    }
147
148    async fn delete(&self, key: &[&str]) -> Result<(), KvError> {
149        let mut connection = self.connection.clone();
150        redis::cmd("DEL")
151            .arg(self.redis_key(key))
152            .query_async::<()>(&mut connection)
153            .await
154            .map_err(error)
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn a_key_is_its_segments_after_the_prefix() {
164        let store = RedisKvStore::new((), "tenant-a:");
165        assert_eq!(
166            store.redis_key(&["jsonld", "context", "https://a.example/ns"]),
167            "tenant-a:jsonld:context:https://a.example/ns"
168        );
169        let unprefixed = RedisKvStore::new((), "");
170        assert_eq!(unprefixed.redis_key(&["ojak", "key", "k"]), "ojak:key:k");
171        assert_eq!(unprefixed.redis_key(&["a", "b", ""]), "a:b:");
172    }
173
174    #[test]
175    fn a_ttl_is_at_least_a_millisecond() {
176        assert_eq!(milliseconds(Duration::from_secs(30)), 30_000);
177        assert_eq!(milliseconds(Duration::from_micros(10)), 1);
178    }
179}