1use fred::prelude::{
27 Builder, Client, ClientLike as _, Config, HashesInterface as _, LuaInterface as _,
28};
29use fred::types::Value;
30use std::collections::HashMap;
31
32use crate::charter::SignalRecord;
33use crate::error::{KernelError, Result};
34use crate::partition::PartitionId;
35
36const LAYOUT: i64 = 1;
38
39const MIGRATE_SCRIPT: &str = r"
41local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
42local mine = tonumber(ARGV[1])
43if stored > mine then return stored end
44if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
45return mine
46";
47
48const CHARTER_APPEND_SCRIPT: &str = r"
50local latest = tonumber(redis.call('GET', KEYS[2]) or '0')
51if latest + 1 ~= tonumber(ARGV[1]) then return 0 end
52redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
53redis.call('SET', KEYS[2], ARGV[1])
54return 1
55";
56
57const CHARTER_CURRENT_SCRIPT: &str = r"
59local latest = redis.call('GET', KEYS[2])
60if not latest then return false end
61return redis.call('HGET', KEYS[1], latest)
62";
63
64const KPI_RECORD_SCRIPT: &str = r"
66if redis.call('SADD', KEYS[2], ARGV[1]) == 0 then return 0 end
67redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2])
68return 1
69";
70
71const JOB_APPLY_SCRIPT: &str = r"
73local stored = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
74if stored + 1 ~= tonumber(ARGV[2]) then return 0 end
75redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])
76redis.call('HSET', KEYS[2], ARGV[1], ARGV[2])
77redis.call('RPUSH', KEYS[3], ARGV[4])
78return 1
79";
80
81const DECISION_SCRIPT: &str = r"
83if redis.call('HSETNX', KEYS[1], ARGV[1], ARGV[3]) == 0 then return 0 end
84redis.call('ZADD', KEYS[2], ARGV[2], ARGV[1])
85return 1
86";
87
88const SIGNAL_RECORD_SCRIPT: &str = r"
92local id = redis.call('HGET', KEYS[1], ARGV[1])
93if id then
94 local row = ARGV[3] .. id
95 if redis.call('HGET', row, 'open') == '1' then
96 redis.call('HINCRBY', row, 'count', 1)
97 redis.call('HSET', row, 'signal', ARGV[7], 'source', ARGV[8], 'last_at', ARGV[9])
98 local fields = redis.call('HGETALL', row)
99 table.insert(fields, 1, 0)
100 return fields
101 end
102end
103local row = ARGV[3] .. ARGV[2]
104redis.call('HSET', row, 'id', ARGV[2], 'partition', ARGV[4], 'kind', ARGV[5], 'topic', ARGV[6],
105 'count', 1, 'signal', ARGV[7], 'source', ARGV[8], 'first_at', ARGV[9], 'last_at', ARGV[9],
106 'open', '1', 'okey', ARGV[1])
107redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
108redis.call('ZADD', KEYS[2], ARGV[9], ARGV[2])
109local fields = redis.call('HGETALL', row)
110table.insert(fields, 1, 1)
111return fields
112";
113
114const SIGNAL_CLOSE_SCRIPT: &str = r"
116if redis.call('HGET', KEYS[2], 'open') ~= '1' then return 0 end
117redis.call('HSET', KEYS[2], 'open', '0')
118local field = redis.call('HGET', KEYS[2], 'okey')
119if field and redis.call('HGET', KEYS[1], field) == ARGV[1] then redis.call('HDEL', KEYS[1], field) end
120return 1
121";
122
123const RANGE_SCRIPT: &str = "return redis.call('ZRANGEBYSCORE', KEYS[1], ARGV[1], ARGV[2])";
125
126const RATE_SCRIPT: &str = r"
128local count = redis.call('INCR', KEYS[1])
129if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
130return count
131";
132
133fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
134 KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
135}
136
137fn decode<T: serde::de::DeserializeOwned>(what: &str, record: &str) -> Result<T> {
138 serde_json::from_str(record).map_err(|error| KernelError::Store {
139 backend: "redis",
140 reason: format!("a stored {what} is corrupt: {error}"),
141 })
142}
143
144fn pairs(values: &[Value]) -> HashMap<String, String> {
146 values
147 .chunks(2)
148 .filter_map(|pair| match pair {
149 [name, value] => Some((name.as_string()?, value.as_string()?)),
150 _ => None,
151 })
152 .collect()
153}
154
155fn signal_record(fields: &HashMap<String, String>) -> Result<SignalRecord> {
157 let text = |name: &str| {
158 fields
159 .get(name)
160 .cloned()
161 .ok_or_else(|| store_error("read a signal record", &format!("no `{name}` field")))
162 };
163 let number = |name: &str| -> Result<i64> {
164 text(name)?
165 .parse::<i64>()
166 .map_err(|error| store_error("read a signal record", &format!("`{name}`: {error}")))
167 };
168 let instant = |name: &str| -> Result<chrono::DateTime<chrono::Utc>> {
169 let micros = number(name)?;
170 chrono::DateTime::from_timestamp_micros(micros).ok_or_else(|| {
171 store_error("read a signal record", &format!("`{name}` is out of range"))
172 })
173 };
174 Ok(SignalRecord {
175 id: text("id")?,
176 partition: PartitionId::new(text("partition")?),
177 kind: text("kind")?,
178 topic: text("topic")?,
179 count: u32::try_from(number("count")?).unwrap_or(u32::MAX),
180 signal: decode("signal", &text("signal")?)?,
181 source: text("source")?,
182 first_at: instant("first_at")?,
183 last_at: instant("last_at")?,
184 open: text("open")? == "1",
185 })
186}
187
188macro_rules! redis_charter_store_type {
191 ($(#[$doc:meta])* $name:ident) => {
192 $(#[$doc])*
193 #[derive(Debug, Clone)]
194 pub struct $name {
195 client: Client,
196 namespace: String,
197 }
198
199 impl $name {
200 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
202
203 pub fn from_client(client: Client) -> Self {
205 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
206 }
207
208 pub async fn connect(url: &str) -> Result<Self> {
215 let config = Config::from_url(url)
216 .map_err(|error| store_error("parse the Redis URL", &error))?;
217 let client = Builder::from_config(config)
218 .build()
219 .map_err(|error| store_error("build the Redis client", &error))?;
220 client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
221 Ok(Self::from_client(client))
222 }
223
224 #[must_use]
226 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
227 self.namespace = namespace.into();
228 self
229 }
230
231 pub fn client(&self) -> &Client {
233 &self.client
234 }
235
236 pub fn namespace(&self) -> &str {
238 &self.namespace
239 }
240
241 pub async fn migrate(&self) -> Result<()> {
248 let stored: i64 = self
249 .client
250 .eval(MIGRATE_SCRIPT, vec![self.key("charter:layout")], vec![LAYOUT.to_string()])
251 .await
252 .map_err(|error| store_error("record the layout version", &error))?;
253 if stored > LAYOUT {
254 return Err(KernelError::Store {
255 backend: "redis",
256 reason: format!(
257 "the charter keys under {} have layout v{stored}, but this release \
258 knows up to v{LAYOUT}; upgrade ADK-Rust",
259 self.namespace
260 ),
261 });
262 }
263 Ok(())
264 }
265
266 fn key(&self, suffix: &str) -> String {
268 let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
269 format!("{{{namespace}}}:{suffix}")
270 }
271 }
272 };
273}
274
275redis_charter_store_type!(
276 RedisCharterStore
290);
291redis_charter_store_type!(
292 RedisKpiStore
295);
296redis_charter_store_type!(
297 RedisAutonomyStore
300);
301redis_charter_store_type!(
302 RedisSignalStore
305);
306
307#[async_trait::async_trait]
308impl crate::charter::CharterStore for RedisCharterStore {
309 async fn append(&self, version: crate::charter::CharterVersion) -> Result<bool> {
310 let site = version.site();
311 let keys = vec![
312 self.key(&format!("charters:{site}")),
313 self.key(&format!("charters:{site}:latest")),
314 ];
315 let added: i64 = self
316 .client
317 .eval(
318 CHARTER_APPEND_SCRIPT,
319 keys,
320 vec![version.version().to_string(), serde_json::to_string(&version)?],
321 )
322 .await
323 .map_err(|error| store_error("append a charter version", &error))?;
324 Ok(added == 1)
325 }
326
327 async fn current(&self, site: uuid::Uuid) -> Result<Option<crate::charter::CharterVersion>> {
328 let keys = vec![
329 self.key(&format!("charters:{site}")),
330 self.key(&format!("charters:{site}:latest")),
331 ];
332 let record: Option<String> = self
333 .client
334 .eval(CHARTER_CURRENT_SCRIPT, keys, Vec::<String>::new())
335 .await
336 .map_err(|error| store_error("read the current charter", &error))?;
337 record.map(|record| decode("charter version", &record)).transpose()
338 }
339
340 async fn history(&self, site: uuid::Uuid) -> Result<Vec<crate::charter::CharterVersion>> {
341 let all: std::collections::HashMap<String, String> = self
342 .client
343 .hgetall(self.key(&format!("charters:{site}")))
344 .await
345 .map_err(|error| store_error("read the charter history", &error))?;
346 let mut versions = all
347 .values()
348 .map(|record| decode::<crate::charter::CharterVersion>("charter version", record))
349 .collect::<Result<Vec<_>>>()?;
350 versions.sort_by_key(crate::charter::CharterVersion::version);
351 Ok(versions)
352 }
353
354 async fn get(
355 &self,
356 site: uuid::Uuid,
357 version: u32,
358 ) -> Result<Option<crate::charter::CharterVersion>> {
359 let record: Option<String> = self
360 .client
361 .hget(self.key(&format!("charters:{site}")), version.to_string())
362 .await
363 .map_err(|error| store_error("read a charter version", &error))?;
364 record.map(|record| decode("charter version", &record)).transpose()
365 }
366}
367
368#[async_trait::async_trait]
369impl crate::charter::KpiStore for RedisKpiStore {
370 async fn record(&self, sample: crate::charter::KpiSample) -> Result<bool> {
371 sample.validate()?;
372 let base = format!("kpi:{}:{}", sample.site, sample.kpi);
373 let keys = vec![self.key(&base), self.key(&format!("{base}:at"))];
374 let added: i64 = self
375 .client
376 .eval(
377 KPI_RECORD_SCRIPT,
378 keys,
379 vec![sample.at.timestamp_micros().to_string(), serde_json::to_string(&sample)?],
380 )
381 .await
382 .map_err(|error| store_error("record a KPI sample", &error))?;
383 Ok(added == 1)
384 }
385
386 async fn samples(
387 &self,
388 site: uuid::Uuid,
389 kpi: &str,
390 from: chrono::DateTime<chrono::Utc>,
391 to: chrono::DateTime<chrono::Utc>,
392 ) -> Result<Vec<crate::charter::KpiSample>> {
393 if from >= to {
394 return Ok(Vec::new());
395 }
396 let records: Vec<String> = self
397 .client
398 .eval(
399 RANGE_SCRIPT,
400 vec![self.key(&format!("kpi:{site}:{kpi}"))],
401 vec![from.timestamp_micros().to_string(), format!("({}", to.timestamp_micros())],
402 )
403 .await
404 .map_err(|error| store_error("read KPI samples", &error))?;
405 records.iter().map(|record| decode("KPI sample", record)).collect()
406 }
407
408 async fn state(&self, site: uuid::Uuid, kpi: &str) -> Result<Option<crate::charter::KpiState>> {
409 let record: Option<String> = self
410 .client
411 .hget(self.key(&format!("kpi-states:{site}")), format!("kpi:{kpi}"))
412 .await
413 .map_err(|error| store_error("read a KPI state", &error))?;
414 record.map(|record| decode("KPI state", &record)).transpose()
415 }
416
417 async fn put_state(&self, state: crate::charter::KpiState) -> Result<()> {
418 let key = self.key(&format!("kpi-states:{}", state.site));
419 self.client
420 .hset::<i64, _, _>(key, (format!("kpi:{}", state.kpi), serde_json::to_string(&state)?))
421 .await
422 .map_err(|error| store_error("write a KPI state", &error))?;
423 Ok(())
424 }
425
426 async fn guardrail(
427 &self,
428 site: uuid::Uuid,
429 guardrail: &str,
430 ) -> Result<Option<crate::charter::GuardrailState>> {
431 let record: Option<String> = self
432 .client
433 .hget(self.key(&format!("kpi-states:{site}")), format!("guardrail:{guardrail}"))
434 .await
435 .map_err(|error| store_error("read a guardrail state", &error))?;
436 record.map(|record| decode("guardrail state", &record)).transpose()
437 }
438
439 async fn put_guardrail(&self, state: crate::charter::GuardrailState) -> Result<()> {
440 let key = self.key(&format!("kpi-states:{}", state.site));
441 self.client
442 .hset::<i64, _, _>(
443 key,
444 (format!("guardrail:{}", state.guardrail), serde_json::to_string(&state)?),
445 )
446 .await
447 .map_err(|error| store_error("write a guardrail state", &error))?;
448 Ok(())
449 }
450}
451
452#[async_trait::async_trait]
453impl crate::charter::AutonomyStore for RedisAutonomyStore {
454 async fn get(
455 &self,
456 site: uuid::Uuid,
457 job: &str,
458 ) -> Result<Option<crate::charter::JobAutonomy>> {
459 let record: Option<String> = self
460 .client
461 .hget(self.key(&format!("jobs:{site}")), job)
462 .await
463 .map_err(|error| store_error("read a job's autonomy", &error))?;
464 record.map(|record| decode("job autonomy", &record)).transpose()
465 }
466
467 async fn list(&self, site: uuid::Uuid) -> Result<Vec<crate::charter::JobAutonomy>> {
468 let all: std::collections::HashMap<String, String> = self
469 .client
470 .hgetall(self.key(&format!("jobs:{site}")))
471 .await
472 .map_err(|error| store_error("list job autonomy", &error))?;
473 let mut jobs = all
474 .values()
475 .map(|record| decode::<crate::charter::JobAutonomy>("job autonomy", record))
476 .collect::<Result<Vec<_>>>()?;
477 jobs.sort_by(|a, b| a.job.cmp(&b.job));
478 Ok(jobs)
479 }
480
481 async fn apply(
482 &self,
483 record: crate::charter::JobAutonomy,
484 change: crate::charter::AutonomyChange,
485 ) -> Result<bool> {
486 crate::charter::check_autonomy_apply(&record, &change)?;
487 let site = record.site;
488 let keys = vec![
489 self.key(&format!("jobs:{site}")),
490 self.key(&format!("job-revisions:{site}")),
491 self.key(&format!("job-history:{site}:{}", record.job)),
492 ];
493 let args = vec![
494 record.job.clone(),
495 record.revision.to_string(),
496 serde_json::to_string(&record)?,
497 serde_json::to_string(&change)?,
498 ];
499 let applied: i64 = self
500 .client
501 .eval(JOB_APPLY_SCRIPT, keys, args)
502 .await
503 .map_err(|error| store_error("change a job's autonomy", &error))?;
504 Ok(applied == 1)
505 }
506
507 async fn history(
508 &self,
509 site: uuid::Uuid,
510 job: &str,
511 ) -> Result<Vec<crate::charter::AutonomyChange>> {
512 use fred::prelude::ListInterface as _;
513
514 let changes: Vec<String> = self
515 .client
516 .lrange(self.key(&format!("job-history:{site}:{job}")), 0, -1)
517 .await
518 .map_err(|error| store_error("read a job's autonomy history", &error))?;
519 changes.iter().map(|change| decode("autonomy change", change)).collect()
520 }
521
522 async fn record_decision(&self, decision: crate::charter::JobDecision) -> Result<bool> {
523 let base = format!("job-decisions:{}:{}", decision.site, decision.job);
524 let keys = vec![self.key(&base), self.key(&format!("{base}:at"))];
525 let args = vec![
526 decision.id.clone(),
527 decision.at.timestamp_micros().to_string(),
528 serde_json::to_string(&decision)?,
529 ];
530 let added: i64 = self
531 .client
532 .eval(DECISION_SCRIPT, keys, args)
533 .await
534 .map_err(|error| store_error("record a job decision", &error))?;
535 Ok(added == 1)
536 }
537
538 async fn decisions(
539 &self,
540 site: uuid::Uuid,
541 job: &str,
542 since: chrono::DateTime<chrono::Utc>,
543 ) -> Result<Vec<crate::charter::JobDecision>> {
544 let base = format!("job-decisions:{site}:{job}");
545 let ids: Vec<String> = self
546 .client
547 .eval(
548 RANGE_SCRIPT,
549 vec![self.key(&format!("{base}:at"))],
550 vec![since.timestamp_micros().to_string(), "+inf".to_string()],
551 )
552 .await
553 .map_err(|error| store_error("read job decisions", &error))?;
554 let mut decisions = Vec::with_capacity(ids.len());
555 for chunk in ids.chunks(500) {
556 let records: Vec<Option<String>> = self
557 .client
558 .hmget(self.key(&base), chunk.to_vec())
559 .await
560 .map_err(|error| store_error("read job decisions", &error))?;
561 for record in records.into_iter().flatten() {
562 decisions.push(decode::<crate::charter::JobDecision>("job decision", &record)?);
563 }
564 }
565 decisions.sort_by(|a, b| a.at.cmp(&b.at).then_with(|| a.id.cmp(&b.id)));
566 Ok(decisions)
567 }
568}
569
570#[async_trait::async_trait]
571impl crate::charter::SignalStore for RedisSignalStore {
572 async fn record(
573 &self,
574 key: &crate::charter::SignalKey,
575 signal: &awp_types::Signal,
576 source: &str,
577 at: chrono::DateTime<chrono::Utc>,
578 new_id: &str,
579 ) -> Result<(SignalRecord, bool)> {
580 let field = serde_json::to_string(&(key.partition.as_str(), &key.kind, &key.topic))?;
581 let keys = vec![self.key("signal-open"), self.key("signals")];
582 let args = vec![
583 field,
584 new_id.to_string(),
585 self.key("signal:"),
586 key.partition.as_str().to_string(),
587 key.kind.clone(),
588 key.topic.clone(),
589 serde_json::to_string(signal)?,
590 source.to_string(),
591 at.timestamp_micros().to_string(),
592 ];
593 let reply: Value = self
594 .client
595 .eval(SIGNAL_RECORD_SCRIPT, keys, args)
596 .await
597 .map_err(|error| store_error("record a signal", &error))?;
598 let mut items = reply.into_array();
599 if items.is_empty() {
600 return Err(store_error("record a signal", &"the script answered nothing"));
601 }
602 let new = items.remove(0).as_i64() == Some(1);
603 Ok((signal_record(&pairs(&items))?, new))
604 }
605
606 async fn get(&self, id: &str) -> Result<Option<SignalRecord>> {
607 let fields: HashMap<String, String> = self
608 .client
609 .hgetall(self.key(&format!("signal:{id}")))
610 .await
611 .map_err(|error| store_error("read a signal record", &error))?;
612 if fields.is_empty() { Ok(None) } else { signal_record(&fields).map(Some) }
613 }
614
615 async fn list(&self, filter: &crate::charter::SignalFilter) -> Result<Vec<SignalRecord>> {
616 let ids: Vec<String> = self
617 .client
618 .eval(
619 RANGE_SCRIPT,
620 vec![self.key("signals")],
621 vec!["-inf".to_string(), "+inf".to_string()],
622 )
623 .await
624 .map_err(|error| store_error("list signal records", &error))?;
625 let mut records = Vec::new();
626 for id in ids {
627 if filter.limit.is_some_and(|limit| records.len() >= limit) {
628 break;
629 }
630 if let Some(record) = self.get(&id).await?
631 && filter.matches(&record)
632 {
633 records.push(record);
634 }
635 }
636 Ok(records)
637 }
638
639 async fn close(&self, id: &str) -> Result<bool> {
640 let keys = vec![self.key("signal-open"), self.key(&format!("signal:{id}"))];
641 let closed: i64 = self
642 .client
643 .eval(SIGNAL_CLOSE_SCRIPT, keys, vec![id.to_string()])
644 .await
645 .map_err(|error| store_error("close a signal record", &error))?;
646 Ok(closed == 1)
647 }
648
649 async fn hit(&self, source: &str, window_start: chrono::DateTime<chrono::Utc>) -> Result<u64> {
650 let key = self.key(&format!("signal-rate:{source}:{}", window_start.timestamp_micros()));
651 let life = (crate::charter::RATE_HORIZON_MICROS / 1_000).to_string();
652 let count: i64 = self
653 .client
654 .eval(RATE_SCRIPT, vec![key], vec![life])
655 .await
656 .map_err(|error| store_error("count a signal source", &error))?;
657 Ok(u64::try_from(count).unwrap_or(0))
658 }
659}