1mod 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#[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 pub fn new(connection: C, prefix: impl Into<String>) -> Self {
62 Self {
63 connection,
64 prefix: prefix.into(),
65 }
66 }
67
68 #[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
90fn milliseconds(ttl: Duration) -> u64 {
93 u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1)
94}
95
96fn 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 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}