Skip to main content

adk_kernel/channels/
redis.rs

1//! The Redis [`ChannelBindingStore`] (spec 3.3 §10 K1; features `channels`, `redis`).
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use fred::prelude::{Client, HashesInterface as _, KeysInterface as _};
6
7use super::{ChannelBinding, ChannelBindingStore, ChannelPairingRequest};
8use crate::error::Result;
9use crate::pairing::redis::{
10    LIST_SCRIPT, PUT_SCRIPT, connect_client, decode, eval_count, eval_list, eval_text,
11    migrate_layout, namespaced, store_error,
12};
13
14/// The layout version this release writes.
15const LAYOUT: i64 = 1;
16
17/// KEYS: request, expiry index, the code's key. ARGV: member, expiry score, the request's
18/// JSON, the code key prefix, the code hash. Replaces the account's request and moves its
19/// code key.
20const PUT_REQUEST_SCRIPT: &str = r"
21local old = redis.call('HGET', KEYS[1], 'code')
22if old then redis.call('DEL', ARGV[4] .. old) end
23redis.call('DEL', KEYS[1])
24redis.call('HSET', KEYS[1], 'json', ARGV[3], 'code', ARGV[5])
25redis.call('SET', KEYS[3], ARGV[1])
26redis.call('ZADD', KEYS[2], ARGV[2], ARGV[1])
27return 1
28";
29
30/// KEYS: the code's key, expiry index. ARGV: request key prefix. Removes and returns the
31/// request the code names, or false.
32const TAKE_REQUEST_SCRIPT: &str = r"
33local member = redis.call('GET', KEYS[1])
34if not member then return false end
35local json = redis.call('HGET', ARGV[1] .. member, 'json')
36redis.call('DEL', ARGV[1] .. member)
37redis.call('DEL', KEYS[1])
38redis.call('ZREM', KEYS[2], member)
39return json or false
40";
41
42/// KEYS: expiry index. ARGV: request key prefix, code key prefix, the highest expiry
43/// removed. Returns how many requests it removed.
44const PRUNE_REQUESTS_SCRIPT: &str = r"
45local members = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[3])
46for _, member in ipairs(members) do
47  local code = redis.call('HGET', ARGV[1] .. member, 'code')
48  if code then redis.call('DEL', ARGV[2] .. code) end
49  redis.call('DEL', ARGV[1] .. member)
50  redis.call('ZREM', KEYS[1], member)
51end
52return #members
53";
54
55/// KEYS: expiry index. ARGV: request key prefix. Returns every request's JSON.
56const LIST_REQUESTS_SCRIPT: &str = r"
57local out = {}
58for _, member in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
59  local json = redis.call('HGET', ARGV[1] .. member, 'json')
60  if json then table.insert(out, json) end
61end
62return out
63";
64
65/// A [`ChannelBindingStore`] in Redis, shared by every replica (spec 3.3 §10 K1, features
66/// `channels`, `redis`).
67///
68/// Keys sit under the namespace [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless
69/// [`with_namespace`](Self::with_namespace) sets another, inside the hash tag
70/// `{<namespace>}`, so the store's scripts touch one Redis Cluster slot.
71///
72/// | Key | Type | Contents |
73/// |-----|------|----------|
74/// | `{<ns>}:channel-binding:<id>` | String | One binding as JSON |
75/// | `{<ns>}:channel-bindings` | Sorted set | Every binding id, scored by its pairing time in microseconds |
76/// | `{<ns>}:channel-request:<member>` | Hash | One pairing request: `json`, and `code`, its code's hash |
77/// | `{<ns>}:channel-requests` | Sorted set | Every request member, scored by its expiry in microseconds |
78/// | `{<ns>}:channel-request-code:<hash>` | String | The request member a code names |
79/// | `{<ns>}:channels-layout` | String | The layout version [`migrate`](Self::migrate) recorded |
80///
81/// A request member is its channel and account, each percent-encoded and joined by `/`, so
82/// no identifier can spill into another key. Every change runs as one Lua script, which
83/// Redis executes atomically.
84///
85/// # Example
86///
87/// ```rust,no_run
88/// # async fn example() -> adk_kernel::Result<()> {
89/// let store = adk_kernel::channels::RedisChannelBindingStore::connect("redis://localhost:6379").await?;
90/// store.migrate().await?;
91/// # Ok(())
92/// # }
93/// ```
94#[derive(Debug, Clone)]
95pub struct RedisChannelBindingStore {
96    client: Client,
97    namespace: String,
98}
99
100/// `text` with every byte outside `[A-Za-z0-9-._~]` percent-encoded.
101fn encode(text: &str) -> String {
102    let mut out = String::with_capacity(text.len());
103    for byte in text.bytes() {
104        if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
105            out.push(byte as char);
106        } else {
107            out.push_str(&format!("%{byte:02X}"));
108        }
109    }
110    out
111}
112
113impl RedisChannelBindingStore {
114    /// The namespace keys sit under by default, shared with the other kernel stores.
115    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
116
117    /// A store over an initialized client, such as one shared with the run store.
118    pub fn from_client(client: Client) -> Self {
119        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
120    }
121
122    /// Connects to `url`.
123    ///
124    /// # Errors
125    ///
126    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the URL is invalid or
127    /// the server cannot be reached.
128    pub async fn connect(url: &str) -> Result<Self> {
129        Ok(Self::from_client(connect_client(url).await?))
130    }
131
132    /// Keeps the store's keys under `namespace`.
133    #[must_use]
134    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
135        self.namespace = namespace.into();
136        self
137    }
138
139    /// The client the store uses.
140    pub fn client(&self) -> &Client {
141        &self.client
142    }
143
144    /// The namespace the store's keys sit under.
145    pub fn namespace(&self) -> &str {
146        &self.namespace
147    }
148
149    /// Records the store's layout version, refusing a database a newer release wrote.
150    ///
151    /// # Errors
152    ///
153    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server fails or
154    /// holds a newer layout.
155    pub async fn migrate(&self) -> Result<()> {
156        migrate_layout(
157            &self.client,
158            self.key("channels-layout"),
159            LAYOUT,
160            "channel",
161            &self.namespace,
162        )
163        .await
164    }
165
166    fn key(&self, suffix: &str) -> String {
167        namespaced(&self.namespace, suffix)
168    }
169
170    fn member(channel: &str, account: &str) -> String {
171        format!("{}/{}", encode(channel), encode(account))
172    }
173}
174
175#[async_trait]
176impl ChannelBindingStore for RedisChannelBindingStore {
177    async fn put_binding(&self, binding: ChannelBinding) -> Result<()> {
178        let keys = vec![
179            self.key(&format!("channel-binding:{}", binding.id)),
180            self.key("channel-bindings"),
181        ];
182        let args = vec![
183            binding.id.clone(),
184            binding.paired_at.timestamp_micros().to_string(),
185            serde_json::to_string(&binding)?,
186        ];
187        eval_count(&self.client, PUT_SCRIPT, keys, args).await?;
188        Ok(())
189    }
190
191    async fn get_binding(&self, id: &str) -> Result<Option<ChannelBinding>> {
192        let text: Option<String> = self
193            .client
194            .get(self.key(&format!("channel-binding:{id}")))
195            .await
196            .map_err(|error| store_error("read the channel binding table", &error))?;
197        text.map(|text| decode("channel binding", &text)).transpose()
198    }
199
200    async fn list_bindings(&self) -> Result<Vec<ChannelBinding>> {
201        let rows = eval_list(
202            &self.client,
203            LIST_SCRIPT,
204            vec![self.key("channel-bindings")],
205            vec![self.key("channel-binding:")],
206        )
207        .await?;
208        rows.iter().map(|text| decode("channel binding", text)).collect()
209    }
210
211    async fn put_request(&self, request: ChannelPairingRequest) -> Result<()> {
212        let member = Self::member(&request.channel, &request.account);
213        let keys = vec![
214            self.key(&format!("channel-request:{member}")),
215            self.key("channel-requests"),
216            self.key(&format!("channel-request-code:{}", request.code_hash)),
217        ];
218        let args = vec![
219            member,
220            request.expires_at.timestamp_micros().to_string(),
221            serde_json::to_string(&request)?,
222            self.key("channel-request-code:"),
223            request.code_hash.clone(),
224        ];
225        eval_count(&self.client, PUT_REQUEST_SCRIPT, keys, args).await?;
226        Ok(())
227    }
228
229    async fn get_request(
230        &self,
231        channel: &str,
232        account: &str,
233    ) -> Result<Option<ChannelPairingRequest>> {
234        let member = Self::member(channel, account);
235        let text: Option<String> = self
236            .client
237            .hget(self.key(&format!("channel-request:{member}")), "json")
238            .await
239            .map_err(|error| store_error("read the channel request table", &error))?;
240        text.map(|text| decode("channel pairing request", &text)).transpose()
241    }
242
243    async fn take_request(&self, code_hash: &str) -> Result<Option<ChannelPairingRequest>> {
244        let keys = vec![
245            self.key(&format!("channel-request-code:{code_hash}")),
246            self.key("channel-requests"),
247        ];
248        let text =
249            eval_text(&self.client, TAKE_REQUEST_SCRIPT, keys, vec![self.key("channel-request:")])
250                .await?;
251        text.map(|text| decode("channel pairing request", &text)).transpose()
252    }
253
254    async fn list_requests(&self) -> Result<Vec<ChannelPairingRequest>> {
255        let rows = eval_list(
256            &self.client,
257            LIST_REQUESTS_SCRIPT,
258            vec![self.key("channel-requests")],
259            vec![self.key("channel-request:")],
260        )
261        .await?;
262        let mut requests = rows
263            .iter()
264            .map(|text| decode::<ChannelPairingRequest>("channel pairing request", text))
265            .collect::<Result<Vec<_>>>()?;
266        requests.sort_by(|a, b| {
267            (a.requested_at, &a.channel, &a.account).cmp(&(b.requested_at, &b.channel, &b.account))
268        });
269        Ok(requests)
270    }
271
272    async fn prune_requests(&self, before: DateTime<Utc>) -> Result<usize> {
273        let args = vec![
274            self.key("channel-request:"),
275            self.key("channel-request-code:"),
276            before.timestamp_micros().to_string(),
277        ];
278        eval_count(&self.client, PRUNE_REQUESTS_SCRIPT, vec![self.key("channel-requests")], args)
279            .await
280    }
281}