Skip to main content

adk_kernel/stores/
agent_redis.rs

1//! The Redis [`AgentStore`] (spec 3.3 §5.7, §10 K7, 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::agents::{AgentRecord, AgentStore};
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 ids index. ARGV: id, version, state, record JSON, the expected version
26/// (`0` for none). Returns 0, writing nothing, when the stored version is another.
27const PUT_SCRIPT: &str = r"
28local stored = tonumber(redis.call('HGET', KEYS[1], 'version') or '0')
29if stored ~= tonumber(ARGV[5]) then return 0 end
30redis.call('HSET', KEYS[1], 'version', ARGV[2], 'state', ARGV[3], 'record', ARGV[4])
31redis.call('ZADD', KEYS[2], 0, ARGV[1])
32return 1
33";
34
35/// KEYS: row, the ids index. ARGV: id. Returns 0 unless the row is a suggestion.
36const DELETE_SCRIPT: &str = r"
37if redis.call('HGET', KEYS[1], 'state') ~= 'proposed' then return 0 end
38redis.call('DEL', KEYS[1])
39redis.call('ZREM', KEYS[2], ARGV[1])
40return 1
41";
42
43/// KEYS: the ids index. ARGV: row key prefix. Returns every record's JSON in id order.
44const LIST_SCRIPT: &str = r"
45local out = {}
46for _, id in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
47  local record = redis.call('HGET', ARGV[1] .. id, 'record')
48  if record then table.insert(out, record) end
49end
50return out
51";
52
53/// An [`AgentStore`] in Redis, shared by every replica (spec 3.3 §5.7, §10 K7, feature
54/// `redis`).
55///
56/// It opens from the URL of `adk-rust serve --store`. Keys sit under the namespace
57/// [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless [`with_namespace`](Self::with_namespace)
58/// sets another, inside the hash tag `{<namespace>}`, so the store's scripts touch one Redis
59/// Cluster slot; braces in the namespace are percent-encoded.
60///
61/// | Key | Type | Contents |
62/// |-----|------|----------|
63/// | `{<ns>}:agents:agent:<id>` | Hash | One agent: `version`, `state` and `record` (the record's JSON) |
64/// | `{<ns>}:agents:ids` | Sorted set | Every id at score 0, so it ranges in byte order |
65/// | `{<ns>}:agents:layout` | String | The layout version [`migrate`](Self::migrate) recorded |
66///
67/// Every change runs as one Lua script, which Redis executes atomically; `put_if_version`
68/// compares the stored version and writes in the same script, so two replicas changing one
69/// agent from the same version change it once.
70///
71/// # Example
72///
73/// ```rust,no_run
74/// # async fn example() -> adk_kernel::Result<()> {
75/// let store = adk_kernel::stores::RedisAgentStore::connect("redis://localhost:6379").await?;
76/// store.migrate().await?;
77/// # Ok(())
78/// # }
79/// ```
80#[derive(Debug, Clone)]
81pub struct RedisAgentStore {
82    client: Client,
83    namespace: String,
84}
85
86impl RedisAgentStore {
87    /// The namespace keys sit under by default, the process store's.
88    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
89
90    /// A store over an initialized client, such as one shared with the process store.
91    pub fn from_client(client: Client) -> Self {
92        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
93    }
94
95    /// Connects to `url`.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`KernelError::Store`] when the URL is invalid or the server cannot be
100    /// reached.
101    pub async fn connect(url: &str) -> Result<Self> {
102        let config =
103            Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
104        let client = Builder::from_config(config)
105            .build()
106            .map_err(|error| store_error("build the Redis client", &error))?;
107        client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
108        Ok(Self::from_client(client))
109    }
110
111    /// Keeps the store's keys under `namespace`.
112    #[must_use]
113    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
114        self.namespace = namespace.into();
115        self
116    }
117
118    /// The client the store uses.
119    pub fn client(&self) -> &Client {
120        &self.client
121    }
122
123    /// The namespace the store's keys sit under.
124    pub fn namespace(&self) -> &str {
125        &self.namespace
126    }
127
128    /// Records the store's layout version, refusing a database a newer release wrote.
129    ///
130    /// # Errors
131    ///
132    /// Returns [`KernelError::Store`] when the server fails or holds a newer layout.
133    pub async fn migrate(&self) -> Result<()> {
134        let stored: i64 = self
135            .client
136            .eval(MIGRATE_SCRIPT, vec![self.key("agents:layout")], vec![LAYOUT.to_string()])
137            .await
138            .map_err(|error| store_error("record the agent layout version", &error))?;
139        if stored > LAYOUT {
140            return Err(KernelError::Store {
141                backend: "redis",
142                reason: format!(
143                    "the agent keys under {} have layout v{stored}, but this release knows up \
144                     to v{LAYOUT}; upgrade ADK-Rust",
145                    self.namespace
146                ),
147            });
148        }
149        Ok(())
150    }
151
152    /// `{<namespace>}:<suffix>`.
153    fn key(&self, suffix: &str) -> String {
154        let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
155        format!("{{{namespace}}}:{suffix}")
156    }
157
158    fn row_key(&self, id: &str) -> String {
159        self.key(&format!("agents:agent:{id}"))
160    }
161
162    fn index_key(&self) -> String {
163        self.key("agents:ids")
164    }
165
166    async fn eval(&self, script: &str, keys: Vec<String>, args: Vec<String>) -> Result<i64> {
167        self.client
168            .eval(script, keys, args)
169            .await
170            .map_err(|error| store_error("write the agent table", &error))
171    }
172}
173
174fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
175    KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
176}
177
178fn decode(record: &str) -> Result<AgentRecord> {
179    serde_json::from_str(record).map_err(|error| KernelError::Store {
180        backend: "redis",
181        reason: format!("a stored agent is corrupt: {error}"),
182    })
183}
184
185#[async_trait]
186impl AgentStore for RedisAgentStore {
187    async fn put_if_version(&self, record: AgentRecord, expected: u64) -> Result<bool> {
188        let keys = vec![self.row_key(&record.id), self.index_key()];
189        let args = vec![
190            record.id.clone(),
191            record.version.to_string(),
192            record.state.as_str().to_string(),
193            serde_json::to_string(&record)?,
194            expected.to_string(),
195        ];
196        Ok(self.eval(PUT_SCRIPT, keys, args).await? == 1)
197    }
198
199    async fn get(&self, id: &str) -> Result<Option<AgentRecord>> {
200        let record: Option<String> = self
201            .client
202            .hget(self.row_key(id), "record")
203            .await
204            .map_err(|error| store_error("read the agent table", &error))?;
205        record.as_deref().map(decode).transpose()
206    }
207
208    async fn list(&self) -> Result<Vec<AgentRecord>> {
209        let reply: Value = self
210            .client
211            .eval(LIST_SCRIPT, vec![self.index_key()], vec![self.key("agents:agent:")])
212            .await
213            .map_err(|error| store_error("list the agent table", &error))?;
214        reply
215            .into_array()
216            .into_iter()
217            .map(|value| {
218                let text = value
219                    .into_string()
220                    .ok_or_else(|| store_error("list the agent table", &"a record is not text"))?;
221                decode(&text)
222            })
223            .collect()
224    }
225
226    async fn delete(&self, id: &str) -> Result<bool> {
227        let keys = vec![self.row_key(id), self.index_key()];
228        Ok(self.eval(DELETE_SCRIPT, keys, vec![id.to_string()]).await? == 1)
229    }
230}