adk_kernel/stores/
agent_redis.rs1use 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
12const LAYOUT: i64 = 1;
14
15const 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
25const 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
35const 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
43const 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#[derive(Debug, Clone)]
81pub struct RedisAgentStore {
82 client: Client,
83 namespace: String,
84}
85
86impl RedisAgentStore {
87 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
89
90 pub fn from_client(client: Client) -> Self {
92 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
93 }
94
95 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 #[must_use]
113 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
114 self.namespace = namespace.into();
115 self
116 }
117
118 pub fn client(&self) -> &Client {
120 &self.client
121 }
122
123 pub fn namespace(&self) -> &str {
125 &self.namespace
126 }
127
128 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 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}