adk_kernel/control/store/
redis.rs1use async_trait::async_trait;
4use fred::prelude::{Client, HashesInterface as _};
5
6use super::{AreaSettings, AwayCursor, ControlStore};
7use crate::error::Result;
8use crate::pairing::redis::{
9 connect_client, decode, eval_count, eval_text, migrate_layout, namespaced, store_error,
10};
11use crate::partition::PartitionId;
12
13const LAYOUT: i64 = 1;
15
16const ADVANCE_SCRIPT: &str = r"
19local stored = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '-1')
20if stored > tonumber(ARGV[2]) then return redis.call('HGET', KEYS[1], ARGV[1]) end
21redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])
22redis.call('HSET', KEYS[2], ARGV[1], ARGV[2])
23return ARGV[3]
24";
25
26const SWAP_SCRIPT: &str = r"
29local stored = redis.call('HGET', KEYS[1], ARGV[1])
30if (stored == false and ARGV[2] == '') or stored == ARGV[2] then
31 redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])
32 return 1
33end
34return 0
35";
36
37const SWAP_ATTEMPTS: usize = 32;
39
40#[derive(Debug, Clone)]
69pub struct RedisControlStore {
70 client: Client,
71 namespace: String,
72}
73
74impl RedisControlStore {
75 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
77
78 pub fn from_client(client: Client) -> Self {
80 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
81 }
82
83 pub async fn connect(url: &str) -> Result<Self> {
90 Ok(Self::from_client(connect_client(url).await?))
91 }
92
93 #[must_use]
95 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
96 self.namespace = namespace.into();
97 self
98 }
99
100 pub fn client(&self) -> &Client {
102 &self.client
103 }
104
105 pub fn namespace(&self) -> &str {
107 &self.namespace
108 }
109
110 pub async fn migrate(&self) -> Result<()> {
117 migrate_layout(&self.client, self.key("control-layout"), LAYOUT, "control", &self.namespace)
118 .await
119 }
120
121 fn key(&self, suffix: &str) -> String {
122 namespaced(&self.namespace, suffix)
123 }
124}
125
126fn cursor_field(user: &str, viewer: &str) -> String {
128 format!("{user}\u{1f}{viewer}")
129}
130
131#[async_trait]
132impl ControlStore for RedisControlStore {
133 async fn area_settings(&self, partition: &PartitionId) -> Result<Option<AreaSettings>> {
134 let text: Option<String> = self
135 .client
136 .hget(self.key("area-settings"), partition.as_str())
137 .await
138 .map_err(|error| store_error("read the area settings", &error))?;
139 text.map(|text| decode("area's settings", &text)).transpose()
140 }
141
142 async fn list_area_settings(&self) -> Result<Vec<AreaSettings>> {
143 let all: std::collections::HashMap<String, String> = self
144 .client
145 .hgetall(self.key("area-settings"))
146 .await
147 .map_err(|error| store_error("list the area settings", &error))?;
148 let mut settings = all
149 .values()
150 .map(|text| decode::<AreaSettings>("area's settings", text))
151 .collect::<Result<Vec<_>>>()?;
152 settings.sort_by(|a, b| a.partition.as_str().cmp(b.partition.as_str()));
153 Ok(settings)
154 }
155
156 async fn put_area_settings(&self, settings: AreaSettings) -> Result<()> {
157 let json = serde_json::to_string(&settings)?;
158 self.client
159 .hset::<(), _, _>(self.key("area-settings"), (settings.partition.as_str(), json))
160 .await
161 .map_err(|error| store_error("write the area settings", &error))
162 }
163
164 async fn update_area_settings(
165 &self,
166 partition: &PartitionId,
167 change: &(dyn for<'a> Fn(&'a mut AreaSettings) + Send + Sync),
168 ) -> Result<AreaSettings> {
169 let key = self.key("area-settings");
170 for _ in 0..SWAP_ATTEMPTS {
171 let read: Option<String> = self
172 .client
173 .hget(&key, partition.as_str())
174 .await
175 .map_err(|error| store_error("read the area settings", &error))?;
176 let mut settings = match &read {
177 Some(text) => decode("area's settings", text)?,
178 None => AreaSettings::new(partition.clone()),
179 };
180 change(&mut settings);
181 let args = vec![
182 partition.as_str().to_string(),
183 read.unwrap_or_default(),
184 serde_json::to_string(&settings)?,
185 ];
186 if eval_count(&self.client, SWAP_SCRIPT, vec![key.clone()], args).await? == 1 {
187 return Ok(settings);
188 }
189 }
190 Err(store_error(
191 "change the area settings",
192 &format!("the settings of area {partition} kept changing; try again"),
193 ))
194 }
195
196 async fn cursor(&self, user: &str, viewer: &str) -> Result<Option<AwayCursor>> {
197 let text: Option<String> = self
198 .client
199 .hget(self.key("away-cursors"), cursor_field(user, viewer))
200 .await
201 .map_err(|error| store_error("read the away cursors", &error))?;
202 text.map(|text| decode("cursor", &text)).transpose()
203 }
204
205 async fn advance_cursor(&self, cursor: AwayCursor) -> Result<AwayCursor> {
206 let keys = vec![self.key("away-cursors"), self.key("away-cursor-seqs")];
207 let args = vec![
208 cursor_field(&cursor.user, &cursor.viewer),
209 cursor.seq.to_string(),
210 serde_json::to_string(&cursor)?,
211 ];
212 let stored = eval_text(&self.client, ADVANCE_SCRIPT, keys, args).await?;
213 match stored {
214 Some(text) => decode("cursor", &text),
215 None => Err(store_error("advance a cursor", &"the script answered nothing")),
216 }
217 }
218}