Skip to main content

adk_kernel/stores/
agenda_redis.rs

1//! The Redis [`AgendaStore`] (spec 3.2 §7.1, §7.5, §13 Q8, feature `redis`).
2
3use async_trait::async_trait;
4use fred::prelude::{
5    Builder, Client, ClientLike as _, Config, HashesInterface as _, LuaInterface as _,
6};
7use fred::types::Value;
8
9use crate::agenda::{AgendaFilter, AgendaItem, AgendaStateKind, AgendaStore};
10use crate::error::{KernelError, Result};
11
12/// The layout version this release writes.
13const LAYOUT: i64 = 1;
14
15/// KEYS: layout. ARGV: this release's layout version. Records it unless the stored one is
16/// newer, and returns the stored one.
17const MIGRATE_SCRIPT: &str = r"
18local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
19local mine = tonumber(ARGV[1])
20if stored > mine then return stored end
21if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
22return mine
23";
24
25/// KEYS: row, the items index. ARGV: id, partition, state, score, item JSON. Replaces the
26/// row and its index entry.
27const PUT_SCRIPT: &str = r"
28redis.call('DEL', KEYS[1])
29redis.call('HSET', KEYS[1], 'partition', ARGV[2], 'state', ARGV[3], 'item', ARGV[5])
30redis.call('ZADD', KEYS[2], ARGV[4], ARGV[1])
31return 1
32";
33
34/// KEYS: row, the items index. ARGV: id, partition, state, score, item JSON, the state the
35/// row must be in. Returns 0, writing nothing, when the row is missing or in another state.
36const TRANSITION_SCRIPT: &str = r"
37if redis.call('HGET', KEYS[1], 'state') ~= ARGV[6] then return 0 end
38redis.call('HSET', KEYS[1], 'partition', ARGV[2], 'state', ARGV[3], 'item', ARGV[5])
39redis.call('ZADD', KEYS[2], ARGV[4], ARGV[1])
40return 1
41";
42
43/// KEYS: row, the items index. ARGV: id. Returns 0 when the row does not exist.
44const DELETE_SCRIPT: &str = r"
45if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
46redis.call('DEL', KEYS[1])
47redis.call('ZREM', KEYS[2], ARGV[1])
48return 1
49";
50
51/// KEYS: the items index. ARGV: row key prefix, the partition (empty for any), the limit
52/// (negative for none), then the states a row may be in (none for any). Returns the
53/// matching items' JSON in index order.
54const LIST_SCRIPT: &str = r"
55local limit = tonumber(ARGV[3])
56local states = {}
57local any_state = true
58for i = 4, #ARGV do states[ARGV[i]] = true; any_state = false end
59local out = {}
60for _, id in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
61  if limit >= 0 and #out >= limit then break end
62  local row = redis.call('HMGET', ARGV[1] .. id, 'partition', 'state', 'item')
63  if row[3] and (ARGV[2] == '' or row[1] == ARGV[2]) and (any_state or states[row[2]]) then
64    table.insert(out, row[3])
65  end
66end
67return out
68";
69
70/// An [`AgendaStore`] in Redis, shared by every replica (spec 3.2 §7.1, §7.5, feature
71/// `redis`).
72///
73/// It opens from the URL of `adk-rust serve --store`. Keys sit under the namespace
74/// [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless [`with_namespace`](Self::with_namespace)
75/// sets another, inside the hash tag `{<namespace>}`, so the store's scripts touch one
76/// Redis Cluster slot; braces in the namespace are percent-encoded.
77///
78/// | Key | Type | Contents |
79/// |-----|------|----------|
80/// | `{<ns>}:agenda:item:<id>` | Hash | One item: `partition`, `state` (its kind) and `item` (the item's JSON) |
81/// | `{<ns>}:agenda:items` | Sorted set | Every id, scored by `created_at` in microseconds, so it ranges oldest first and ties in byte order |
82/// | `{<ns>}:agenda:layout` | String | The layout version [`migrate`](Self::migrate) recorded |
83///
84/// Every change runs as one Lua script, which Redis executes atomically; `transition`
85/// compares the stored state's kind and writes in the same script, so two replicas moving
86/// one item from the same state move it once.
87///
88/// # Example
89///
90/// ```rust,no_run
91/// # async fn example() -> adk_kernel::Result<()> {
92/// let store = adk_kernel::RedisAgendaStore::connect("redis://localhost:6379").await?;
93/// store.migrate().await?;
94/// # Ok(())
95/// # }
96/// ```
97#[derive(Debug, Clone)]
98pub struct RedisAgendaStore {
99    client: Client,
100    namespace: String,
101}
102
103impl RedisAgendaStore {
104    /// The namespace keys sit under by default, the process store's.
105    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
106
107    /// A store over an initialized client, such as one shared with the process store.
108    pub fn from_client(client: Client) -> Self {
109        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
110    }
111
112    /// Connects to `url`.
113    ///
114    /// # Errors
115    ///
116    /// Returns [`KernelError::Store`] when the URL is invalid or the server cannot be
117    /// reached.
118    pub async fn connect(url: &str) -> Result<Self> {
119        let config =
120            Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
121        let client = Builder::from_config(config)
122            .build()
123            .map_err(|error| store_error("build the Redis client", &error))?;
124        client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
125        Ok(Self::from_client(client))
126    }
127
128    /// Keeps the store's keys under `namespace`.
129    #[must_use]
130    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
131        self.namespace = namespace.into();
132        self
133    }
134
135    /// The client the store uses.
136    pub fn client(&self) -> &Client {
137        &self.client
138    }
139
140    /// The namespace the store's keys sit under.
141    pub fn namespace(&self) -> &str {
142        &self.namespace
143    }
144
145    /// Records the store's layout version, refusing a database a newer release wrote.
146    ///
147    /// # Errors
148    ///
149    /// Returns [`KernelError::Store`] when the server fails or holds a newer layout.
150    pub async fn migrate(&self) -> Result<()> {
151        let stored: i64 = self
152            .client
153            .eval(MIGRATE_SCRIPT, vec![self.key("agenda:layout")], vec![LAYOUT.to_string()])
154            .await
155            .map_err(|error| store_error("record the agenda layout version", &error))?;
156        if stored > LAYOUT {
157            return Err(KernelError::Store {
158                backend: "redis",
159                reason: format!(
160                    "the agenda keys under {} have layout v{stored}, but this release knows up \
161                     to v{LAYOUT}; upgrade ADK-Rust",
162                    self.namespace
163                ),
164            });
165        }
166        Ok(())
167    }
168
169    /// `{<namespace>}:<suffix>`.
170    fn key(&self, suffix: &str) -> String {
171        let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
172        format!("{{{namespace}}}:{suffix}")
173    }
174
175    fn row_key(&self, id: &str) -> String {
176        self.key(&format!("agenda:item:{id}"))
177    }
178
179    fn index_key(&self) -> String {
180        self.key("agenda:items")
181    }
182
183    fn row_args(item: &AgendaItem) -> Result<Vec<String>> {
184        Ok(vec![
185            item.id.clone(),
186            item.partition.as_str().to_string(),
187            item.state.kind().as_str().to_string(),
188            item.created_at.timestamp_micros().to_string(),
189            serde_json::to_string(item)?,
190        ])
191    }
192
193    async fn eval(&self, script: &str, keys: Vec<String>, args: Vec<String>) -> Result<i64> {
194        self.client
195            .eval(script, keys, args)
196            .await
197            .map_err(|error| store_error("write the agenda", &error))
198    }
199}
200
201fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
202    KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
203}
204
205fn decode(item: &str) -> Result<AgendaItem> {
206    serde_json::from_str(item).map_err(|error| KernelError::Store {
207        backend: "redis",
208        reason: format!("an agenda item is corrupt: {error}"),
209    })
210}
211
212#[async_trait]
213impl AgendaStore for RedisAgendaStore {
214    async fn put(&self, item: AgendaItem) -> Result<()> {
215        let keys = vec![self.row_key(&item.id), self.index_key()];
216        self.eval(PUT_SCRIPT, keys, Self::row_args(&item)?).await?;
217        Ok(())
218    }
219
220    async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
221        let item: Option<String> = self
222            .client
223            .hget(self.row_key(id), "item")
224            .await
225            .map_err(|error| store_error("read the agenda", &error))?;
226        item.as_deref().map(decode).transpose()
227    }
228
229    async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
230        let mut args = vec![
231            self.key("agenda:item:"),
232            filter.partition.as_ref().map(|p| p.as_str().to_string()).unwrap_or_default(),
233            filter.limit.map_or(-1, |limit| i64::try_from(limit).unwrap_or(i64::MAX)).to_string(),
234        ];
235        args.extend(filter.states.iter().map(|state| state.as_str().to_string()));
236        let reply: Value = self
237            .client
238            .eval(LIST_SCRIPT, vec![self.index_key()], args)
239            .await
240            .map_err(|error| store_error("list the agenda", &error))?;
241        reply
242            .into_array()
243            .into_iter()
244            .map(|value| {
245                let text = value
246                    .into_string()
247                    .ok_or_else(|| store_error("list the agenda", &"an item is not text"))?;
248                decode(&text)
249            })
250            .collect()
251    }
252
253    async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool> {
254        let keys = vec![self.row_key(&item.id), self.index_key()];
255        let mut args = Self::row_args(&item)?;
256        args.push(from.as_str().to_string());
257        Ok(self.eval(TRANSITION_SCRIPT, keys, args).await? == 1)
258    }
259
260    async fn delete(&self, id: &str) -> Result<bool> {
261        let keys = vec![self.row_key(id), self.index_key()];
262        Ok(self.eval(DELETE_SCRIPT, keys, vec![id.to_string()]).await? == 1)
263    }
264}