Skip to main content

adk_graph/checkpointers/
redis.rs

1//! Redis [`Checkpointer`].
2//!
3//! # Key layout
4//!
5//! | Key | Type | Contents |
6//! |-----|------|----------|
7//! | `adk:graph:{<thread>}:versions` | Sorted set | Checkpoint ID, scored by version |
8//! | `adk:graph:{<thread>}:data` | Hash | Checkpoint ID → checkpoint JSON |
9//! | `adk:graph:id:{<id>}` | String | The thread that holds the checkpoint ID |
10//!
11//! Thread and checkpoint IDs are percent-encoded (`%`, `:`, `{`, `}`), so an ID cannot
12//! spill into the next segment or move a key's hash slot. A thread's two keys share a
13//! hash tag, so the save script runs on Redis Cluster. Versions are sorted-set scores,
14//! exact up to 2^53.
15
16use async_trait::async_trait;
17use fred::prelude::*;
18
19use super::{decode, encode, storage_error};
20use crate::checkpoint::{Checkpointer, RetentionPolicy, conflict, duplicate_id, ensure_newer};
21use crate::error::Result;
22use crate::state::Checkpoint;
23
24const BACKEND: &str = "redis";
25
26/// KEYS: versions, data. ARGV: version, checkpoint ID, checkpoint JSON.
27/// Returns -1 when stored, or the thread's head version when it refuses.
28const SAVE_SCRIPT: &str = r#"
29local top = redis.call('ZREVRANGE', KEYS[1], 0, 0, 'WITHSCORES')
30if top[2] and tonumber(top[2]) >= tonumber(ARGV[1]) then
31  return tonumber(top[2])
32end
33redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2])
34redis.call('HSET', KEYS[2], ARGV[2], ARGV[3])
35return -1
36"#;
37
38/// KEYS: versions, data. ARGV: ZREVRANGEBYSCORE max, count (-1 for all), order.
39/// Returns checkpoint JSON in the requested order.
40const READ_SCRIPT: &str = r#"
41local ids
42if ARGV[3] == 'asc' then
43  ids = redis.call('ZRANGE', KEYS[1], 0, -1)
44else
45  ids = redis.call('ZREVRANGEBYSCORE', KEYS[1], ARGV[1], '-inf', 'LIMIT', 0, ARGV[2])
46end
47if #ids == 0 then return {} end
48return redis.call('HMGET', KEYS[2], unpack(ids))
49"#;
50
51/// KEYS: versions, data. ARGV: checkpoint IDs to remove.
52const REMOVE_SCRIPT: &str = r#"
53local removed = 0
54for _, id in ipairs(ARGV) do
55  removed = removed + redis.call('ZREM', KEYS[1], id)
56  redis.call('HDEL', KEYS[2], id)
57end
58return removed
59"#;
60
61/// Percent-encodes the characters that delimit key segments or hash tags.
62fn encode_segment(segment: &str) -> String {
63    let mut encoded = String::with_capacity(segment.len());
64    for c in segment.chars() {
65        match c {
66            '%' => encoded.push_str("%25"),
67            ':' => encoded.push_str("%3A"),
68            '{' => encoded.push_str("%7B"),
69            '}' => encoded.push_str("%7D"),
70            other => encoded.push(other),
71        }
72    }
73    encoded
74}
75
76fn thread_keys(thread_id: &str) -> Vec<String> {
77    let prefix = format!("adk:graph:{{{}}}", encode_segment(thread_id));
78    vec![format!("{prefix}:versions"), format!("{prefix}:data")]
79}
80
81fn id_key(checkpoint_id: &str) -> String {
82    format!("adk:graph:id:{{{}}}", encode_segment(checkpoint_id))
83}
84
85/// Redis-backed [`Checkpointer`].
86///
87/// A save first claims the checkpoint ID with `SET NX`, then one Lua script compares
88/// the version with the thread's highest and stores the checkpoint; a refused save
89/// releases the ID. See the [module documentation](self) for the key layout.
90///
91/// # Example
92///
93/// ```rust,no_run
94/// use adk_graph::RedisCheckpointer;
95///
96/// # async fn example() -> adk_graph::Result<()> {
97/// let checkpointer = RedisCheckpointer::new("redis://localhost:6379").await?;
98/// checkpointer.migrate().await?;
99/// # Ok(())
100/// # }
101/// ```
102#[derive(Clone)]
103pub struct RedisCheckpointer {
104    client: Client,
105}
106
107impl std::fmt::Debug for RedisCheckpointer {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("RedisCheckpointer").finish_non_exhaustive()
110    }
111}
112
113impl RedisCheckpointer {
114    /// Connects to `url`.
115    ///
116    /// # Errors
117    ///
118    /// Returns `GraphError::CheckpointError` when the server cannot be reached.
119    pub async fn new(url: &str) -> Result<Self> {
120        let fail =
121            |e: fred::error::Error| storage_error(BACKEND, format!("connection failed: {e}"));
122        let config = Config::from_url(url).map_err(fail)?;
123        let client = Builder::from_config(config).build().map_err(fail)?;
124        client.init().await.map_err(fail)?;
125        Ok(Self::from_client(client))
126    }
127
128    /// Uses an initialized client, such as one shared with other Redis stores.
129    pub fn from_client(client: Client) -> Self {
130        Self { client }
131    }
132
133    /// Loads the checkpointer's scripts into the server's script cache.
134    ///
135    /// # Errors
136    ///
137    /// Returns `GraphError::CheckpointError` when the server rejects a script.
138    pub async fn migrate(&self) -> Result<()> {
139        for script in [SAVE_SCRIPT, READ_SCRIPT, REMOVE_SCRIPT] {
140            let _: String =
141                self.client.script_load(script).await.map_err(|e| storage_error(BACKEND, e))?;
142        }
143        Ok(())
144    }
145
146    async fn read(
147        &self,
148        thread_id: &str,
149        max: &str,
150        count: i64,
151        order: &str,
152    ) -> Result<Vec<Checkpoint>> {
153        let documents: Vec<Option<String>> = self
154            .client
155            .eval(
156                READ_SCRIPT,
157                thread_keys(thread_id),
158                vec![max.to_string(), count.to_string(), order.to_string()],
159            )
160            .await
161            .map_err(|e| storage_error(BACKEND, e))?;
162        documents.into_iter().flatten().map(|data| decode(BACKEND, &data)).collect()
163    }
164}
165
166#[async_trait]
167impl Checkpointer for RedisCheckpointer {
168    async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
169        ensure_newer(checkpoint, None)?;
170        let claimed: Option<String> = self
171            .client
172            .set(
173                id_key(&checkpoint.checkpoint_id),
174                checkpoint.thread_id.as_str(),
175                None,
176                Some(SetOptions::NX),
177                false,
178            )
179            .await
180            .map_err(|e| storage_error(BACKEND, e))?;
181        if claimed.is_none() {
182            return Err(duplicate_id(&checkpoint.checkpoint_id));
183        }
184        let stored: Result<i64> = self
185            .client
186            .eval(
187                SAVE_SCRIPT,
188                thread_keys(&checkpoint.thread_id),
189                vec![
190                    checkpoint.version.to_string(),
191                    checkpoint.checkpoint_id.clone(),
192                    encode(checkpoint)?,
193                ],
194            )
195            .await
196            .map_err(|e| storage_error(BACKEND, e));
197        match stored {
198            Ok(-1) => Ok(checkpoint.checkpoint_id.clone()),
199            refused => {
200                let _: i64 = self
201                    .client
202                    .del(id_key(&checkpoint.checkpoint_id))
203                    .await
204                    .map_err(|e| storage_error(BACKEND, e))?;
205                Err(conflict(checkpoint, refused? as u64))
206            }
207        }
208    }
209
210    async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
211        Ok(self.read(thread_id, "+inf", 1, "desc").await?.pop())
212    }
213
214    async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
215        let thread: Option<String> =
216            self.client.get(id_key(checkpoint_id)).await.map_err(|e| storage_error(BACKEND, e))?;
217        let Some(thread) = thread else { return Ok(None) };
218        let data: Option<String> = self
219            .client
220            .hget(&thread_keys(&thread)[1], checkpoint_id)
221            .await
222            .map_err(|e| storage_error(BACKEND, e))?;
223        data.map(|data| decode(BACKEND, &data)).transpose()
224    }
225
226    async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
227        self.read(thread_id, "+inf", -1, "asc").await
228    }
229
230    async fn list_page(
231        &self,
232        thread_id: &str,
233        before: Option<u64>,
234        limit: usize,
235    ) -> Result<Vec<Checkpoint>> {
236        if limit == 0 {
237            return Ok(Vec::new());
238        }
239        let max = before.map_or_else(|| "+inf".to_string(), |before| format!("({before}"));
240        self.read(thread_id, &max, i64::try_from(limit).unwrap_or(i64::MAX), "desc").await
241    }
242
243    async fn delete(&self, thread_id: &str) -> Result<()> {
244        let ids: Vec<String> = self
245            .list(thread_id)
246            .await?
247            .into_iter()
248            .map(|checkpoint| id_key(&checkpoint.checkpoint_id))
249            .collect();
250        let _: i64 =
251            self.client.del(thread_keys(thread_id)).await.map_err(|e| storage_error(BACKEND, e))?;
252        // ID keys live in their own hash slots, so they are removed one at a time.
253        for key in ids {
254            let _: i64 = self.client.del(key).await.map_err(|e| storage_error(BACKEND, e))?;
255        }
256        Ok(())
257    }
258
259    async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
260        let expired = policy.expired(&self.list(thread_id).await?);
261        if expired.is_empty() {
262            return Ok(0);
263        }
264        let removed: i64 = self
265            .client
266            .eval(REMOVE_SCRIPT, thread_keys(thread_id), expired.clone())
267            .await
268            .map_err(|e| storage_error(BACKEND, e))?;
269        for checkpoint_id in &expired {
270            let _: i64 = self
271                .client
272                .del(id_key(checkpoint_id))
273                .await
274                .map_err(|e| storage_error(BACKEND, e))?;
275        }
276        Ok(removed as usize)
277    }
278}