1use 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
14const LAYOUT: i64 = 1;
16
17const 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
30const 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
42const 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
55const 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#[derive(Debug, Clone)]
95pub struct RedisChannelBindingStore {
96 client: Client,
97 namespace: String,
98}
99
100fn 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 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
116
117 pub fn from_client(client: Client) -> Self {
119 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
120 }
121
122 pub async fn connect(url: &str) -> Result<Self> {
129 Ok(Self::from_client(connect_client(url).await?))
130 }
131
132 #[must_use]
134 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
135 self.namespace = namespace.into();
136 self
137 }
138
139 pub fn client(&self) -> &Client {
141 &self.client
142 }
143
144 pub fn namespace(&self) -> &str {
146 &self.namespace
147 }
148
149 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}