Skip to main content

adk_kernel/stores/
driver_redis.rs

1//! The Redis [`DriverStore`] (spec 3.2 §7.7, §13 Q8; features `drivers`, `redis`).
2
3use adk_core::ApprovalScope;
4use async_trait::async_trait;
5use fred::prelude::{
6    Builder, Client, ClientLike as _, Config, HashesInterface as _, KeysInterface as _,
7    LuaInterface as _,
8};
9use fred::types::Value;
10
11use crate::drivers::store::park_key;
12use crate::drivers::{DriverPark, DriverRecord, DriverStore};
13use crate::error::{KernelError, Result};
14
15/// The layout version this release writes.
16const LAYOUT: i64 = 1;
17
18/// KEYS: layout. ARGV: this release's layout version. Records it unless the stored one is
19/// newer, and returns the stored one.
20const MIGRATE_SCRIPT: &str = r"
21local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
22local mine = tonumber(ARGV[1])
23if stored > mine then return stored end
24if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
25return mine
26";
27
28/// KEYS: record, all-ids index. ARGV: id, the record's JSON.
29const PUT_SCRIPT: &str = r"
30redis.call('SET', KEYS[1], ARGV[2])
31redis.call('ZADD', KEYS[2], 0, ARGV[1])
32return 1
33";
34
35/// KEYS: record, all-ids index. ARGV: id. Returns 0 when there was no record.
36const DELETE_SCRIPT: &str = r"
37local existed = redis.call('DEL', KEYS[1])
38redis.call('ZREM', KEYS[2], ARGV[1])
39return existed
40";
41
42/// KEYS: park, all-parks index, the driver's park index. ARGV: member, the park's JSON.
43/// Replaces the park and moves its index entry.
44const PUT_PARK_SCRIPT: &str = r"
45local old = redis.call('HGET', KEYS[1], 'idx')
46if old then redis.call('SREM', old, ARGV[1]) end
47redis.call('DEL', KEYS[1])
48redis.call('HSET', KEYS[1], 'json', ARGV[2], 'idx', KEYS[3])
49redis.call('SADD', KEYS[3], ARGV[1])
50redis.call('ZADD', KEYS[2], 0, ARGV[1])
51return 1
52";
53
54/// KEYS: park, all-parks index. ARGV: member. Returns 0 when there was no park.
55const DELETE_PARK_SCRIPT: &str = r"
56local old = redis.call('HGET', KEYS[1], 'idx')
57if not old then return 0 end
58redis.call('SREM', old, ARGV[1])
59redis.call('DEL', KEYS[1])
60redis.call('ZREM', KEYS[2], ARGV[1])
61return 1
62";
63
64/// KEYS: the index to walk (a sorted set when ARGV[2] is `z`, else a set). ARGV: park key
65/// prefix, index kind. Returns every listed park's JSON.
66const LIST_PARKS_SCRIPT: &str = r"
67local members
68if ARGV[2] == 'z' then members = redis.call('ZRANGE', KEYS[1], 0, -1)
69else members = redis.call('SMEMBERS', KEYS[1]) end
70local out = {}
71for _, member in ipairs(members) do
72  local json = redis.call('HGET', ARGV[1] .. member, 'json')
73  if json then table.insert(out, json) end
74end
75return out
76";
77
78/// KEYS: the all-ids index. ARGV: record key prefix. Returns every record's JSON in id order.
79const LIST_SCRIPT: &str = r"
80local out = {}
81for _, id in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
82  local json = redis.call('GET', ARGV[1] .. id)
83  if json then table.insert(out, json) end
84end
85return out
86";
87
88/// A [`DriverStore`] in Redis, shared by every replica (spec 3.2 §7.7, features `drivers`,
89/// `redis`).
90///
91/// Keys sit under the namespace [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless
92/// [`with_namespace`](Self::with_namespace) sets another, inside the hash tag
93/// `{<namespace>}`, so the store's scripts touch one Redis Cluster slot; braces in the
94/// namespace are percent-encoded.
95///
96/// | Key | Type | Contents |
97/// |-----|------|----------|
98/// | `{<ns>}:driver:<id>` | String | One driver's record as JSON |
99/// | `{<ns>}:drivers` | Sorted set | Every driver id, scored 0, so it ranges in byte order |
100/// | `{<ns>}:driver-park:<key>` | Hash | One parked call: `json`, and `idx`, the driver index it is in |
101/// | `{<ns>}:driver-parks` | Sorted set | Every park key, scored 0 |
102/// | `{<ns>}:driver-parks:driver:<id>` | Set | The park keys of one driver |
103/// | `{<ns>}:drivers-layout` | String | The layout version [`migrate`](Self::migrate) recorded |
104///
105/// A park key is its scope's app, user and session and its call id, each percent-encoded
106/// and joined by `/`, so no identifier can spill into another key. Every change runs as
107/// one Lua script, which Redis executes atomically.
108///
109/// # Example
110///
111/// ```rust,no_run
112/// # async fn example() -> adk_kernel::Result<()> {
113/// let store = adk_kernel::stores::RedisDriverStore::connect("redis://localhost:6379").await?;
114/// store.migrate().await?;
115/// # Ok(())
116/// # }
117/// ```
118#[derive(Debug, Clone)]
119pub struct RedisDriverStore {
120    client: Client,
121    namespace: String,
122}
123
124fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
125    KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
126}
127
128/// `text` with every byte outside `[A-Za-z0-9-._~]` percent-encoded.
129fn encode(text: &str) -> String {
130    let mut out = String::with_capacity(text.len());
131    for byte in text.bytes() {
132        if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
133            out.push(byte as char);
134        } else {
135            out.push_str(&format!("%{byte:02X}"));
136        }
137    }
138    out
139}
140
141impl RedisDriverStore {
142    /// The namespace keys sit under by default, shared with the process store.
143    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
144
145    /// A store over an initialized client, such as one shared with the run store.
146    pub fn from_client(client: Client) -> Self {
147        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
148    }
149
150    /// Connects to `url`.
151    ///
152    /// # Errors
153    ///
154    /// Returns [`KernelError::Store`] when the URL is invalid or the server cannot be
155    /// reached.
156    pub async fn connect(url: &str) -> Result<Self> {
157        let config =
158            Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
159        let client = Builder::from_config(config)
160            .build()
161            .map_err(|error| store_error("build the Redis client", &error))?;
162        client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
163        Ok(Self::from_client(client))
164    }
165
166    /// Keeps the store's keys under `namespace`.
167    #[must_use]
168    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
169        self.namespace = namespace.into();
170        self
171    }
172
173    /// The client the store uses.
174    pub fn client(&self) -> &Client {
175        &self.client
176    }
177
178    /// The namespace the store's keys sit under.
179    pub fn namespace(&self) -> &str {
180        &self.namespace
181    }
182
183    /// Records the store's layout version, refusing a database a newer release wrote.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`KernelError::Store`] when the server fails or holds a newer layout.
188    pub async fn migrate(&self) -> Result<()> {
189        let stored: i64 = self
190            .client
191            .eval(MIGRATE_SCRIPT, vec![self.key("drivers-layout")], vec![LAYOUT.to_string()])
192            .await
193            .map_err(|error| store_error("record the layout version", &error))?;
194        if stored > LAYOUT {
195            return Err(KernelError::Store {
196                backend: "redis",
197                reason: format!(
198                    "the driver keys under {} have layout v{stored}, but this release knows up \
199                     to v{LAYOUT}; upgrade ADK-Rust",
200                    self.namespace
201                ),
202            });
203        }
204        Ok(())
205    }
206
207    /// `{<namespace>}:<suffix>`.
208    fn key(&self, suffix: &str) -> String {
209        let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
210        format!("{{{namespace}}}:{suffix}")
211    }
212
213    fn park_member(scope: &ApprovalScope, call_id: &str) -> String {
214        let (app, user, session, call) = park_key(scope, call_id);
215        [app, user, session, call].iter().map(|part| encode(part)).collect::<Vec<_>>().join("/")
216    }
217
218    async fn eval(&self, script: &str, keys: Vec<String>, args: Vec<String>) -> Result<i64> {
219        self.client
220            .eval(script, keys, args)
221            .await
222            .map_err(|error| store_error("write the driver table", &error))
223    }
224
225    async fn eval_list(
226        &self,
227        script: &str,
228        keys: Vec<String>,
229        args: Vec<String>,
230    ) -> Result<Vec<String>> {
231        let reply: Value = self
232            .client
233            .eval(script, keys, args)
234            .await
235            .map_err(|error| store_error("list the driver table", &error))?;
236        reply
237            .into_array()
238            .into_iter()
239            .map(|value| {
240                value
241                    .into_string()
242                    .ok_or_else(|| store_error("list the driver table", &"a value is not text"))
243            })
244            .collect()
245    }
246}
247
248fn decode<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
249    serde_json::from_str(text).map_err(|error| KernelError::Store {
250        backend: "redis",
251        reason: format!("a stored {what} is corrupt: {error}"),
252    })
253}
254
255#[async_trait]
256impl DriverStore for RedisDriverStore {
257    async fn put(&self, record: DriverRecord) -> Result<()> {
258        let id = record.id().to_string();
259        let keys = vec![self.key(&format!("driver:{id}")), self.key("drivers")];
260        self.eval(PUT_SCRIPT, keys, vec![id, serde_json::to_string(&record)?]).await?;
261        Ok(())
262    }
263
264    async fn get(&self, id: &str) -> Result<Option<DriverRecord>> {
265        let text: Option<String> = self
266            .client
267            .get(self.key(&format!("driver:{id}")))
268            .await
269            .map_err(|error| store_error("read the driver table", &error))?;
270        text.map(|text| decode("driver", &text)).transpose()
271    }
272
273    async fn list(&self) -> Result<Vec<DriverRecord>> {
274        let rows = self
275            .eval_list(LIST_SCRIPT, vec![self.key("drivers")], vec![self.key("driver:")])
276            .await?;
277        rows.iter().map(|text| decode("driver", text)).collect()
278    }
279
280    async fn delete(&self, id: &str) -> Result<bool> {
281        let keys = vec![self.key(&format!("driver:{id}")), self.key("drivers")];
282        Ok(self.eval(DELETE_SCRIPT, keys, vec![id.to_string()]).await? > 0)
283    }
284
285    async fn put_park(&self, park: DriverPark) -> Result<()> {
286        let member = Self::park_member(&park.scope, &park.call_id);
287        let keys = vec![
288            self.key(&format!("driver-park:{member}")),
289            self.key("driver-parks"),
290            self.key(&format!("driver-parks:driver:{}", park.driver)),
291        ];
292        self.eval(PUT_PARK_SCRIPT, keys, vec![member, serde_json::to_string(&park)?]).await?;
293        Ok(())
294    }
295
296    async fn get_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<Option<DriverPark>> {
297        let member = Self::park_member(scope, call_id);
298        let text: Option<String> = self
299            .client
300            .hget(self.key(&format!("driver-park:{member}")), "json")
301            .await
302            .map_err(|error| store_error("read the driver table", &error))?;
303        text.map(|text| decode("parked driver call", &text)).transpose()
304    }
305
306    async fn list_parks(&self, driver: Option<&str>) -> Result<Vec<DriverPark>> {
307        let (index, kind) = match driver {
308            Some(driver) => (self.key(&format!("driver-parks:driver:{driver}")), "s"),
309            None => (self.key("driver-parks"), "z"),
310        };
311        let rows = self
312            .eval_list(LIST_PARKS_SCRIPT, vec![index], vec![self.key("driver-park:"), kind.into()])
313            .await?;
314        let mut parks = rows
315            .iter()
316            .map(|text| decode::<DriverPark>("parked driver call", text))
317            .collect::<Result<Vec<_>>>()?;
318        parks.sort_by_key(|park| park_key(&park.scope, &park.call_id));
319        Ok(parks)
320    }
321
322    async fn delete_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<bool> {
323        let member = Self::park_member(scope, call_id);
324        let keys = vec![self.key(&format!("driver-park:{member}")), self.key("driver-parks")];
325        Ok(self.eval(DELETE_PARK_SCRIPT, keys, vec![member]).await? > 0)
326    }
327}