vld-data 0.8.0

Database and message-queue integrations for the vld validation library: sqlx, diesel, SeaORM, SurrealDB, redis, lapin
//! The redis integration, written once against `super::redis` and compiled
//! by `redis0.rs` / `redis1.rs` (the two majors share one API here, so there
//! is no `compat` module).

use super::redis;
use std::fmt;
use std::ops::{Deref, DerefMut};

fn encode<V>(value: &V) -> Result<Vec<u8>, VldRedisError>
where
    V: serde::Serialize + vld::schema::VldParse,
{
    let json =
        serde_json::to_value(value).map_err(|e| VldRedisError::Serialization(e.to_string()))?;
    V::vld_parse_value(&json).map_err(VldRedisError::Validation)?;
    serde_json::to_vec(&json).map_err(|e| VldRedisError::Serialization(e.to_string()))
}

fn decode<T: vld::schema::VldParse>(bytes: &[u8]) -> Result<T, VldRedisError> {
    let value: serde_json::Value =
        serde_json::from_slice(bytes).map_err(|e| VldRedisError::Deserialization(e.to_string()))?;
    T::vld_parse_value(&value).map_err(VldRedisError::Validation)
}

fn decode_opt<T: vld::schema::VldParse>(raw: Option<Vec<u8>>) -> Result<Option<T>, VldRedisError> {
    raw.map(|b| decode(&b)).transpose()
}

fn decode_all<T: vld::schema::VldParse>(raw: Vec<Vec<u8>>) -> Result<Vec<T>, VldRedisError> {
    raw.iter().map(|b| decode(b)).collect()
}

macro_rules! wrapper {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        pub struct $name<C> {
            inner: C,
        }

        impl<C> $name<C> {
            /// Wrap a connection.
            pub fn new(inner: C) -> Self {
                Self { inner }
            }

            /// Unwrap the inner connection.
            pub fn into_inner(self) -> C {
                self.inner
            }
        }

        impl<C> Deref for $name<C> {
            type Target = C;

            fn deref(&self) -> &Self::Target {
                &self.inner
            }
        }

        impl<C> DerefMut for $name<C> {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.inner
            }
        }
    };
}

wrapper!(
    /// Sync Redis connection wrapper with validate+JSON behavior.
    ///
    /// Its methods shadow `redis::Commands` methods of the same name; see the
    /// module docs for calling the native ones.
    RedisConn
);

#[cfg(feature = "redis-aio")]
wrapper!(
    /// Async Redis connection wrapper with validate+JSON behavior (feature `redis-aio`,
    /// plus a redis runtime feature such as `redis-aio-tokio`).
    ///
    /// Same methods as [`RedisConn`], but `async`. They shadow
    /// `redis::AsyncCommands` methods of the same name.
    AsyncRedisConn
);

/// Defines every validating command once, for both the sync and async wrapper.
/// Each command builds a `redis::Cmd` (`build`), runs it into `raw`, then maps it.
macro_rules! commands {
    ($(
        $(#[$meta:meta])*
        fn $name:ident<$($gen:tt),*>($($arg:ident: $ty:ty),*) -> $ret:ty
        where [$($bound:tt)*]
        { build: $build:expr, raw: $raw:ty, map: $map:expr $(,)? }
    )*) => {
        impl<C: redis::ConnectionLike> RedisConn<C> {
            $(
                $(#[$meta])*
                pub fn $name<$($gen),*>(&mut self, $($arg: $ty),*) -> Result<$ret, VldRedisError>
                where $($bound)*
                {
                    let cmd: redis::Cmd = $build;
                    let raw: $raw = cmd.query(&mut self.inner)?;
                    ($map)(raw)
                }
            )*
        }

        #[cfg(feature = "redis-aio")]
        impl<C: redis::aio::ConnectionLike> AsyncRedisConn<C> {
            $(
                $(#[$meta])*
                pub async fn $name<$($gen),*>(&mut self, $($arg: $ty),*) -> Result<$ret, VldRedisError>
                where $($bound)*
                {
                    let cmd: redis::Cmd = $build;
                    let raw: $raw = cmd.query_async(&mut self.inner).await?;
                    ($map)(raw)
                }
            )*
        }
    };
}

fn cmd1<A: redis::ToRedisArgs>(name: &str, a: A) -> redis::Cmd {
    let mut c = redis::cmd(name);
    c.arg(a);
    c
}

commands! {
    /// `SET key value`: validate `value`, store it as JSON.
    fn set<K, V>(key: K, value: &V) -> ()
    where [K: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("SET", key); c.arg(encode(value)?); c }, raw: (), map: Ok }

    /// `GET key`: decode and validate the stored JSON (`None` if the key is missing).
    fn get<K, T>(key: K) -> Option<T>
    where [K: redis::ToRedisArgs, T: vld::schema::VldParse]
    { build: cmd1("GET", key), raw: Option<Vec<u8>>, map: decode_opt }

    /// `MSET`: validate every value, then store them all as JSON.
    fn mset<'a, K, V, I>(items: I) -> ()
    where [I: IntoIterator<Item = (K, &'a V)>, K: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse + 'a]
    {
        build: {
            let mut c = redis::cmd("MSET");
            for (key, value) in items {
                c.arg(key).arg(encode(value)?);
            }
            c
        },
        raw: (),
        map: Ok,
    }

    /// `MGET`: decode and validate each stored value (`None` for missing keys).
    fn mget<K, T, I>(keys: I) -> Vec<Option<T>>
    where [I: IntoIterator<Item = K>, K: redis::ToRedisArgs, T: vld::schema::VldParse]
    {
        build: {
            let mut c = redis::cmd("MGET");
            for key in keys {
                c.arg(key);
            }
            c
        },
        raw: Vec<Option<Vec<u8>>>,
        map: |raw: Vec<Option<Vec<u8>>>| raw.into_iter().map(decode_opt).collect(),
    }

    /// `HSET key field value`: validate `value`, store it as JSON.
    fn hset<K, F, V>(key: K, field: F, value: &V) -> ()
    where [K: redis::ToRedisArgs, F: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("HSET", key); c.arg(field).arg(encode(value)?); c }, raw: (), map: Ok }

    /// `HGET key field`: decode and validate the stored JSON.
    fn hget<K, F, T>(key: K, field: F) -> Option<T>
    where [K: redis::ToRedisArgs, F: redis::ToRedisArgs, T: vld::schema::VldParse]
    { build: { let mut c = cmd1("HGET", key); c.arg(field); c }, raw: Option<Vec<u8>>, map: decode_opt }

    /// `LPUSH`: validate `value`, push it as JSON; returns the new list length.
    fn lpush<K, V>(key: K, value: &V) -> usize
    where [K: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("LPUSH", key); c.arg(encode(value)?); c }, raw: usize, map: Ok }

    /// `RPUSH`: validate `value`, push it as JSON; returns the new list length.
    fn rpush<K, V>(key: K, value: &V) -> usize
    where [K: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("RPUSH", key); c.arg(encode(value)?); c }, raw: usize, map: Ok }

    /// `LPOP`: pop and validate the first element (`None` if the list is empty).
    fn lpop<K, T>(key: K) -> Option<T>
    where [K: redis::ToRedisArgs, T: vld::schema::VldParse]
    { build: cmd1("LPOP", key), raw: Option<Vec<u8>>, map: decode_opt }

    /// `RPOP`: pop and validate the last element (`None` if the list is empty).
    fn rpop<K, T>(key: K) -> Option<T>
    where [K: redis::ToRedisArgs, T: vld::schema::VldParse]
    { build: cmd1("RPOP", key), raw: Option<Vec<u8>>, map: decode_opt }

    /// `SADD`: validate `value`, add it as JSON; returns how many were added.
    fn sadd<K, V>(key: K, value: &V) -> usize
    where [K: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("SADD", key); c.arg(encode(value)?); c }, raw: usize, map: Ok }

    /// `SMEMBERS`: decode and validate every member.
    fn smembers<K, T>(key: K) -> Vec<T>
    where [K: redis::ToRedisArgs, T: vld::schema::VldParse]
    { build: cmd1("SMEMBERS", key), raw: Vec<Vec<u8>>, map: decode_all }

    /// `ZADD key score value`: validate `value`, add it as JSON; returns how many were added.
    fn zadd<K, V>(key: K, score: f64, value: &V) -> usize
    where [K: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("ZADD", key); c.arg(score).arg(encode(value)?); c }, raw: usize, map: Ok }

    /// `ZRANGE key start stop`: decode and validate every element in the range.
    fn zrange<K, T>(key: K, start: isize, stop: isize) -> Vec<T>
    where [K: redis::ToRedisArgs, T: vld::schema::VldParse]
    { build: { let mut c = cmd1("ZRANGE", key); c.arg(start).arg(stop); c }, raw: Vec<Vec<u8>>, map: decode_all }

    /// `PUBLISH`: validate `value`, publish it as JSON; returns the number of receivers.
    fn publish<Cn, V>(channel: Cn, value: &V) -> i64
    where [Cn: redis::ToRedisArgs, V: serde::Serialize + vld::schema::VldParse]
    { build: { let mut c = cmd1("PUBLISH", channel); c.arg(encode(value)?); c }, raw: i64, map: Ok }
}

/// Error type of the redis wrappers.
#[derive(Debug)]
pub enum VldRedisError {
    /// The value (written or read) failed schema validation.
    Validation(vld::error::VldError),
    /// The value could not be serialized to JSON.
    Serialization(String),
    /// The stored bytes are not valid JSON.
    Deserialization(String),
    /// The Redis command failed.
    Redis(redis::RedisError),
}

impl fmt::Display for VldRedisError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VldRedisError::Validation(e) => write!(f, "Validation error: {e}"),
            VldRedisError::Serialization(e) => write!(f, "Serialization error: {e}"),
            VldRedisError::Deserialization(e) => write!(f, "Deserialization error: {e}"),
            VldRedisError::Redis(e) => write!(f, "Redis error: {e}"),
        }
    }
}

impl std::error::Error for VldRedisError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            VldRedisError::Validation(e) => Some(e),
            VldRedisError::Redis(e) => Some(e),
            VldRedisError::Serialization(_) | VldRedisError::Deserialization(_) => None,
        }
    }
}

impl From<vld::error::VldError> for VldRedisError {
    fn from(value: vld::error::VldError) -> Self {
        Self::Validation(value)
    }
}

impl From<redis::RedisError> for VldRedisError {
    fn from(value: redis::RedisError) -> Self {
        Self::Redis(value)
    }
}

/// Common imports: the connection wrappers, `VldRedisError` and `vld::prelude`.
pub mod prelude {
    #[cfg(feature = "redis-aio")]
    pub use super::AsyncRedisConn;
    pub use super::{RedisConn, VldRedisError};
    pub use vld::prelude::*;
}