Skip to main content

adk_kernel/control/store/
redis.rs

1//! The Redis [`ControlStore`] (spec 3.3 §10 K3, K4; feature `redis`).
2
3use 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
13/// The layout version this release writes.
14const LAYOUT: i64 = 1;
15
16/// KEYS: cursors hash, sequence hash. ARGV: field, sequence number, the cursor's JSON.
17/// Stores the cursor unless the stored one is past it, and returns the stored cursor.
18const 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
26/// KEYS: settings hash. ARGV: field, the record read (empty when there was none), the new
27/// record. Stores the new record only while the stored one is still the one read.
28const 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
37/// How often a change is applied again to a record another write changed meanwhile.
38const SWAP_ATTEMPTS: usize = 32;
39
40/// A [`ControlStore`] in Redis, shared by every replica (spec 3.3 §10 K3, K4; feature
41/// `redis`).
42///
43/// Keys sit under the namespace [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless
44/// [`with_namespace`](Self::with_namespace) sets another, inside the hash tag
45/// `{<namespace>}`, so the store's script touches one Redis Cluster slot; braces in the
46/// namespace are percent-encoded.
47///
48/// | Key | Type | Contents |
49/// |-----|------|----------|
50/// | `{<ns>}:area-settings` | Hash | Each area's changed settings as JSON, by partition id |
51/// | `{<ns>}:away-cursors` | Hash | Each viewer's cursor as JSON, by user and viewer |
52/// | `{<ns>}:away-cursor-seqs` | Hash | Each viewer's sequence number, compared by the advance script |
53/// | `{<ns>}:control-layout` | String | The layout version [`migrate`](Self::migrate) recorded |
54///
55/// A cursor advances in one Lua script, which Redis executes atomically, so two concurrent
56/// advances keep the higher; an area's record changes by compare-and-swap in another, so
57/// concurrent changes all hold.
58///
59/// # Example
60///
61/// ```rust,no_run
62/// # async fn example() -> adk_kernel::Result<()> {
63/// let store = adk_kernel::control::RedisControlStore::connect("redis://localhost:6379").await?;
64/// store.migrate().await?;
65/// # Ok(())
66/// # }
67/// ```
68#[derive(Debug, Clone)]
69pub struct RedisControlStore {
70    client: Client,
71    namespace: String,
72}
73
74impl RedisControlStore {
75    /// The namespace keys sit under by default, shared with the other kernel stores.
76    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
77
78    /// A store over an initialized client, such as one shared with the process store.
79    pub fn from_client(client: Client) -> Self {
80        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
81    }
82
83    /// Connects to `url`.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the URL is invalid or
88    /// the server cannot be reached.
89    pub async fn connect(url: &str) -> Result<Self> {
90        Ok(Self::from_client(connect_client(url).await?))
91    }
92
93    /// Keeps the store's keys under `namespace`.
94    #[must_use]
95    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
96        self.namespace = namespace.into();
97        self
98    }
99
100    /// The client the store uses.
101    pub fn client(&self) -> &Client {
102        &self.client
103    }
104
105    /// The namespace the store's keys sit under.
106    pub fn namespace(&self) -> &str {
107        &self.namespace
108    }
109
110    /// Records the store's layout version, refusing a database a newer release wrote.
111    ///
112    /// # Errors
113    ///
114    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the server fails or
115    /// holds a newer layout.
116    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
126/// The hash field of `viewer` of `user`: the unit separator never appears in either.
127fn 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}