Messaging
A Redis connection wrapper that validates JSON payloads on write and on read.

vld_data::redis1 wraps a sync or async Redis connection. Values are validated and stored as JSON on write, and decoded and validated on read.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["redis-1"] }
FeatureModule / effect
redis-0vld_data::redis0, redis >=0.32, <1
redis-1vld_data::redis1, redis 1.x
redis-aioAsyncRedisConn over redis::aio::ConnectionLike, for every enabled major
redis-aio-tokioredis-aio plus redis' tokio support (tokio-comp)

Both modules have the same API and can be enabled together. Each re-exports its redis crate as redis, so you do not need a separate dependency. redis refuses to compile aio without a runtime: use redis-aio-tokio, or redis-aio together with a runtime feature (smol-comp, …) on your own redis dependency of the same major. The examples use redis1.

Example

use vld_data::redis1::prelude::*;
use vld_data::redis1::redis;

vld::schema! {
    #[derive(Debug, serde::Serialize)]
    pub struct UserSchema {
        pub name: String => vld::string().min(1).max(100),
        pub email: String => vld::string().email(),
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = redis::Client::open("redis://127.0.0.1/")?;
    let mut conn = RedisConn::new(client.get_connection()?);

    let alice = UserSchema { name: "Alice".into(), email: "alice@example.com".into() };
    conn.set("user:1", &alice)?;
    let loaded: Option<UserSchema> = conn.get("user:1")?;
    assert_eq!(loaded.unwrap().email, "alice@example.com");

    let bad = UserSchema { name: "".into(), email: "nope".into() };
    assert!(matches!(conn.set("user:2", &bad), Err(VldRedisError::Validation(_))));
    Ok(())
}

API

  • RedisConn<C> — sync wrapper over redis::ConnectionLike; new, into_inner, Deref / DerefMut to the connection.
  • AsyncRedisConn<C> (redis-aio) — the same methods, async, over redis::aio::ConnectionLike.
  • Validating commands: set / get, mset / mget, hset / hget, lpush / rpush / lpop / rpop, sadd / smembers, zadd / zrange, publish.
  • VldRedisError — Validation, Serialization, Deserialization, Redis(RedisError).

Gotchas

  • The value type is the schema. Written values must be Serialize + VldParse (a schema! struct with #[derive(serde::Serialize)]); read values are parsed with VldParse.
  • The wrapper's methods shadow redis::Commands / redis::AsyncCommands. conn.get(k) is always the validating JSON get. Commands without a validating version (del, expire, incr, …) go through Deref. To call the native one, use the trait on the inner connection:
    let raw: Option<String> = redis::Commands::get(&mut *conn, "key")?;
    
  • A stored value that is not valid JSON fails with Deserialization; valid JSON that fails the schema fails with Validation.