Skip to main content

adk_kernel/pairing/
redis.rs

1//! The Redis [`DeviceStore`] (spec 3.3 §10 K2; feature `redis`).
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use fred::prelude::{
6    Builder, Client, ClientLike as _, Config, KeysInterface as _, LuaInterface as _,
7};
8use fred::types::Value;
9
10use super::{AttachmentHolder, DeviceAttachment, DeviceRecord, DeviceStore, PairingCode};
11use crate::error::{KernelError, Result};
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.
18pub(crate) const 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: record, index. ARGV: member, score, the record's JSON.
27pub(crate) const PUT_SCRIPT: &str = r"
28redis.call('SET', KEYS[1], ARGV[3])
29redis.call('ZADD', KEYS[2], ARGV[2], ARGV[1])
30return 1
31";
32
33/// KEYS: record, index. ARGV: member. Removes and returns the record, or false.
34pub(crate) const TAKE_SCRIPT: &str = r"
35local json = redis.call('GET', KEYS[1])
36if not json then return false end
37redis.call('DEL', KEYS[1])
38redis.call('ZREM', KEYS[2], ARGV[1])
39return json
40";
41
42/// KEYS: index. ARGV: record key prefix, the highest score removed (`+inf` for every
43/// member). Returns how many records it removed.
44pub(crate) const PRUNE_SCRIPT: &str = r"
45local members = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[2])
46for _, member in ipairs(members) do
47  redis.call('DEL', ARGV[1] .. member)
48  redis.call('ZREM', KEYS[1], member)
49end
50return #members
51";
52
53/// Writes an attachment into its holder's hash of its kind, and notes the kind: `ARGV[4]` is
54/// `1` to write only when absent. Returns whether it wrote.
55const PUT_ATTACHMENT_SCRIPT: &str = r"
56local wrote = 1
57if ARGV[4] == '1' then
58  wrote = redis.call('HSETNX', KEYS[1], ARGV[1], ARGV[2])
59else
60  redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
61end
62if wrote == 1 then redis.call('SADD', KEYS[2], ARGV[3]) end
63return wrote
64";
65
66const LIST_ATTACHMENTS_SCRIPT: &str = r"
67return redis.call('HVALS', KEYS[1])
68";
69
70const REMOVE_ATTACHMENT_SCRIPT: &str = r"
71return redis.call('HDEL', KEYS[1], ARGV[1])
72";
73
74/// Removes every hash of a holder's kinds, and the kinds; returns how many attachments went.
75const REMOVE_ATTACHMENTS_SCRIPT: &str = r"
76local removed = 0
77for _, kind in ipairs(redis.call('SMEMBERS', KEYS[1])) do
78  local hash = ARGV[1] .. kind
79  removed = removed + redis.call('HLEN', hash)
80  redis.call('DEL', hash)
81end
82redis.call('DEL', KEYS[1])
83return removed
84";
85
86/// KEYS: index. ARGV: record key prefix. Returns every record's JSON in index order.
87pub(crate) const LIST_SCRIPT: &str = r"
88local out = {}
89for _, member in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
90  local json = redis.call('GET', ARGV[1] .. member)
91  if json then table.insert(out, json) end
92end
93return out
94";
95
96/// A [`DeviceStore`] in Redis, shared by every replica (spec 3.3 §10 K2, feature `redis`).
97///
98/// Keys sit under the namespace [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless
99/// [`with_namespace`](Self::with_namespace) sets another, inside the hash tag
100/// `{<namespace>}`, so the store's scripts touch one Redis Cluster slot; braces in the
101/// namespace are percent-encoded.
102///
103/// | Key | Type | Contents |
104/// |-----|------|----------|
105/// | `{<ns>}:device:<id>` | String | One device's record as JSON |
106/// | `{<ns>}:devices` | Sorted set | Every device id, scored by its pairing time in microseconds |
107/// | `{<ns>}:pairing-code:<hash>` | String | One waiting code's record as JSON |
108/// | `{<ns>}:pairing-codes` | Sorted set | Every waiting code's hash, scored by its expiry in microseconds |
109/// | `{<ns>}:pairing-attempts` | String | The count of claims since the last code was issued or claimed |
110/// | `{<ns>}:devices-layout` | String | The layout version [`migrate`](Self::migrate) recorded |
111/// | `{<ns>}:attachments:<holder hex>:<kind>` | Hash | One holder's attachments of one kind, each key's record as JSON |
112/// | `{<ns>}:attachment-kinds:<holder hex>` | Set | The kinds a holder has attachments of, so a revocation removes every one |
113///
114/// Device ids are hex and code hashes are SHA-256 hex, so no identifier can spill into
115/// another key. Every change runs as one Lua script, which Redis executes atomically, so
116/// two claims of one code take it once.
117///
118/// # Example
119///
120/// ```rust,no_run
121/// # async fn example() -> adk_kernel::Result<()> {
122/// let store = adk_kernel::pairing::RedisDeviceStore::connect("redis://localhost:6379").await?;
123/// store.migrate().await?;
124/// # Ok(())
125/// # }
126/// ```
127#[derive(Debug, Clone)]
128pub struct RedisDeviceStore {
129    client: Client,
130    namespace: String,
131}
132
133pub(crate) fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
134    KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
135}
136
137pub(crate) fn decode<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
138    serde_json::from_str(text).map_err(|error| KernelError::Store {
139        backend: "redis",
140        reason: format!("a stored {what} is corrupt: {error}"),
141    })
142}
143
144/// `{<namespace>}:<suffix>`, braces in the namespace percent-encoded.
145pub(crate) fn namespaced(namespace: &str, suffix: &str) -> String {
146    let namespace = namespace.replace('{', "%7B").replace('}', "%7D");
147    format!("{{{namespace}}}:{suffix}")
148}
149
150/// Connects a client to `url`.
151pub(crate) async fn connect_client(url: &str) -> Result<Client> {
152    let config =
153        Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
154    let client = Builder::from_config(config)
155        .build()
156        .map_err(|error| store_error("build the Redis client", &error))?;
157    client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
158    Ok(client)
159}
160
161/// Records layout `layout` under `key`, refusing one a newer release wrote.
162pub(crate) async fn migrate_layout(
163    client: &Client,
164    key: String,
165    layout: i64,
166    what: &str,
167    namespace: &str,
168) -> Result<()> {
169    let stored: i64 = client
170        .eval(MIGRATE_SCRIPT, vec![key], vec![layout.to_string()])
171        .await
172        .map_err(|error| store_error("record the layout version", &error))?;
173    if stored > layout {
174        return Err(KernelError::Store {
175            backend: "redis",
176            reason: format!(
177                "the {what} keys under {namespace} have layout v{stored}, but this release knows \
178                 up to v{layout}; upgrade ADK-Rust"
179            ),
180        });
181    }
182    Ok(())
183}
184
185/// Runs `script` and reads its answer as a list of text.
186pub(crate) async fn eval_list(
187    client: &Client,
188    script: &str,
189    keys: Vec<String>,
190    args: Vec<String>,
191) -> Result<Vec<String>> {
192    let reply: Value =
193        client.eval(script, keys, args).await.map_err(|error| store_error("list", &error))?;
194    reply
195        .into_array()
196        .into_iter()
197        .map(|value| value.into_string().ok_or_else(|| store_error("list", &"a value is not text")))
198        .collect()
199}
200
201/// Runs `script` and reads its answer as optional text.
202pub(crate) async fn eval_text(
203    client: &Client,
204    script: &str,
205    keys: Vec<String>,
206    args: Vec<String>,
207) -> Result<Option<String>> {
208    let reply: Value =
209        client.eval(script, keys, args).await.map_err(|error| store_error("read", &error))?;
210    Ok(match reply {
211        Value::Null | Value::Boolean(false) => None,
212        other => other.into_string(),
213    })
214}
215
216/// Runs `script` and reads its answer as a count.
217pub(crate) async fn eval_count(
218    client: &Client,
219    script: &str,
220    keys: Vec<String>,
221    args: Vec<String>,
222) -> Result<usize> {
223    let count: i64 =
224        client.eval(script, keys, args).await.map_err(|error| store_error("write", &error))?;
225    Ok(usize::try_from(count).unwrap_or_default())
226}
227
228impl RedisDeviceStore {
229    /// The namespace keys sit under by default, shared with the other kernel stores.
230    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
231
232    /// A store over an initialized client, such as one shared with the run store.
233    pub fn from_client(client: Client) -> Self {
234        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
235    }
236
237    /// Connects to `url`.
238    ///
239    /// # Errors
240    ///
241    /// Returns [`KernelError::Store`] when the URL is invalid or the server cannot be
242    /// reached.
243    pub async fn connect(url: &str) -> Result<Self> {
244        Ok(Self::from_client(connect_client(url).await?))
245    }
246
247    /// Keeps the store's keys under `namespace`.
248    #[must_use]
249    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
250        self.namespace = namespace.into();
251        self
252    }
253
254    /// The client the store uses.
255    pub fn client(&self) -> &Client {
256        &self.client
257    }
258
259    /// The namespace the store's keys sit under.
260    pub fn namespace(&self) -> &str {
261        &self.namespace
262    }
263
264    /// Records the store's layout version, refusing a database a newer release wrote.
265    ///
266    /// # Errors
267    ///
268    /// Returns [`KernelError::Store`] when the server fails or holds a newer layout.
269    pub async fn migrate(&self) -> Result<()> {
270        migrate_layout(&self.client, self.key("devices-layout"), LAYOUT, "device", &self.namespace)
271            .await
272    }
273
274    fn key(&self, suffix: &str) -> String {
275        namespaced(&self.namespace, suffix)
276    }
277
278    /// The prefix of `holder`'s attachment hashes, one per kind; the holder is hex-encoded, so
279    /// no holder's prefix is another's.
280    fn attachments_prefix(&self, holder: &AttachmentHolder) -> String {
281        self.key(&format!("attachments:{}:", hex_of(&holder.key())))
282    }
283
284    fn attachment_kinds(&self, holder: &AttachmentHolder) -> String {
285        self.key(&format!("attachment-kinds:{}", hex_of(&holder.key())))
286    }
287
288    async fn write_attachment(
289        &self,
290        attachment: DeviceAttachment,
291        only_if_absent: bool,
292    ) -> Result<bool> {
293        let keys = vec![
294            format!("{}{}", self.attachments_prefix(&attachment.holder), attachment.kind),
295            self.attachment_kinds(&attachment.holder),
296        ];
297        let args = vec![
298            attachment.key.clone(),
299            serde_json::to_string(&attachment)?,
300            attachment.kind.clone(),
301            if only_if_absent { "1" } else { "0" }.to_string(),
302        ];
303        Ok(eval_count(&self.client, PUT_ATTACHMENT_SCRIPT, keys, args).await? == 1)
304    }
305}
306
307fn hex_of(text: &str) -> String {
308    text.bytes().map(|byte| format!("{byte:02x}")).collect()
309}
310
311#[async_trait]
312impl DeviceStore for RedisDeviceStore {
313    async fn put_code(&self, code: PairingCode) -> Result<()> {
314        let keys =
315            vec![self.key(&format!("pairing-code:{}", code.code_hash)), self.key("pairing-codes")];
316        let args = vec![
317            code.code_hash.clone(),
318            code.expires_at.timestamp_micros().to_string(),
319            serde_json::to_string(&code)?,
320        ];
321        eval_count(&self.client, PUT_SCRIPT, keys, args).await?;
322        Ok(())
323    }
324
325    async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>> {
326        let keys = vec![self.key(&format!("pairing-code:{code_hash}")), self.key("pairing-codes")];
327        let text = eval_text(&self.client, TAKE_SCRIPT, keys, vec![code_hash.to_string()]).await?;
328        text.map(|text| decode("pairing code", &text)).transpose()
329    }
330
331    async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize> {
332        let args = vec![self.key("pairing-code:"), before.timestamp_micros().to_string()];
333        eval_count(&self.client, PRUNE_SCRIPT, vec![self.key("pairing-codes")], args).await
334    }
335
336    async fn clear_codes(&self) -> Result<usize> {
337        let args = vec![self.key("pairing-code:"), "+inf".to_string()];
338        eval_count(&self.client, PRUNE_SCRIPT, vec![self.key("pairing-codes")], args).await
339    }
340
341    async fn put_device(&self, device: DeviceRecord) -> Result<()> {
342        let keys = vec![self.key(&format!("device:{}", device.id)), self.key("devices")];
343        let args = vec![
344            device.id.clone(),
345            device.created_at.timestamp_micros().to_string(),
346            serde_json::to_string(&device)?,
347        ];
348        eval_count(&self.client, PUT_SCRIPT, keys, args).await?;
349        Ok(())
350    }
351
352    async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>> {
353        let text: Option<String> = self
354            .client
355            .get(self.key(&format!("device:{id}")))
356            .await
357            .map_err(|error| store_error("read the device table", &error))?;
358        text.map(|text| decode("device", &text)).transpose()
359    }
360
361    async fn list_devices(&self) -> Result<Vec<DeviceRecord>> {
362        let rows = eval_list(
363            &self.client,
364            LIST_SCRIPT,
365            vec![self.key("devices")],
366            vec![self.key("device:")],
367        )
368        .await?;
369        rows.iter().map(|text| decode("device", text)).collect()
370    }
371
372    async fn count_claim_attempt(&self) -> Result<u64> {
373        let count: i64 = self
374            .client
375            .incr(self.key("pairing-attempts"))
376            .await
377            .map_err(|error| store_error("count a pairing claim", &error))?;
378        Ok(u64::try_from(count).unwrap_or_default())
379    }
380
381    async fn reset_claim_attempts(&self) -> Result<()> {
382        let _: () = self
383            .client
384            .set(self.key("pairing-attempts"), 0, None, None, false)
385            .await
386            .map_err(|error| store_error("reset the count of pairing claims", &error))?;
387        Ok(())
388    }
389
390    async fn put_attachment(&self, attachment: DeviceAttachment) -> Result<()> {
391        self.write_attachment(attachment, false).await?;
392        Ok(())
393    }
394
395    async fn put_attachment_if_absent(&self, attachment: DeviceAttachment) -> Result<bool> {
396        self.write_attachment(attachment, true).await
397    }
398
399    async fn attachments(
400        &self,
401        holder: &AttachmentHolder,
402        kind: &str,
403    ) -> Result<Vec<DeviceAttachment>> {
404        let hash = format!("{}{kind}", self.attachments_prefix(holder));
405        let rows = eval_list(&self.client, LIST_ATTACHMENTS_SCRIPT, vec![hash], Vec::new()).await?;
406        let mut attachments: Vec<DeviceAttachment> =
407            rows.iter().map(|text| decode("attachment", text)).collect::<Result<_>>()?;
408        attachments.sort_by(|a, b| a.key.cmp(&b.key));
409        Ok(attachments)
410    }
411
412    async fn remove_attachment(
413        &self,
414        holder: &AttachmentHolder,
415        kind: &str,
416        key: &str,
417    ) -> Result<bool> {
418        let hash = format!("{}{kind}", self.attachments_prefix(holder));
419        let removed =
420            eval_count(&self.client, REMOVE_ATTACHMENT_SCRIPT, vec![hash], vec![key.to_string()])
421                .await?;
422        Ok(removed > 0)
423    }
424
425    async fn remove_attachments(&self, holder: &AttachmentHolder) -> Result<usize> {
426        eval_count(
427            &self.client,
428            REMOVE_ATTACHMENTS_SCRIPT,
429            vec![self.attachment_kinds(holder)],
430            vec![self.attachments_prefix(holder)],
431        )
432        .await
433    }
434}