adk_kernel/stores/
watermark_redis.rs1use 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
11const LAYOUT: i64 = 1;
13
14const 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
24const 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#[derive(Debug, Clone)]
60pub struct RedisCronWatermarkStore {
61 client: Client,
62 namespace: String,
63}
64
65impl RedisCronWatermarkStore {
66 pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
68
69 pub fn from_client(client: Client) -> Self {
71 Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
72 }
73
74 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 #[must_use]
92 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
93 self.namespace = namespace.into();
94 self
95 }
96
97 pub fn client(&self) -> &Client {
99 &self.client
100 }
101
102 pub fn namespace(&self) -> &str {
104 &self.namespace
105 }
106
107 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 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
146fn 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}