Skip to main content

adk_kernel/stores/
partition_redis.rs

1//! The Redis [`PartitionStore`] (spec 3.2 §7.8, §13 Q8, feature `redis`).
2
3use 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
13/// The layout version this release writes.
14const LAYOUT: i64 = 1;
15
16/// KEYS: layout. ARGV: this release's layout version. Records it unless the stored one is
17/// newer, and returns the stored one.
18const 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
26/// KEYS: row, index. ARGV: id, record. Writes the record and indexes the id.
27const PUT_SCRIPT: &str = r"
28redis.call('SET', KEYS[1], ARGV[2])
29redis.call('ZADD', KEYS[2], 0, ARGV[1])
30return 1
31";
32
33/// KEYS: row, index. ARGV: id. Returns 0 when there was no record.
34const DELETE_SCRIPT: &str = r"
35local existed = redis.call('DEL', KEYS[1])
36redis.call('ZREM', KEYS[2], ARGV[1])
37return existed
38";
39
40/// KEYS: index. ARGV: row key prefix. Returns every indexed record, in id order.
41const 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
50/// KEYS: row, every-crossing index, run index, source index. ARGV: id, score, record.
51const 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
57/// KEYS: the index to walk. ARGV: row key prefix, least score (`-inf` for any). Returns the
58/// records in (time, id) order.
59const 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
68/// KEYS: the run's grant set. Returns how many grants it held, then drops it.
69const RELEASE_SCRIPT: &str = r"
70local held = redis.call('SCARD', KEYS[1])
71redis.call('DEL', KEYS[1])
72return held
73";
74
75/// A [`PartitionStore`] in Redis, shared by every replica (spec 3.2 §7.1, §7.8, feature
76/// `redis`).
77///
78/// It opens from the URL of `adk-rust serve --store`. Keys sit under the namespace
79/// [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless
80/// [`with_namespace`](Self::with_namespace) sets another, inside the hash tag
81/// `{<namespace>}`, so the store's scripts touch one Redis Cluster slot; braces in the
82/// namespace are percent-encoded. The process store's keys under the same namespace do not
83/// collide with these.
84///
85/// | Key | Type | Contents |
86/// |-----|------|----------|
87/// | `{<ns>}:partition:<id>` | String | One partition, as JSON |
88/// | `{<ns>}:partitions` | Sorted set | Every partition id, scored 0, so it ranges in byte order |
89/// | `{<ns>}:crossing:<id>` | String | One crossing record, as JSON |
90/// | `{<ns>}:crossings`, `:crossings:run:<run>`, `:crossings:from:<partition>` | Sorted set | Crossing ids scored by time in microseconds: every crossing, one run's, one source partition's |
91/// | `{<ns>}:crossing-grants:<run>` | Set | The fingerprint digests of a durable run's live grants, dropped when the run is released |
92/// | `{<ns>}:partitions:layout` | String | The layout version [`migrate`](Self::migrate) recorded |
93///
94/// Every write is one Lua script, which Redis runs atomically; crossing records are only
95/// ever added.
96///
97/// # Example
98///
99/// ```rust,no_run
100/// # async fn example() -> adk_kernel::Result<()> {
101/// let store = adk_kernel::RedisPartitionStore::connect("redis://localhost:6379").await?;
102/// store.migrate().await?;
103/// # Ok(())
104/// # }
105/// ```
106#[derive(Debug, Clone)]
107pub struct RedisPartitionStore {
108    client: Client,
109    namespace: String,
110}
111
112impl RedisPartitionStore {
113    /// The namespace keys sit under by default, shared with the process store.
114    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
115
116    /// A store over an initialized client, such as one shared with the run store.
117    pub fn from_client(client: Client) -> Self {
118        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
119    }
120
121    /// Connects to `url`.
122    ///
123    /// # Errors
124    ///
125    /// Returns [`KernelError::Store`] when the URL is invalid or the server cannot be
126    /// reached.
127    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    /// Keeps the store's keys under `namespace`.
138    #[must_use]
139    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
140        self.namespace = namespace.into();
141        self
142    }
143
144    /// The client the store uses.
145    pub fn client(&self) -> &Client {
146        &self.client
147    }
148
149    /// The namespace the store's keys sit under.
150    pub fn namespace(&self) -> &str {
151        &self.namespace
152    }
153
154    /// Records the store's layout version, refusing a database a newer release wrote.
155    ///
156    /// # Errors
157    ///
158    /// Returns [`KernelError::Store`] when the server fails or holds a newer layout.
159    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    /// `{<namespace>}:<suffix>`.
179    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        // Walk the narrowest index the filter names; the rest is checked here.
277        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}