use async_trait::async_trait;
use fred::prelude::{Client, HashesInterface as _};
use super::{AreaSettings, AwayCursor, ControlStore};
use crate::error::Result;
use crate::pairing::redis::{
connect_client, decode, eval_count, eval_text, migrate_layout, namespaced, store_error,
};
use crate::partition::PartitionId;
const LAYOUT: i64 = 1;
const ADVANCE_SCRIPT: &str = r"
local stored = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '-1')
if stored > tonumber(ARGV[2]) then return redis.call('HGET', KEYS[1], ARGV[1]) end
redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])
redis.call('HSET', KEYS[2], ARGV[1], ARGV[2])
return ARGV[3]
";
const SWAP_SCRIPT: &str = r"
local stored = redis.call('HGET', KEYS[1], ARGV[1])
if (stored == false and ARGV[2] == '') or stored == ARGV[2] then
redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])
return 1
end
return 0
";
const SWAP_ATTEMPTS: usize = 32;
#[derive(Debug, Clone)]
pub struct RedisControlStore {
client: Client,
namespace: String,
}
impl RedisControlStore {
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> {
Ok(Self::from_client(connect_client(url).await?))
}
#[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<()> {
migrate_layout(&self.client, self.key("control-layout"), LAYOUT, "control", &self.namespace)
.await
}
fn key(&self, suffix: &str) -> String {
namespaced(&self.namespace, suffix)
}
}
fn cursor_field(user: &str, viewer: &str) -> String {
format!("{user}\u{1f}{viewer}")
}
#[async_trait]
impl ControlStore for RedisControlStore {
async fn area_settings(&self, partition: &PartitionId) -> Result<Option<AreaSettings>> {
let text: Option<String> = self
.client
.hget(self.key("area-settings"), partition.as_str())
.await
.map_err(|error| store_error("read the area settings", &error))?;
text.map(|text| decode("area's settings", &text)).transpose()
}
async fn list_area_settings(&self) -> Result<Vec<AreaSettings>> {
let all: std::collections::HashMap<String, String> = self
.client
.hgetall(self.key("area-settings"))
.await
.map_err(|error| store_error("list the area settings", &error))?;
let mut settings = all
.values()
.map(|text| decode::<AreaSettings>("area's settings", text))
.collect::<Result<Vec<_>>>()?;
settings.sort_by(|a, b| a.partition.as_str().cmp(b.partition.as_str()));
Ok(settings)
}
async fn put_area_settings(&self, settings: AreaSettings) -> Result<()> {
let json = serde_json::to_string(&settings)?;
self.client
.hset::<(), _, _>(self.key("area-settings"), (settings.partition.as_str(), json))
.await
.map_err(|error| store_error("write the area settings", &error))
}
async fn update_area_settings(
&self,
partition: &PartitionId,
change: &(dyn for<'a> Fn(&'a mut AreaSettings) + Send + Sync),
) -> Result<AreaSettings> {
let key = self.key("area-settings");
for _ in 0..SWAP_ATTEMPTS {
let read: Option<String> = self
.client
.hget(&key, partition.as_str())
.await
.map_err(|error| store_error("read the area settings", &error))?;
let mut settings = match &read {
Some(text) => decode("area's settings", text)?,
None => AreaSettings::new(partition.clone()),
};
change(&mut settings);
let args = vec![
partition.as_str().to_string(),
read.unwrap_or_default(),
serde_json::to_string(&settings)?,
];
if eval_count(&self.client, SWAP_SCRIPT, vec![key.clone()], args).await? == 1 {
return Ok(settings);
}
}
Err(store_error(
"change the area settings",
&format!("the settings of area {partition} kept changing; try again"),
))
}
async fn cursor(&self, user: &str, viewer: &str) -> Result<Option<AwayCursor>> {
let text: Option<String> = self
.client
.hget(self.key("away-cursors"), cursor_field(user, viewer))
.await
.map_err(|error| store_error("read the away cursors", &error))?;
text.map(|text| decode("cursor", &text)).transpose()
}
async fn advance_cursor(&self, cursor: AwayCursor) -> Result<AwayCursor> {
let keys = vec![self.key("away-cursors"), self.key("away-cursor-seqs")];
let args = vec![
cursor_field(&cursor.user, &cursor.viewer),
cursor.seq.to_string(),
serde_json::to_string(&cursor)?,
];
let stored = eval_text(&self.client, ADVANCE_SCRIPT, keys, args).await?;
match stored {
Some(text) => decode("cursor", &text),
None => Err(store_error("advance a cursor", &"the script answered nothing")),
}
}
}