1use async_trait::async_trait;
4use fred::prelude::{
5 Builder, Client, ClientLike as _, Config, KeysInterface as _, LuaInterface as _,
6 SetsInterface as _,
7};
8use fred::types::Value;
9
10use crate::error::{KernelError, Result};
11use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
12
13const LAYOUT: i64 = 1;
15
16const MIGRATE_SCRIPT: &str = r"
19local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
20local mine = tonumber(ARGV[1])
21if stored > mine then return stored end
22if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
23return mine
24";
25
26const PUT_SCRIPT: &str = r"
28redis.call('SET', KEYS[1], ARGV[2])
29redis.call('ZADD', KEYS[2], 0, ARGV[1])
30return 1
31";
32
33const DELETE_SCRIPT: &str = r"
35local existed = redis.call('DEL', KEYS[1])
36redis.call('ZREM', KEYS[2], ARGV[1])
37return existed
38";
39
40const LIST_SCRIPT: &str = r"
42local out = {}
43for _, id in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
44 local record = redis.call('GET', ARGV[1] .. id)
45 if record then table.insert(out, record) end
46end
47return out
48";
49
50const RECORD_SCRIPT: &str = r"
52redis.call('SET', KEYS[1], ARGV[3])
53for i = 2, 4 do redis.call('ZADD', KEYS[i], ARGV[2], ARGV[1]) end
54return 1
55";
56
57const CROSSINGS_SCRIPT: &str = r"
60local out = {}
61for _, id in ipairs(redis.call('ZRANGEBYSCORE', KEYS[1], ARGV[2], '+inf')) do
62 local record = redis.call('GET', ARGV[1] .. id)
63 if record then table.insert(out, record) end
64end
65return out
66";
67
68const RELEASE_SCRIPT: &str = r"
70local held = redis.call('SCARD', KEYS[1])
71redis.call('DEL', KEYS[1])
72return held
73";
74
75#[derive(Debug, Clone)]
107pub struct RedisPartitionStore {
108 client: Client,
109 namespace: String,
110}
111
112impl RedisPartitionStore {
113 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
115
116 pub fn from_client(client: Client) -> Self {
118 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
119 }
120
121 pub async fn connect(url: &str) -> Result<Self> {
128 let config =
129 Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
130 let client = Builder::from_config(config)
131 .build()
132 .map_err(|error| store_error("build the Redis client", &error))?;
133 client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
134 Ok(Self::from_client(client))
135 }
136
137 #[must_use]
139 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
140 self.namespace = namespace.into();
141 self
142 }
143
144 pub fn client(&self) -> &Client {
146 &self.client
147 }
148
149 pub fn namespace(&self) -> &str {
151 &self.namespace
152 }
153
154 pub async fn migrate(&self) -> Result<()> {
160 let stored: i64 = self
161 .client
162 .eval(MIGRATE_SCRIPT, vec![self.key("partitions:layout")], vec![LAYOUT.to_string()])
163 .await
164 .map_err(|error| store_error("record the layout version", &error))?;
165 if stored > LAYOUT {
166 return Err(KernelError::Store {
167 backend: "redis",
168 reason: format!(
169 "the partition keys under {} have layout v{stored}, but this release \
170 knows up to v{LAYOUT}; upgrade ADK-Rust",
171 self.namespace
172 ),
173 });
174 }
175 Ok(())
176 }
177
178 fn key(&self, suffix: &str) -> String {
180 let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
181 format!("{{{namespace}}}:{suffix}")
182 }
183
184 async fn strings(
185 &self,
186 script: &str,
187 keys: Vec<String>,
188 args: Vec<String>,
189 ) -> Result<Vec<String>> {
190 let reply: Value = self
191 .client
192 .eval(script, keys, args)
193 .await
194 .map_err(|error| store_error("read the partition table", &error))?;
195 reply
196 .into_array()
197 .into_iter()
198 .map(|value| {
199 value
200 .into_string()
201 .ok_or_else(|| store_error("read the partition table", &"a record is not text"))
202 })
203 .collect()
204 }
205}
206
207fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
208 KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
209}
210
211fn corrupt(what: &str, error: &serde_json::Error) -> KernelError {
212 KernelError::Store { backend: "redis", reason: format!("a stored {what} is corrupt: {error}") }
213}
214
215#[async_trait]
216impl PartitionStore for RedisPartitionStore {
217 async fn put(&self, partition: Partition) -> Result<()> {
218 let record = serde_json::to_string(&partition)?;
219 let id = partition.id.as_str().to_string();
220 let keys = vec![self.key(&format!("partition:{id}")), self.key("partitions")];
221 self.client
222 .eval::<i64, _, _, _>(PUT_SCRIPT, keys, vec![id, record])
223 .await
224 .map_err(|error| store_error("write the partition table", &error))?;
225 Ok(())
226 }
227
228 async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
229 let record: Option<String> = self
230 .client
231 .get(self.key(&format!("partition:{id}")))
232 .await
233 .map_err(|error| store_error("read the partition table", &error))?;
234 record
235 .map(|record| serde_json::from_str(&record).map_err(|e| corrupt("partition", &e)))
236 .transpose()
237 }
238
239 async fn list(&self) -> Result<Vec<Partition>> {
240 let records = self
241 .strings(LIST_SCRIPT, vec![self.key("partitions")], vec![self.key("partition:")])
242 .await?;
243 records
244 .iter()
245 .map(|record| serde_json::from_str(record).map_err(|e| corrupt("partition", &e)))
246 .collect()
247 }
248
249 async fn delete(&self, id: &PartitionId) -> Result<bool> {
250 let keys = vec![self.key(&format!("partition:{id}")), self.key("partitions")];
251 let existed: i64 = self
252 .client
253 .eval(DELETE_SCRIPT, keys, vec![id.as_str().to_string()])
254 .await
255 .map_err(|error| store_error("delete from the partition table", &error))?;
256 Ok(existed > 0)
257 }
258
259 async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
260 let json = serde_json::to_string(&record)?;
261 let keys = vec![
262 self.key(&format!("crossing:{}", record.id)),
263 self.key("crossings"),
264 self.key(&format!("crossings:run:{}", record.run)),
265 self.key(&format!("crossings:from:{}", record.from)),
266 ];
267 let args = vec![record.id.clone(), record.at.timestamp_micros().to_string(), json];
268 self.client
269 .eval::<i64, _, _, _>(RECORD_SCRIPT, keys, args)
270 .await
271 .map_err(|error| store_error("record a crossing", &error))?;
272 Ok(())
273 }
274
275 async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
276 let walk = match (&filter.run, &filter.from) {
278 (Some(run), _) => self.key(&format!("crossings:run:{run}")),
279 (None, Some(from)) => self.key(&format!("crossings:from:{from}")),
280 (None, None) => self.key("crossings"),
281 };
282 let least = filter
283 .since
284 .map_or_else(|| "-inf".to_string(), |since| since.timestamp_micros().to_string());
285 let records =
286 self.strings(CROSSINGS_SCRIPT, vec![walk], vec![self.key("crossing:"), least]).await?;
287 let mut out = Vec::new();
288 for record in records {
289 let record: CrossingRecord =
290 serde_json::from_str(&record).map_err(|e| corrupt("crossing record", &e))?;
291 if filter.matches(&record) {
292 out.push(record);
293 }
294 if filter.limit.is_some_and(|limit| out.len() >= limit) {
295 break;
296 }
297 }
298 Ok(out)
299 }
300
301 async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
302 self.client
303 .sadd::<i64, _, _>(self.key(&format!("crossing-grants:{run}")), fingerprint)
304 .await
305 .map_err(|error| store_error("record a crossing grant", &error))?;
306 Ok(())
307 }
308
309 async fn grants(&self, run: &str) -> Result<Vec<String>> {
310 let mut grants: Vec<String> = self
311 .client
312 .smembers(self.key(&format!("crossing-grants:{run}")))
313 .await
314 .map_err(|error| store_error("read the crossing grants", &error))?;
315 grants.sort();
316 Ok(grants)
317 }
318
319 async fn release_run(&self, run: &str) -> Result<u64> {
320 let held: i64 = self
321 .client
322 .eval(
323 RELEASE_SCRIPT,
324 vec![self.key(&format!("crossing-grants:{run}"))],
325 Vec::<String>::new(),
326 )
327 .await
328 .map_err(|error| store_error("release the crossing grants", &error))?;
329 Ok(u64::try_from(held).unwrap_or(0))
330 }
331}