mod commands;
#[cfg(test)]
mod tests;
pub mod types;
use std::sync::{Arc, OnceLock};
use encore_sdk_core::cache::{self as core_cache, Access, Client, redis as rs};
use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;
pub use self::commands::{
Scan, ScanOptions, bitmap, generic, geo, hash, hyperloglog, list, pubsub, set, sorted_set,
stream, string,
};
pub use self::types::{
FromRedisValue, Increment, Json, Popped, PoppedMany, PoppedScored, PoppedScoredMany,
ToRedisArgs, Value,
};
pub use rs::{Direction, ExistenceCheck, Expiry, SetExpiry, SetOptions};
use self::commands::Cmd;
pub struct Database {
name: &'static str,
#[allow(dead_code)]
persistent: bool,
client: OnceLock<Arc<Client>>,
readers: [OnceLock<Arc<Client>>; 2],
}
impl Database {
pub const fn new(name: &'static str) -> Self {
Self {
name,
persistent: false,
client: OnceLock::new(),
readers: [OnceLock::new(), OnceLock::new()],
}
}
pub const fn named(name: &'static str) -> Self {
Self::new(name)
}
pub const fn persistent(mut self) -> Self {
self.persistent = true;
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn write(&'static self) -> DatabaseRef {
DatabaseRef { db: self }
}
pub const fn read(&'static self) -> ReadOnlyDatabaseRef {
ReadOnlyDatabaseRef {
db: self,
access: Access::Read,
}
}
pub const fn read_primary(&'static self) -> ReadOnlyDatabaseRef {
ReadOnlyDatabaseRef {
db: self,
access: Access::ReadPrimary,
}
}
fn client(&self) -> Result<Arc<Client>, Error> {
if let Some(client) = self.client.get() {
return Ok(client.clone());
}
if let Some(test) = testing::active()? {
return test.redis_client(self.name);
}
let client = core()
.cache()
.cluster(&self.name.into())
.client()
.map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?;
let _ = self.client.set(Arc::new(client));
Ok(self.client.get().expect("client just set").clone())
}
fn client_for(&self, access: Access) -> Result<Arc<Client>, Error> {
let slot = match access {
Access::ReadWrite => return self.client(),
Access::Read => &self.readers[0],
Access::ReadPrimary => &self.readers[1],
};
if let Some(reader) = slot.get() {
return Ok(reader.clone());
}
let client = self.client()?;
let reader = Arc::new(
client
.with_access(access)
.map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?,
);
if !self
.client
.get()
.is_some_and(|own| Arc::ptr_eq(own, &client))
{
return Ok(reader);
}
let _ = slot.set(reader);
Ok(slot.get().expect("reader just set").clone())
}
}
#[derive(Clone, Copy)]
pub struct DatabaseRef {
db: &'static Database,
}
#[derive(Clone, Copy)]
pub struct ReadOnlyDatabaseRef {
db: &'static Database,
access: Access,
}
macro_rules! groups {
($form:ident<$lt:lifetime>, |$this:ident| $target:expr) => {
groups!(@each $form<$lt>, |$this| $target;
generic,
string,
bitmap,
hash,
list,
set,
sorted_set,
geo,
stream,
hyperloglog,
pubsub,
);
};
(@each $form:ident<$lt:lifetime>, |$this:ident| $target:expr; $($(#[$doc:meta])* $group:ident,)*) => {
$(
$(#[$doc])*
pub fn $group(&self) -> $group::$form<$lt> {
let $this = self;
$group::$form { target: $target }
}
)*
};
}
macro_rules! queues {
() => {
queues!(@each generic, string, bitmap, hash, list, set, sorted_set, geo, stream, hyperloglog, pubsub);
};
(@each $($group:ident),*) => {
$(
pub fn $group(&mut self) -> $group::Queue<'_> {
$group::Queue { queue: &mut self.queued }
}
)*
pub fn script(&mut self, script: &'static Script) -> QueuedInvocation<'_> {
QueuedInvocation {
queue: &mut self.queued,
script,
keys: Vec::new(),
args: Vec::new(),
}
}
pub fn command(&mut self, name: &'static str) -> QueuedCommandInvocation<'_> {
QueuedCommandInvocation {
queue: &mut self.queued,
cmd: core_cache::Command::raw(name),
}
}
pub fn len(&self) -> usize {
self.queued.commands.len()
}
pub fn is_empty(&self) -> bool {
self.queued.commands.is_empty()
}
};
}
macro_rules! writer_methods {
($lt:lifetime, |$this:ident| $db:expr) => {
groups!(Commands<$lt>, |$this| Target::Database(
$db,
Access::ReadWrite
));
pub fn pipeline(&self) -> Pipeline<$lt> {
let $this = self;
Pipeline {
target: Target::Database($db, Access::ReadWrite),
queued: Queued::default(),
}
}
pub fn transaction(&self) -> Transaction<$lt> {
let $this = self;
Transaction {
target: Target::Database($db, Access::ReadWrite),
queued: Queued::default(),
}
}
pub async fn acquire(&self) -> Result<Connection, Error> {
let $this = self;
let client = ($db).client()?;
let inner = client.acquire().await.map_err(redis_err)?;
Ok(Connection {
inner: tokio::sync::Mutex::new(inner),
client,
})
}
pub async fn watch<T>(
&self,
keys: impl ToRedisArgs,
mut body: impl AsyncFnMut(&Connection, &mut WatchedTransaction<'_>) -> Result<T, Error>,
) -> Result<T, Error> {
const ATTEMPTS: usize = 64;
let keys = keys.to_redis_args();
let conn = self.acquire().await?;
for _ in 0..ATTEMPTS {
conn.watch(&keys).await?;
let mut tx = conn.transaction();
let out = body(&conn, &mut tx).await?;
if tx.exec::<Value>().await?.is_some() {
return Ok(out);
}
}
Err(Error::new(
ErrCode::Aborted,
format!("watched keys kept changing; gave up after {ATTEMPTS} attempts"),
))
}
pub fn script(&self, script: &'static Script) -> Invocation<$lt> {
let $this = self;
Invocation {
target: Target::Database($db, Access::ReadWrite),
script,
read_only: false,
keys: Vec::new(),
args: Vec::new(),
}
}
pub fn command(&self, name: &'static str) -> CommandInvocation<$lt> {
let $this = self;
CommandInvocation {
target: Target::Database($db, Access::ReadWrite),
cmd: core_cache::Command::raw(name),
}
}
pub fn connection_string(&self) -> Result<String, Error> {
let $this = self;
Ok(($db).client()?.connection_url())
}
};
}
impl Database {
writer_methods!('_, |this| this);
}
impl DatabaseRef {
writer_methods!('static, |this| this.db);
}
impl ReadOnlyDatabaseRef {
groups!(ReadCommands<'static>, |this| Target::Database(
this.db,
this.access
));
pub fn command(&self, name: &'static str) -> CommandInvocation<'static> {
CommandInvocation {
target: Target::Database(self.db, self.access),
cmd: core_cache::Command::raw(name).read_only(),
}
}
pub fn script(&self, script: &'static Script) -> Invocation<'static> {
Invocation {
target: Target::Database(self.db, self.access),
script,
read_only: true,
keys: Vec::new(),
args: Vec::new(),
}
}
}
#[derive(Clone, Copy)]
pub(crate) enum Target<'a> {
Database(&'a Database, Access),
Connection(&'a Connection),
}
impl Target<'_> {
fn client(&self) -> Result<Arc<Client>, Error> {
match self {
Target::Database(db, access) => db.client_for(*access),
Target::Connection(conn) => Ok(conn.client.clone()),
}
}
async fn reply(self, cmd: &core_cache::Command) -> Result<Value, core_cache::OpError> {
match self {
Target::Database(db, access) => match db.client_for(access) {
Ok(client) => client.execute(cmd).await,
Err(err) => Err(unavailable(cmd, err)),
},
Target::Connection(conn) => conn.inner.lock().await.execute(cmd).await,
}
}
pub(crate) async fn run<T: FromRedisValue>(self, cmd: Cmd) -> Result<T, Error> {
let value = self.reply(&cmd.inner).await.map_err(redis_err)?;
T::from_redis_value(value)
}
async fn run_all(self, queued: Queued, atomic: bool) -> Result<Option<Value>, Error> {
let commands: Vec<core_cache::Command> = queued
.commands
.iter()
.map(|cmd| cmd.inner.clone())
.collect();
let client = self.client()?;
let replies = match self {
Target::Database(..) => Some(client.execute_all(&commands, atomic).await),
Target::Connection(conn) => conn
.inner
.lock()
.await
.execute_all(&commands, atomic)
.await
.transpose(),
};
let Some(replies) = replies else {
return Ok(None);
};
let replies = replies.map_err(redis_err)?;
Ok(Some(Value::Array(replies)))
}
}
fn unavailable(cmd: &core_cache::Command, err: Error) -> core_cache::OpError {
core_cache::OpError::new(
cmd.operation(),
"",
core_cache::Error::Redis(std::io::Error::other(err.message).into()),
)
}
#[derive(Default)]
pub(crate) struct Queued {
commands: Vec<Cmd>,
}
impl Queued {
pub(crate) fn push(&mut self, cmd: Cmd) {
self.commands.push(cmd);
}
}
pub struct Pipeline<'a> {
target: Target<'a>,
queued: Queued,
}
impl Pipeline<'_> {
queues!();
pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
let replies = self.target.run_all(self.queued, false).await?;
T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
}
}
pub struct Transaction<'a> {
target: Target<'a>,
queued: Queued,
}
impl Transaction<'_> {
queues!();
pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
let replies = self.target.run_all(self.queued, true).await?;
T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
}
pub fn discard(self) {}
}
pub struct WatchedTransaction<'a> {
target: Target<'a>,
queued: Queued,
}
impl WatchedTransaction<'_> {
queues!();
pub async fn exec<T: FromRedisValue>(&mut self) -> Result<Option<T>, Error> {
let queued = std::mem::take(&mut self.queued);
match self.target.run_all(queued, true).await? {
Some(replies) => T::from_redis_value(replies).map(Some),
None => Ok(None),
}
}
}
pub struct Connection {
inner: tokio::sync::Mutex<core_cache::Connection>,
client: Arc<Client>,
}
impl Connection {
groups!(Commands<'_>, |this| Target::Connection(this));
pub async fn watch(&self, keys: impl ToRedisArgs) -> Result<(), Error> {
self.inner
.lock()
.await
.watch(&keys.to_redis_args())
.await
.map_err(redis_err)
}
pub async fn unwatch(&self) -> Result<(), Error> {
self.inner.lock().await.unwatch().await.map_err(redis_err)
}
pub fn transaction(&self) -> WatchedTransaction<'_> {
WatchedTransaction {
target: Target::Connection(self),
queued: Queued::default(),
}
}
pub fn pipeline(&self) -> Pipeline<'_> {
Pipeline {
target: Target::Connection(self),
queued: Queued::default(),
}
}
pub fn command(&self, name: &'static str) -> CommandInvocation<'_> {
CommandInvocation {
target: Target::Connection(self),
cmd: core_cache::Command::raw(name),
}
}
pub fn script(&self, script: &'static Script) -> Invocation<'_> {
Invocation {
target: Target::Connection(self),
script,
read_only: false,
keys: Vec::new(),
args: Vec::new(),
}
}
}
pub struct Script {
source: &'static str,
read_only: bool,
hash: OnceLock<String>,
}
impl Script {
pub const fn new(source: &'static str) -> Self {
Self {
source,
read_only: false,
hash: OnceLock::new(),
}
}
pub const fn read_only(source: &'static str) -> Self {
Self {
source,
read_only: true,
hash: OnceLock::new(),
}
}
fn hash(&self) -> &str {
self.hash
.get_or_init(|| rs::Script::new(self.source).get_hash().to_string())
}
fn command(&self, by_hash: bool, keys: &[Vec<u8>], args: &[Vec<u8>]) -> core_cache::Command {
let name = match (by_hash, self.read_only) {
(true, false) => "EVALSHA",
(true, true) => "EVALSHA_RO",
(false, false) => "EVAL",
(false, true) => "EVAL_RO",
};
let mut cmd = core_cache::Command::new("script", name, !self.read_only)
.arg(if by_hash { self.hash() } else { self.source })
.arg(keys.len().to_string());
for key in keys {
cmd = cmd.key(key.as_slice());
}
for arg in args {
cmd = cmd.arg(arg.as_slice());
}
cmd
}
}
pub struct Invocation<'a> {
target: Target<'a>,
script: &'static Script,
read_only: bool,
keys: Vec<Vec<u8>>,
args: Vec<Vec<u8>>,
}
impl Invocation<'_> {
pub fn key(mut self, key: impl ToRedisArgs) -> Self {
self.keys.extend(key.to_redis_args());
self
}
pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
self.args.extend(arg.to_redis_args());
self
}
pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
if self.read_only && !self.script.read_only {
return Err(Error::new(
ErrCode::FailedPrecondition,
"read-only handles can only run scripts declared with `Script::read_only`",
));
}
let by_hash = self.script.command(true, &self.keys, &self.args);
let value = match self.target.reply(&by_hash).await {
Ok(value) => value,
Err(err) if is_no_script(&err) => {
let by_source = self.script.command(false, &self.keys, &self.args);
self.target.reply(&by_source).await.map_err(redis_err)?
}
Err(err) => return Err(redis_err(err)),
};
T::from_redis_value(value)
}
}
pub struct QueuedInvocation<'a> {
queue: &'a mut Queued,
script: &'static Script,
keys: Vec<Vec<u8>>,
args: Vec<Vec<u8>>,
}
impl QueuedInvocation<'_> {
pub fn key(mut self, key: impl ToRedisArgs) -> Self {
self.keys.extend(key.to_redis_args());
self
}
pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
self.args.extend(arg.to_redis_args());
self
}
pub fn queue(self) {
let inner = self.script.command(false, &self.keys, &self.args);
self.queue.push(Cmd::from_core(inner));
}
}
pub struct CommandInvocation<'a> {
target: Target<'a>,
cmd: core_cache::Command,
}
impl CommandInvocation<'_> {
pub fn key(mut self, key: impl ToRedisArgs) -> Self {
for key in key.to_redis_args() {
self.cmd = self.cmd.key(key);
}
self
}
pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
for arg in arg.to_redis_args() {
self.cmd = self.cmd.arg(arg);
}
self
}
pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
let value = self.target.reply(&self.cmd).await.map_err(redis_err)?;
T::from_redis_value(value)
}
}
pub struct QueuedCommandInvocation<'a> {
queue: &'a mut Queued,
cmd: core_cache::Command,
}
impl QueuedCommandInvocation<'_> {
pub fn key(mut self, key: impl ToRedisArgs) -> Self {
for key in key.to_redis_args() {
self.cmd = self.cmd.key(key);
}
self
}
pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
for arg in arg.to_redis_args() {
self.cmd = self.cmd.arg(arg);
}
self
}
pub fn queue(self) {
self.queue.push(Cmd::from_core(self.cmd));
}
}
fn is_no_script(err: &core_cache::OpError) -> bool {
matches!(
&err.source,
core_cache::Error::Redis(err)
if err.kind() == rs::ErrorKind::Server(rs::ServerErrorKind::NoScript)
)
}
fn redis_err(err: core_cache::OpError) -> Error {
Error::wrap(redis_err_code(&err.source), err)
}
fn redis_err_code(err: &core_cache::Error) -> ErrCode {
let err = match err {
core_cache::Error::Refused(_) => return ErrCode::InvalidArgument,
core_cache::Error::PoolTimeout => return ErrCode::Unavailable,
core_cache::Error::Redis(err) => err,
};
if let Some(code) = err.code() {
return match code {
"EXECABORT" | "BUSYKEY" => ErrCode::Aborted,
"LOADING" | "BUSY" | "TRYAGAIN" | "CLUSTERDOWN" | "MASTERDOWN" => ErrCode::Unavailable,
"NOPERM" => ErrCode::PermissionDenied,
_ => ErrCode::Internal,
};
}
match err.kind() {
rs::ErrorKind::Client | rs::ErrorKind::InvalidClientConfig => ErrCode::InvalidArgument,
rs::ErrorKind::Parse | rs::ErrorKind::UnexpectedReturnType => ErrCode::Internal,
_ => ErrCode::Unavailable,
}
}