Skip to main content

adk_kernel/stores/
watermark_redis.rs

1//! The Redis [`CronWatermarkStore`] (spec 3.2 §7.4, §13 Q8, feature `redis`).
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use fred::prelude::{Builder, Client, ClientLike as _, Config, LuaInterface as _};
6use fred::types::Value;
7
8use crate::error::{KernelError, Result};
9use crate::watermark::CronWatermarkStore;
10
11/// The layout version this release writes.
12const LAYOUT: i64 = 1;
13
14/// KEYS: layout. ARGV: this release's layout version. Records it unless the stored one is
15/// newer, and returns the stored one.
16const MIGRATE_SCRIPT: &str = r"
17local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
18local mine = tonumber(ARGV[1])
19if stored > mine then return stored end
20if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
21return mine
22";
23
24/// KEYS: the cursor hash. ARGV: source, cursor in microseconds. Keeps the later cursor and
25/// returns it.
26const ADVANCE_SCRIPT: &str = r"
27local stored = redis.call('HGET', KEYS[1], ARGV[1])
28if (not stored) or tonumber(stored) < tonumber(ARGV[2]) then
29  redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
30  return ARGV[2]
31end
32return stored
33";
34
35/// A [`CronWatermarkStore`] in Redis, shared by every replica (spec 3.2 §7.4, feature
36/// `redis`).
37///
38/// It opens from the URL of `adk-rust serve --store`. Keys sit under the namespace
39/// [`DEFAULT_NAMESPACE`](Self::DEFAULT_NAMESPACE) unless
40/// [`with_namespace`](Self::with_namespace) sets another, inside the hash tag
41/// `{<namespace>}`; braces in the namespace are percent-encoded.
42///
43/// | Key | Type | Contents |
44/// |-----|------|----------|
45/// | `{<ns>}:cron-watermarks` | Hash | Each source's cursor, in microseconds since the Unix epoch |
46/// | `{<ns>}:cron-watermarks:layout` | String | The layout version [`migrate`](Self::migrate) recorded |
47///
48/// An advance is one Lua script, which Redis runs atomically, so the later cursor wins.
49///
50/// # Example
51///
52/// ```rust,no_run
53/// # async fn example() -> adk_kernel::Result<()> {
54/// let store = adk_kernel::RedisCronWatermarkStore::connect("redis://localhost:6379").await?;
55/// store.migrate().await?;
56/// # Ok(())
57/// # }
58/// ```
59#[derive(Debug, Clone)]
60pub struct RedisCronWatermarkStore {
61    client: Client,
62    namespace: String,
63}
64
65impl RedisCronWatermarkStore {
66    /// The namespace keys sit under by default, shared with the other kernel stores.
67    pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
68
69    /// A store over an initialized client, such as one shared with the run store.
70    pub fn from_client(client: Client) -> Self {
71        Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
72    }
73
74    /// Connects to `url`.
75    ///
76    /// # Errors
77    ///
78    /// Returns [`KernelError::Store`] when the URL is invalid or the server cannot be
79    /// reached.
80    pub async fn connect(url: &str) -> Result<Self> {
81        let config =
82            Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
83        let client = Builder::from_config(config)
84            .build()
85            .map_err(|error| store_error("build the Redis client", &error))?;
86        client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
87        Ok(Self::from_client(client))
88    }
89
90    /// Keeps the store's keys under `namespace`.
91    #[must_use]
92    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
93        self.namespace = namespace.into();
94        self
95    }
96
97    /// The client the store uses.
98    pub fn client(&self) -> &Client {
99        &self.client
100    }
101
102    /// The namespace the store's keys sit under.
103    pub fn namespace(&self) -> &str {
104        &self.namespace
105    }
106
107    /// Records the store's layout version, refusing a database a newer release wrote.
108    ///
109    /// # Errors
110    ///
111    /// Returns [`KernelError::Store`] when the server fails or holds a newer layout.
112    pub async fn migrate(&self) -> Result<()> {
113        let stored: i64 = self
114            .client
115            .eval(
116                MIGRATE_SCRIPT,
117                vec![self.key("cron-watermarks:layout")],
118                vec![LAYOUT.to_string()],
119            )
120            .await
121            .map_err(|error| store_error("record the layout version", &error))?;
122        if stored > LAYOUT {
123            return Err(KernelError::Store {
124                backend: "redis",
125                reason: format!(
126                    "the cron watermark keys under {} have layout v{stored}, but this release \
127                     knows up to v{LAYOUT}; upgrade ADK-Rust",
128                    self.namespace
129                ),
130            });
131        }
132        Ok(())
133    }
134
135    /// `{<namespace>}:<suffix>`.
136    fn key(&self, suffix: &str) -> String {
137        let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
138        format!("{{{namespace}}}:{suffix}")
139    }
140}
141
142fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
143    KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
144}
145
146/// The instant a stored cursor names.
147fn instant(value: Value) -> Result<DateTime<Utc>> {
148    let text = value
149        .into_string()
150        .ok_or_else(|| store_error("read a cron watermark", &"the cursor is not text"))?;
151    text.parse::<i64>()
152        .ok()
153        .and_then(DateTime::from_timestamp_micros)
154        .ok_or_else(|| store_error("read a cron watermark", &format!("`{text}` is no cursor")))
155}
156
157#[async_trait]
158impl CronWatermarkStore for RedisCronWatermarkStore {
159    async fn read(&self, source: &str) -> Result<Option<DateTime<Utc>>> {
160        use fred::prelude::HashesInterface as _;
161
162        let value: Value = self
163            .client
164            .hget(self.key("cron-watermarks"), source)
165            .await
166            .map_err(|error| store_error("read a cron watermark", &error))?;
167        if value.is_null() { Ok(None) } else { instant(value).map(Some) }
168    }
169
170    async fn advance(&self, source: &str, cursor: DateTime<Utc>) -> Result<DateTime<Utc>> {
171        let value: Value = self
172            .client
173            .eval(
174                ADVANCE_SCRIPT,
175                vec![self.key("cron-watermarks")],
176                vec![source.to_string(), cursor.timestamp_micros().to_string()],
177            )
178            .await
179            .map_err(|error| store_error("advance a cron watermark", &error))?;
180        instant(value)
181    }
182
183    async fn delete(&self, source: &str) -> Result<bool> {
184        use fred::prelude::HashesInterface as _;
185
186        let removed: i64 = self
187            .client
188            .hdel(self.key("cron-watermarks"), source)
189            .await
190            .map_err(|error| store_error("delete a cron watermark", &error))?;
191        Ok(removed > 0)
192    }
193}