use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::client::ArcadeDbClient;
use crate::error::{ArcadeDbError, Result};
use crate::proto::com::arcadedb::grpc::ExecuteCommandResponse;
use crate::{GrpcValue, Kind};
#[derive(Clone)]
pub struct Cache {
client: ArcadeDbClient,
}
impl Cache {
pub(crate) fn new(client: ArcadeDbClient) -> Self {
Self { client }
}
pub async fn raw(&self, database: &str, command: &str) -> Result<Option<String>> {
Ok(first_scalar(&self.command(database, command).await?))
}
pub async fn raw_batch(&self, database: &str, commands: &str) -> Result<Vec<Option<String>>> {
let resp = self.command(database, commands).await?;
let Some(list) = resp.records.first().and_then(|rec| {
rec.properties.values().next().and_then(|v| match &v.kind {
Some(Kind::ListValue(list)) => Some(list),
_ => None,
})
}) else {
return Err(ArcadeDbError::InvalidInput {
message: format!(
"raw_batch: unexpected response shape (expected a per-command \
result array, got {:?})",
resp.records
.first()
.and_then(|rec| rec.properties.values().next())
),
});
};
Ok(list.values.iter().map(value_to_string).collect())
}
pub async fn set(
&self,
database: &str,
key: &str,
value: &str,
ttl: Option<Duration>,
) -> Result<()> {
self.store(database, key, &value, ttl).await
}
pub async fn get(&self, database: &str, key: &str) -> Result<Option<String>> {
self.load(database, key).await
}
pub async fn set_json<T: Serialize>(
&self,
database: &str,
key: &str,
value: &T,
ttl: Option<Duration>,
) -> Result<()> {
self.store(database, key, value, ttl).await
}
pub async fn get_json<T: DeserializeOwned>(
&self,
database: &str,
key: &str,
) -> Result<Option<T>> {
self.load(database, key).await
}
pub async fn getdel(&self, database: &str, key: &str) -> Result<Option<String>> {
self.consume(database, key).await
}
pub async fn getdel_json<T: DeserializeOwned>(
&self,
database: &str,
key: &str,
) -> Result<Option<T>> {
self.consume(database, key).await
}
pub async fn exists(&self, database: &str, key: &str) -> Result<bool> {
validate_key(key)?;
let v = self.raw(database, &format!("EXISTS {key}")).await?;
Ok(v.as_deref() == Some("1"))
}
pub async fn incr(&self, database: &str, key: &str) -> Result<i64> {
validate_key(key)?;
let v = self
.raw(database, &format!("INCR {key}"))
.await?
.ok_or_else(|| ArcadeDbError::CommandFailed {
operation: "cache incr".into(),
message: format!("INCR `{key}` returned no value"),
affected: None,
})?;
v.parse().map_err(|_| ArcadeDbError::InvalidInput {
message: format!("cache incr: `{key}` holds a non-integer value ({v:?})"),
})
}
async fn command(&self, database: &str, command: &str) -> Result<ExecuteCommandResponse> {
self.client
.execute_language(database, "redis", command)
.await
}
async fn store<T: Serialize>(
&self,
database: &str,
key: &str,
value: &T,
ttl: Option<Duration>,
) -> Result<()> {
validate_key(key)?;
let envelope = Envelope {
stored_at_epoch: unix_now(),
ttl_secs: ttl.map_or(u64::MAX, |d| d.as_secs()),
payload: value,
};
let bytes = serde_json::to_vec(&envelope).map_err(|e| ArcadeDbError::InvalidInput {
message: format!("cache set `{key}`: payload serialization failed: {e}"),
})?;
let encoded = encode_hex(&bytes);
self.command(database, &set_command(key, &encoded, ttl))
.await?;
Ok(())
}
async fn load<T: DeserializeOwned>(&self, database: &str, key: &str) -> Result<Option<T>> {
validate_key(key)?;
let Some(encoded) = self.raw(database, &format!("GET {key}")).await? else {
return Ok(None);
};
let bytes = match decode_hex(&encoded) {
Ok(bytes) => bytes,
Err(e) => return Ok(self.heal(database, key, format!("hex decode: {e}")).await),
};
match serde_json::from_slice::<Envelope<T>>(&bytes) {
Ok(envelope) if !envelope.expired() => Ok(Some(envelope.payload)),
Ok(_) => Ok(self.heal(database, key, "expired".into()).await),
Err(e) => Ok(self
.heal(database, key, format!("envelope decode: {e}"))
.await),
}
}
async fn consume<T: DeserializeOwned>(&self, database: &str, key: &str) -> Result<Option<T>> {
validate_key(key)?;
let Some(encoded) = self.raw(database, &format!("GETDEL {key}")).await? else {
return Ok(None);
};
let decoded = decode_hex(&encoded)
.map_err(|e| format!("hex decode: {e}"))
.and_then(|bytes| {
serde_json::from_slice::<Envelope<T>>(&bytes)
.map_err(|e| format!("envelope decode: {e}"))
});
match decoded {
Ok(envelope) => Ok(Some(envelope.payload)),
Err(why) => {
tracing::warn!(
key,
why,
"consumed cache entry undecodable — treating as miss"
);
Ok(None)
}
}
}
async fn heal<T>(&self, database: &str, key: &str, why: String) -> Option<T> {
tracing::warn!(key, why, "cache entry self-heal: consuming via GETDEL");
if let Err(e) = self.command(database, &format!("GETDEL {key}")).await {
tracing::warn!(key, %e, "cache entry self-heal cleanup failed");
}
None
}
}
fn set_command(key: &str, encoded: &str, _ttl: Option<Duration>) -> String {
format!("SET {key} {encoded}")
}
#[derive(Serialize, Deserialize)]
struct Envelope<T> {
stored_at_epoch: u64,
ttl_secs: u64,
payload: T,
}
impl<T> Envelope<T> {
fn expired(&self) -> bool {
self.stored_at_epoch.saturating_add(self.ttl_secs) <= unix_now()
}
}
fn unix_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn validate_key(key: &str) -> Result<()> {
let valid = !key.is_empty()
&& key
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | ':' | '.' | '-'));
if valid {
Ok(())
} else {
Err(ArcadeDbError::InvalidInput {
message: format!(
"cache key `{key}`: expected non-empty [A-Za-z0-9_:.] and `-` only \
(the Redis command tokenizer splits on whitespace; newline is the batch separator)"
),
})
}
}
fn value_to_string(v: &GrpcValue) -> Option<String> {
match &v.kind {
Some(Kind::StringValue(s)) => Some(s.clone()),
Some(Kind::Int64Value(n)) => Some(n.to_string()),
Some(Kind::Int32Value(n)) => Some(n.to_string()),
_ => None,
}
}
fn first_scalar(resp: &ExecuteCommandResponse) -> Option<String> {
resp.records
.first()
.and_then(|rec| rec.properties.values().find_map(value_to_string))
}
fn encode_hex(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
out
}
fn decode_hex(s: &str) -> std::result::Result<Vec<u8>, String> {
fn nibble(c: u8) -> std::result::Result<u8, String> {
match c {
b'0'..=b'9' => Ok(c - b'0'),
b'a'..=b'f' => Ok(c - b'a' + 10),
_ => Err(format!("invalid hex byte {c:#04x}")),
}
}
let bytes = s.as_bytes();
if !bytes.len().is_multiple_of(2) {
return Err(format!("odd hex length {}", bytes.len()));
}
bytes
.chunks(2)
.map(|pair| Ok(nibble(pair[0])? << 4 | nibble(pair[1])?))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_charset_rejects_tokenizer_breakers() {
for good in ["feed:page:123", "k", "A-b.c_9", "probe_cache:abc"] {
validate_key(good).unwrap_or_else(|e| panic!("`{good}` must be valid: {e}"));
}
for bad in [
"",
"has space",
"line\nbreak",
"tab\tchar",
"quote\"d",
"semi;colon",
] {
assert!(
validate_key(bad).is_err(),
"`{bad}` must be rejected before the wire"
);
}
}
#[test]
fn hex_round_trip_and_garbage_rejection() {
let payload = b"{\"title\":\"Space Game, \"quoted\"\":1}";
assert_eq!(decode_hex(&encode_hex(payload)).unwrap(), payload);
assert!(decode_hex("zz").is_err());
assert!(decode_hex("abc").is_err());
}
#[test]
fn envelope_expiry_logic() {
let now = unix_now();
let fresh = Envelope {
stored_at_epoch: now - 10,
ttl_secs: 60,
payload: (),
};
let stale = Envelope {
stored_at_epoch: now - 61,
ttl_secs: 60,
payload: (),
};
let zero_ttl = Envelope {
stored_at_epoch: now,
ttl_secs: 0,
payload: (),
};
let no_expiry = Envelope {
stored_at_epoch: now - 10_000,
ttl_secs: u64::MAX,
payload: (),
};
assert!(!fresh.expired());
assert!(stale.expired());
assert!(zero_ttl.expired(), "0 = evict on read");
assert!(!no_expiry.expired(), "u64::MAX = never (saturating_add)");
}
#[test]
fn envelope_json_round_trips_payload_types() {
for bytes in [
serde_json::to_vec(&Envelope {
stored_at_epoch: 1,
ttl_secs: 2,
payload: "s",
})
.unwrap(),
serde_json::to_vec(&Envelope {
stored_at_epoch: 1,
ttl_secs: 2,
payload: vec![1i64, 2],
})
.unwrap(),
] {
let re: Envelope<serde_json::Value> =
serde_json::from_slice(&bytes).expect("envelope shape is self-describing");
assert_eq!(re.stored_at_epoch, 1);
}
}
#[test]
fn set_command_omits_ex_today() {
assert_eq!(
set_command("k", "deadbeef", Some(Duration::from_secs(60))),
"SET k deadbeef"
);
}
#[test]
fn batch_shape_decodes_per_command_scalars() {
use crate::encode::{list_v, str_v};
let resp = ExecuteCommandResponse {
records: vec![crate::rec(
"redis",
vec![("value", list_v([str_v("OK"), str_v("3331")]))],
)],
..Default::default()
};
let decoded: Vec<Option<String>> = resp
.records
.first()
.and_then(|rec| rec.properties.values().next())
.and_then(|v| match &v.kind {
Some(Kind::ListValue(list)) => {
Some(list.values.iter().map(value_to_string).collect())
}
_ => None,
})
.expect("batch responses carry the per-command array");
assert_eq!(decoded, vec![Some("OK".into()), Some("3331".into())]);
}
#[test]
fn first_scalar_fishes_the_wire_shapes() {
use crate::encode::{i64_v, str_v};
let resp = |v| ExecuteCommandResponse {
records: vec![crate::rec("redis", vec![("value", v)])],
..Default::default()
};
assert_eq!(first_scalar(&resp(str_v("OK"))), Some("OK".to_string()));
assert_eq!(first_scalar(&resp(i64_v(1))), Some("1".to_string()));
let empty = ExecuteCommandResponse::default();
assert_eq!(first_scalar(&empty), None);
}
}