1use std::collections::HashMap;
4
5use async_trait::async_trait;
6use chrono::{Datelike as _, NaiveDate};
7use fred::prelude::{
8 Builder, Client, ClientLike as _, Config, HashesInterface as _, LuaInterface as _,
9};
10use fred::types::Value;
11
12use super::{ProcessFilter, ProcessStore, SpendScope, UsageTotals, counters, stored_amount};
13use crate::bus::SpendDelta;
14use crate::error::{KernelError, Result};
15use crate::partition::PartitionId;
16use crate::process::ProcessMeta;
17use crate::sched::QueueClass;
18use crate::wake::WakeSet;
19
20const LAYOUT: i64 = 1;
22
23const MIGRATE_SCRIPT: &str = r"
26local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
27local mine = tonumber(ARGV[1])
28if stored > mine then return stored end
29if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
30return mine
31";
32
33const PUT_SCRIPT: &str = r"
36local row, pid = KEYS[1], ARGV[1]
37local old = redis.call('HMGET', row, 'idx_partition', 'idx_queue', 'idx_parent', 'idx_suspend')
38for i = 1, 4 do if old[i] then redis.call('ZREM', old[i], pid) end end
39redis.call('DEL', row)
40redis.call('HSET', row, unpack(ARGV, 2))
41local new = redis.call('HMGET', row, 'idx_partition', 'idx_queue', 'idx_parent', 'idx_suspend')
42for i = 1, 4 do if new[i] then redis.call('ZADD', new[i], 0, pid) end end
43redis.call('ZADD', KEYS[2], 0, pid)
44return 1
45";
46
47const SET_WAKE_SCRIPT: &str = r"
50if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
51if ARGV[1] == '1' then
52 redis.call('HSET', KEYS[1], 'wake', ARGV[2])
53else
54 redis.call('HDEL', KEYS[1], 'wake')
55end
56return 1
57";
58
59const SET_QUEUE_SCRIPT: &str = r"
62if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
63local old = redis.call('HGET', KEYS[1], 'idx_queue')
64if old then redis.call('ZREM', old, ARGV[1]) end
65redis.call('HSET', KEYS[1], 'queue', ARGV[2], 'idx_queue', ARGV[3])
66redis.call('ZADD', ARGV[3], 0, ARGV[1])
67return 1
68";
69
70const SET_SUSPEND_SCRIPT: &str = r"
73if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
74redis.call('HSET', KEYS[1], 'suspend_requested', ARGV[2])
75if ARGV[2] == '1' then
76 redis.call('HSET', KEYS[1], 'idx_suspend', KEYS[2])
77 redis.call('ZADD', KEYS[2], 0, ARGV[1])
78else
79 redis.call('HDEL', KEYS[1], 'idx_suspend')
80 redis.call('ZREM', KEYS[2], ARGV[1])
81end
82return 1
83";
84
85const DELETE_SCRIPT: &str = r"
87if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
88local old = redis.call('HMGET', KEYS[1], 'idx_partition', 'idx_queue', 'idx_parent', 'idx_suspend')
89for i = 1, 4 do if old[i] then redis.call('ZREM', old[i], ARGV[1]) end end
90redis.call('DEL', KEYS[1])
91redis.call('ZREM', KEYS[2], ARGV[1])
92return 1
93";
94
95const LIST_SCRIPT: &str = r"
100local limit = tonumber(ARGV[6])
101local out = {}
102for _, pid in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
103 if limit >= 0 and #out >= limit then break end
104 local row = ARGV[1] .. pid
105 local idx = redis.call('HMGET', row, 'idx_partition', 'idx_queue', 'idx_parent', 'suspend_requested')
106 if (ARGV[2] == '' or idx[1] == ARGV[2])
107 and (ARGV[3] == '' or idx[2] == ARGV[3])
108 and (ARGV[4] == '' or idx[3] == ARGV[4])
109 and (ARGV[5] == '' or (idx[4] or '0') == ARGV[5]) then
110 local fields = redis.call('HGETALL', row)
111 if #fields > 0 then table.insert(out, fields) end
112 end
113end
114return out
115";
116
117const ADD_SPEND_SCRIPT: &str = r"
120redis.call('HINCRBY', KEYS[1], ARGV[1], ARGV[2])
121redis.call('HINCRBY', KEYS[2], ARGV[1], ARGV[2])
122for i = 3, #ARGV, 2 do
123 local field = ARGV[1] .. ':' .. ARGV[i]
124 redis.call('HINCRBY', KEYS[3], field, ARGV[i + 1])
125 redis.call('HINCRBY', KEYS[4], field, ARGV[i + 1])
126end
127return 1
128";
129
130#[derive(Debug, Clone)]
169pub struct RedisProcessStore {
170 client: Client,
171 namespace: String,
172}
173
174impl RedisProcessStore {
175 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
177
178 pub fn from_client(client: Client) -> Self {
180 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
181 }
182
183 pub async fn connect(url: &str) -> Result<Self> {
190 let config =
191 Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
192 let client = Builder::from_config(config)
193 .build()
194 .map_err(|error| store_error("build the Redis client", &error))?;
195 client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
196 Ok(Self::from_client(client))
197 }
198
199 #[must_use]
202 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
203 self.namespace = namespace.into();
204 self
205 }
206
207 pub fn client(&self) -> &Client {
209 &self.client
210 }
211
212 pub fn namespace(&self) -> &str {
214 &self.namespace
215 }
216
217 pub async fn migrate(&self) -> Result<()> {
223 let stored: i64 = self
224 .client
225 .eval(MIGRATE_SCRIPT, vec![self.key("layout")], vec![LAYOUT.to_string()])
226 .await
227 .map_err(|error| store_error("record the layout version", &error))?;
228 if stored > LAYOUT {
229 return Err(KernelError::Store {
230 backend: "redis",
231 reason: format!(
232 "the keys under {} have layout v{stored}, but this release knows up to \
233 v{LAYOUT}; upgrade ADK-Rust",
234 self.namespace
235 ),
236 });
237 }
238 Ok(())
239 }
240
241 fn key(&self, suffix: &str) -> String {
243 let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
244 format!("{{{namespace}}}:{suffix}")
245 }
246
247 fn row_key(&self, pid: &str) -> String {
248 self.key(&format!("process:{pid}"))
249 }
250
251 fn index_key(&self, index: &str, value: &str) -> String {
252 self.key(&format!("processes:{index}:{value}"))
253 }
254
255 async fn eval(&self, script: &str, keys: Vec<String>, args: Vec<String>) -> Result<i64> {
256 self.client
257 .eval(script, keys, args)
258 .await
259 .map_err(|error| store_error("write the process table", &error))
260 }
261}
262
263const SUSPEND_INDEX: &str = "processes:suspend_requested";
265
266fn flag(set: bool) -> &'static str {
268 if set { "1" } else { "0" }
269}
270
271fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
272 KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
273}
274
275fn decode(mut fields: HashMap<String, String>) -> Result<ProcessMeta> {
277 let pid = fields
278 .remove("pid")
279 .ok_or_else(|| store_error("read a process row", &"the row has no `pid` field"))?;
280 let mut required = |field: &str| {
281 fields.remove(field).ok_or_else(|| KernelError::Store {
282 backend: "redis",
283 reason: format!("the row of process {pid} has no `{field}` field"),
284 })
285 };
286 let partition = required("partition")?;
287 let queue = required("queue")?;
288 let kind = required("kind")?;
289 let labels = required("labels")?;
290 let corrupt = |field: &str, error: serde_json::Error| KernelError::Store {
291 backend: "redis",
292 reason: format!("field `{field}` of process {pid} is corrupt: {error}"),
293 };
294 let kind = serde_json::from_str(&kind).map_err(|e| corrupt("kind", e))?;
295 let labels = serde_json::from_str(&labels).map_err(|e| corrupt("labels", e))?;
296 let wake = fields
297 .remove("wake")
298 .map(|wake| serde_json::from_str(&wake))
299 .transpose()
300 .map_err(|e| corrupt("wake", e))?;
301 let suspended_by = fields
302 .remove("suspended_by")
303 .map(|suspension| serde_json::from_str(&suspension))
304 .transpose()
305 .map_err(|e| corrupt("suspended_by", e))?;
306 let suspend_requested = fields.remove("suspend_requested").as_deref() == Some("1");
307 Ok(ProcessMeta {
308 parent: fields.remove("parent"),
309 partition: PartitionId::new(partition),
310 queue: QueueClass::from_name(&queue),
311 kind,
312 wake,
313 suspended_by,
314 suspend_requested,
315 agenda_item: fields.remove("agenda_item"),
316 labels,
317 pid,
318 })
319}
320
321fn reply_fields(row: Value) -> Result<HashMap<String, String>> {
323 let items = row.into_array();
324 let mut fields = HashMap::with_capacity(items.len() / 2);
325 let mut items = items.into_iter();
326 while let (Some(field), Some(value)) = (items.next(), items.next()) {
327 match (field.into_string(), value.into_string()) {
328 (Some(field), Some(value)) => {
329 fields.insert(field, value);
330 }
331 _ => return Err(store_error("list processes", &"a row field is not text")),
332 }
333 }
334 Ok(fields)
335}
336
337#[async_trait]
338impl ProcessStore for RedisProcessStore {
339 async fn put(&self, meta: ProcessMeta) -> Result<()> {
340 let mut args = vec![meta.pid.clone()];
341 let mut field = |name: &str, value: String| {
342 args.push(name.to_string());
343 args.push(value);
344 };
345 field("pid", meta.pid.clone());
346 field("partition", meta.partition.as_str().to_string());
347 field("idx_partition", self.index_key("partition", meta.partition.as_str()));
348 field("queue", meta.queue.as_str().to_string());
349 field("idx_queue", self.index_key("queue", meta.queue.as_str()));
350 field("kind", serde_json::to_string(&meta.kind)?);
351 field("labels", serde_json::to_string(&meta.labels)?);
352 field("suspend_requested", flag(meta.suspend_requested).to_string());
353 if meta.suspend_requested {
354 field("idx_suspend", self.key(SUSPEND_INDEX));
355 }
356 if let Some(parent) = &meta.parent {
357 field("parent", parent.clone());
358 field("idx_parent", self.index_key("parent", parent));
359 }
360 if let Some(wake) = &meta.wake {
361 field("wake", serde_json::to_string(wake)?);
362 }
363 if let Some(suspension) = &meta.suspended_by {
364 field("suspended_by", serde_json::to_string(suspension)?);
365 }
366 if let Some(item) = &meta.agenda_item {
367 field("agenda_item", item.clone());
368 }
369 self.eval(PUT_SCRIPT, vec![self.row_key(&meta.pid), self.key("processes")], args).await?;
370 Ok(())
371 }
372
373 async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
374 let fields: HashMap<String, String> = self
375 .client
376 .hgetall(self.row_key(pid))
377 .await
378 .map_err(|error| store_error("read the process table", &error))?;
379 if fields.is_empty() {
380 return Ok(None);
381 }
382 decode(fields).map(Some)
383 }
384
385 async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
386 let partition = filter
387 .partition
388 .as_ref()
389 .map(|partition| self.index_key("partition", partition.as_str()));
390 let queue = filter.queue.as_ref().map(|queue| self.index_key("queue", queue.as_str()));
391 let parent = filter.parent.as_ref().map(|parent| self.index_key("parent", parent));
392 let walk = (filter.suspend_requested == Some(true))
394 .then(|| self.key(SUSPEND_INDEX))
395 .or_else(|| parent.clone())
396 .or_else(|| partition.clone())
397 .or_else(|| queue.clone())
398 .unwrap_or_else(|| self.key("processes"));
399 let limit = filter.limit.map_or(-1, |limit| i64::try_from(limit).unwrap_or(i64::MAX));
400 let reply: Value = self
401 .client
402 .eval(
403 LIST_SCRIPT,
404 vec![walk],
405 vec![
406 self.row_key(""),
407 partition.unwrap_or_default(),
408 queue.unwrap_or_default(),
409 parent.unwrap_or_default(),
410 filter.suspend_requested.map(flag).unwrap_or_default().to_string(),
411 limit.to_string(),
412 ],
413 )
414 .await
415 .map_err(|error| store_error("list processes", &error))?;
416 reply.into_array().into_iter().map(|row| decode(reply_fields(row)?)).collect()
417 }
418
419 async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
420 let args = match &wake {
421 Some(wake) => vec!["1".to_string(), serde_json::to_string(wake)?],
422 None => vec!["0".to_string(), String::new()],
423 };
424 if self.eval(SET_WAKE_SCRIPT, vec![self.row_key(pid)], args).await? == 0 {
425 return Err(KernelError::NotFound { pid: pid.into() });
426 }
427 Ok(())
428 }
429
430 async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
431 let args = vec![
432 pid.to_string(),
433 queue.as_str().to_string(),
434 self.index_key("queue", queue.as_str()),
435 ];
436 if self.eval(SET_QUEUE_SCRIPT, vec![self.row_key(pid)], args).await? == 0 {
437 return Err(KernelError::NotFound { pid: pid.into() });
438 }
439 Ok(())
440 }
441
442 async fn delete(&self, pid: &str) -> Result<bool> {
443 let keys = vec![self.row_key(pid), self.key("processes")];
444 Ok(self.eval(DELETE_SCRIPT, keys, vec![pid.to_string()]).await? == 1)
445 }
446
447 async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
448 let keys = vec![self.row_key(pid), self.key(SUSPEND_INDEX)];
449 let args = vec![pid.to_string(), flag(requested).to_string()];
450 if self.eval(SET_SUSPEND_SCRIPT, keys, args).await? == 0 {
451 return Err(KernelError::NotFound { pid: pid.into() });
452 }
453 Ok(())
454 }
455
456 async fn add_spend(
457 &self,
458 pid: &str,
459 partition: &PartitionId,
460 day: NaiveDate,
461 delta: SpendDelta,
462 ) -> Result<()> {
463 let micro_usd = i64::try_from(delta.micro_usd).map_err(|_| KernelError::Store {
464 backend: "redis",
465 reason: format!(
466 "a spend delta of {} micro-USD exceeds a Redis integer",
467 delta.micro_usd
468 ),
469 })?;
470 let keys = vec![
471 self.key(&format!("spend:process:{pid}")),
472 self.key(&format!("spend:partition:{partition}")),
473 self.key(&format!("usage:process:{pid}")),
474 self.key(&format!("usage:partition:{partition}")),
475 ];
476 let mut args = vec![day.num_days_from_ce().to_string(), micro_usd.to_string()];
477 for (name, amount) in counters(&delta) {
478 args.push(name.to_string());
479 args.push(stored_amount("redis", name, amount)?.to_string());
480 }
481 self.client
482 .eval::<i64, _, _, _>(ADD_SPEND_SCRIPT, keys, args)
483 .await
484 .map_err(|error| store_error("add to the spend totals", &error))?;
485 Ok(())
486 }
487
488 async fn spend(
489 &self,
490 scope: &SpendScope,
491 from: NaiveDate,
492 to_inclusive: NaiveDate,
493 ) -> Result<u64> {
494 let key = match scope {
495 SpendScope::Process(pid) => self.key(&format!("spend:process:{pid}")),
496 SpendScope::Partition(partition) => self.key(&format!("spend:partition:{partition}")),
497 };
498 let days: HashMap<String, String> = self
499 .client
500 .hgetall(key)
501 .await
502 .map_err(|error| store_error("read the spend totals", &error))?;
503 let range = from.num_days_from_ce()..=to_inclusive.num_days_from_ce();
504 let mut total = 0_u64;
505 for (day, micro_usd) in days {
506 let (Ok(number), Ok(amount)) = (day.parse::<i32>(), micro_usd.parse::<u64>()) else {
507 return Err(store_error(
508 "read the spend totals",
509 &format!("the day total {day} = {micro_usd} is corrupt"),
510 ));
511 };
512 if range.contains(&number) {
513 total = total.saturating_add(amount);
514 }
515 }
516 Ok(total)
517 }
518
519 async fn usage(
520 &self,
521 scope: &SpendScope,
522 from: NaiveDate,
523 to_inclusive: NaiveDate,
524 ) -> Result<UsageTotals> {
525 let key = match scope {
526 SpendScope::Process(pid) => self.key(&format!("usage:process:{pid}")),
527 SpendScope::Partition(partition) => self.key(&format!("usage:partition:{partition}")),
528 };
529 let mut totals = UsageTotals {
530 micro_usd: self.spend(scope, from, to_inclusive).await?,
531 ..UsageTotals::default()
532 };
533 let fields: HashMap<String, String> = self
534 .client
535 .hgetall(key)
536 .await
537 .map_err(|error| store_error("read the usage totals", &error))?;
538 let range = from.num_days_from_ce()..=to_inclusive.num_days_from_ce();
539 for (field, amount) in fields {
540 let parsed = field.split_once(':').and_then(|(day, name)| {
541 Some((day.parse::<i32>().ok()?, name, amount.parse::<u64>().ok()?))
542 });
543 let Some((number, name, amount)) = parsed else {
544 return Err(store_error(
545 "read the usage totals",
546 &format!("the usage total {field} = {amount} is corrupt"),
547 ));
548 };
549 if range.contains(&number) {
550 totals.add_counter(name, amount);
551 }
552 }
553 Ok(totals)
554 }
555}