use async_trait::async_trait;
use fred::prelude::{
Builder, Client, ClientLike as _, Config, KeysInterface as _, LuaInterface as _,
SetsInterface as _,
};
use fred::types::Value;
use crate::error::{KernelError, Result};
use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
const LAYOUT: i64 = 1;
const MIGRATE_SCRIPT: &str = r"
local stored = tonumber(redis.call('GET', KEYS[1]) or '0')
local mine = tonumber(ARGV[1])
if stored > mine then return stored end
if stored < mine then redis.call('SET', KEYS[1], ARGV[1]) end
return mine
";
const PUT_SCRIPT: &str = r"
redis.call('SET', KEYS[1], ARGV[2])
redis.call('ZADD', KEYS[2], 0, ARGV[1])
return 1
";
const DELETE_SCRIPT: &str = r"
local existed = redis.call('DEL', KEYS[1])
redis.call('ZREM', KEYS[2], ARGV[1])
return existed
";
const LIST_SCRIPT: &str = r"
local out = {}
for _, id in ipairs(redis.call('ZRANGE', KEYS[1], 0, -1)) do
local record = redis.call('GET', ARGV[1] .. id)
if record then table.insert(out, record) end
end
return out
";
const RECORD_SCRIPT: &str = r"
redis.call('SET', KEYS[1], ARGV[3])
for i = 2, 4 do redis.call('ZADD', KEYS[i], ARGV[2], ARGV[1]) end
return 1
";
const CROSSINGS_SCRIPT: &str = r"
local out = {}
for _, id in ipairs(redis.call('ZRANGEBYSCORE', KEYS[1], ARGV[2], '+inf')) do
local record = redis.call('GET', ARGV[1] .. id)
if record then table.insert(out, record) end
end
return out
";
const RELEASE_SCRIPT: &str = r"
local held = redis.call('SCARD', KEYS[1])
redis.call('DEL', KEYS[1])
return held
";
#[derive(Debug, Clone)]
pub struct RedisPartitionStore {
client: Client,
namespace: String,
}
impl RedisPartitionStore {
pub const DEFAULT_NAMESPACE: &'static str = "adk:kernel";
pub fn from_client(client: Client) -> Self {
Self { client, namespace: Self::DEFAULT_NAMESPACE.to_string() }
}
pub async fn connect(url: &str) -> Result<Self> {
let config =
Config::from_url(url).map_err(|error| store_error("parse the Redis URL", &error))?;
let client = Builder::from_config(config)
.build()
.map_err(|error| store_error("build the Redis client", &error))?;
client.init().await.map_err(|error| store_error("connect to Redis", &error))?;
Ok(Self::from_client(client))
}
#[must_use]
pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
self.namespace = namespace.into();
self
}
pub fn client(&self) -> &Client {
&self.client
}
pub fn namespace(&self) -> &str {
&self.namespace
}
pub async fn migrate(&self) -> Result<()> {
let stored: i64 = self
.client
.eval(MIGRATE_SCRIPT, vec![self.key("partitions:layout")], vec![LAYOUT.to_string()])
.await
.map_err(|error| store_error("record the layout version", &error))?;
if stored > LAYOUT {
return Err(KernelError::Store {
backend: "redis",
reason: format!(
"the partition keys under {} have layout v{stored}, but this release \
knows up to v{LAYOUT}; upgrade ADK-Rust",
self.namespace
),
});
}
Ok(())
}
fn key(&self, suffix: &str) -> String {
let namespace = self.namespace.replace('{', "%7B").replace('}', "%7D");
format!("{{{namespace}}}:{suffix}")
}
async fn strings(
&self,
script: &str,
keys: Vec<String>,
args: Vec<String>,
) -> Result<Vec<String>> {
let reply: Value = self
.client
.eval(script, keys, args)
.await
.map_err(|error| store_error("read the partition table", &error))?;
reply
.into_array()
.into_iter()
.map(|value| {
value
.into_string()
.ok_or_else(|| store_error("read the partition table", &"a record is not text"))
})
.collect()
}
}
fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
KernelError::Store { backend: "redis", reason: format!("could not {action}: {error}") }
}
fn corrupt(what: &str, error: &serde_json::Error) -> KernelError {
KernelError::Store { backend: "redis", reason: format!("a stored {what} is corrupt: {error}") }
}
#[async_trait]
impl PartitionStore for RedisPartitionStore {
async fn put(&self, partition: Partition) -> Result<()> {
let record = serde_json::to_string(&partition)?;
let id = partition.id.as_str().to_string();
let keys = vec![self.key(&format!("partition:{id}")), self.key("partitions")];
self.client
.eval::<i64, _, _, _>(PUT_SCRIPT, keys, vec![id, record])
.await
.map_err(|error| store_error("write the partition table", &error))?;
Ok(())
}
async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
let record: Option<String> = self
.client
.get(self.key(&format!("partition:{id}")))
.await
.map_err(|error| store_error("read the partition table", &error))?;
record
.map(|record| serde_json::from_str(&record).map_err(|e| corrupt("partition", &e)))
.transpose()
}
async fn list(&self) -> Result<Vec<Partition>> {
let records = self
.strings(LIST_SCRIPT, vec![self.key("partitions")], vec![self.key("partition:")])
.await?;
records
.iter()
.map(|record| serde_json::from_str(record).map_err(|e| corrupt("partition", &e)))
.collect()
}
async fn delete(&self, id: &PartitionId) -> Result<bool> {
let keys = vec![self.key(&format!("partition:{id}")), self.key("partitions")];
let existed: i64 = self
.client
.eval(DELETE_SCRIPT, keys, vec![id.as_str().to_string()])
.await
.map_err(|error| store_error("delete from the partition table", &error))?;
Ok(existed > 0)
}
async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
let json = serde_json::to_string(&record)?;
let keys = vec![
self.key(&format!("crossing:{}", record.id)),
self.key("crossings"),
self.key(&format!("crossings:run:{}", record.run)),
self.key(&format!("crossings:from:{}", record.from)),
];
let args = vec![record.id.clone(), record.at.timestamp_micros().to_string(), json];
self.client
.eval::<i64, _, _, _>(RECORD_SCRIPT, keys, args)
.await
.map_err(|error| store_error("record a crossing", &error))?;
Ok(())
}
async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
let walk = match (&filter.run, &filter.from) {
(Some(run), _) => self.key(&format!("crossings:run:{run}")),
(None, Some(from)) => self.key(&format!("crossings:from:{from}")),
(None, None) => self.key("crossings"),
};
let least = filter
.since
.map_or_else(|| "-inf".to_string(), |since| since.timestamp_micros().to_string());
let records =
self.strings(CROSSINGS_SCRIPT, vec![walk], vec![self.key("crossing:"), least]).await?;
let mut out = Vec::new();
for record in records {
let record: CrossingRecord =
serde_json::from_str(&record).map_err(|e| corrupt("crossing record", &e))?;
if filter.matches(&record) {
out.push(record);
}
if filter.limit.is_some_and(|limit| out.len() >= limit) {
break;
}
}
Ok(out)
}
async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
self.client
.sadd::<i64, _, _>(self.key(&format!("crossing-grants:{run}")), fingerprint)
.await
.map_err(|error| store_error("record a crossing grant", &error))?;
Ok(())
}
async fn grants(&self, run: &str) -> Result<Vec<String>> {
let mut grants: Vec<String> = self
.client
.smembers(self.key(&format!("crossing-grants:{run}")))
.await
.map_err(|error| store_error("read the crossing grants", &error))?;
grants.sort();
Ok(grants)
}
async fn release_run(&self, run: &str) -> Result<u64> {
let held: i64 = self
.client
.eval(
RELEASE_SCRIPT,
vec![self.key(&format!("crossing-grants:{run}"))],
Vec::<String>::new(),
)
.await
.map_err(|error| store_error("release the crossing grants", &error))?;
Ok(u64::try_from(held).unwrap_or(0))
}
}