simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
//! Lightweight validation (Go `core/gvalid` subset), designed for extension.
//!
//! ## Design
//!
//! - Built-in presets live in [`FieldRule`] (`Required` / `MinLength` / `Range`).
//! - **Any** type can become a rule by implementing [`Rule`].
//! - [`Validator`] stores `Arc<dyn Rule>`, so application crates can add rules
//!   (password strength, email, regex, …) without changing this SDK.
//!
//! Prefer [`Validator`] for reusable rule sets, or [`crate::validate_object!`]
//! for one-off checks.
//!
//! # Examples
//!
//! ## Built-in rules
//!
//! ```
//! use simplejrpc::valid::{FieldRule, Validator};
//! use serde_json::json;
//!
//! let v = Validator::new()
//!     .field("username", FieldRule::Required)
//!     .field("username", FieldRule::MinLength(3))
//!     .field("age", FieldRule::Range { min: 18, max: 100 });
//!
//! assert!(v.validate(&json!({"username":"zack","age":22})).is_ok());
//! assert!(v.validate(&json!({"username":"ab","age":22})).is_err());
//! ```
//!
//! ## Custom rule (e.g. Password) in an application crate
//!
//! ```
//! use simplejrpc::valid::{FieldRule, Rule, Validator};
//! use serde_json::Value;
//!
//! /// Application-defined password policy (not part of the SDK enum).
//! #[derive(Debug, Clone)]
//! struct Password {
//!     min_len: usize,
//!     require_digit: bool,
//! }
//!
//! impl Rule for Password {
//!     fn check(&self, value: Option<&Value>) -> Result<(), String> {
//!         let Some(Value::String(s)) = value else {
//!             return Err("must be a string".into());
//!         };
//!         if s.len() < self.min_len {
//!             return Err(format!("min length is {}", self.min_len));
//!         }
//!         if self.require_digit && !s.chars().any(|c| c.is_ascii_digit()) {
//!             return Err("must contain a digit".into());
//!         }
//!         Ok(())
//!     }
//! }
//!
//! let v = Validator::new()
//!     .field("password", FieldRule::Required)
//!     .field("password", Password { min_len: 8, require_digit: true });
//!
//! assert!(v.validate(&serde_json::json!({"password": "secret12"})).is_ok());
//! assert!(v.validate(&serde_json::json!({"password": "short"})).is_err());
//! assert!(v.validate(&serde_json::json!({"password": "nodigits"})).is_err());
//! ```
//!
//! ## Closure rule
//!
//! ```
//! use simplejrpc::valid::{rule_fn, Validator};
//! use serde_json::json;
//!
//! let v = Validator::new().field(
//!     "role",
//!     rule_fn(|v| match v.and_then(|x| x.as_str()) {
//!         Some("admin" | "user") => Ok(()),
//!         _ => Err("must be admin or user".into()),
//!     }),
//! );
//! assert!(v.validate(&json!({"role": "admin"})).is_ok());
//! assert!(v.validate(&json!({"role": "guest"})).is_err());
//! ```
//!
//! ## Macro registration (built-in or custom)
//!
//! ```
//! use simplejrpc::{validate_object, valid::FieldRule};
//! use serde_json::json;
//!
//! let err = validate_object!(
//!     &json!({"name": ""}),
//!     "name" => FieldRule::Required,
//!     "name" => FieldRule::MinLength(1),
//! );
//! assert!(err.is_err());
//! ```

use std::sync::Arc;

use serde_json::Value;

use crate::error::{Error, Result};

/// Extension point for field validation.
///
/// App-defined rules (password, email, …) implement this
/// (password, email, regex, domain-specific enums, …).
///
/// # Examples
///
/// See the [module-level “Custom rule” example](crate::valid).
pub trait Rule: Send + Sync {
    /// Check one JSON value (`None` if the key is missing).
    ///
    /// Return `Ok(())` on success, or `Err(reason)` with a short English fragment
    /// (the [`Validator`] prefixes it with `"{field}: "`).
    fn check(&self, value: Option<&Value>) -> std::result::Result<(), String>;
}

/// Built-in rule presets (closed set kept small on purpose).
///
/// For anything domain-specific (e.g. password policy), implement [`Rule`] on
/// your own type instead of extending this enum.
///
/// # Examples
///
/// ```
/// use simplejrpc::valid::{FieldRule, Validator};
/// use serde_json::json;
///
/// let v = Validator::new().field("n", FieldRule::Range { min: 1, max: 3 });
/// assert!(v.validate(&json!({"n": 2})).is_ok());
/// assert!(v.validate(&json!({"n": 9})).is_err());
/// ```
#[derive(Debug, Clone)]
pub enum FieldRule {
    /// Value must be present and non-null / non-empty string or non-empty array.
    Required,
    /// Minimum string length in **UTF-8 bytes** (`str::len`), not Unicode scalars
    /// or grapheme clusters. Prefer a custom [`Rule`] for character-count policies.
    MinLength(usize),
    /// Numeric inclusive range for JSON integers (`as_i64`).
    Range {
        /// Inclusive lower bound.
        min: i64,
        /// Inclusive upper bound.
        max: i64,
    },
}

impl Rule for FieldRule {
    fn check(&self, value: Option<&Value>) -> std::result::Result<(), String> {
        match self {
            Self::Required => match value {
                None | Some(Value::Null) => Err("is required".into()),
                Some(Value::String(s)) if s.is_empty() => Err("is required".into()),
                Some(Value::Array(a)) if a.is_empty() => Err("is required".into()),
                _ => Ok(()),
            },
            Self::MinLength(n) => match value.and_then(|x| x.as_str()) {
                Some(s) if s.len() >= *n => Ok(()),
                Some(_) => Err(format!("min length is {n}")),
                None => Err("must be a string".into()),
            },
            Self::Range { min, max } => match value.and_then(|x| x.as_i64()) {
                Some(i) if i >= *min && i <= *max => Ok(()),
                Some(_) => Err(format!("must be in [{min}, {max}]")),
                None => Err("must be an integer".into()),
            },
        }
    }
}

/// Wrap a closure as a [`Rule`].
///
/// # Examples
///
/// ```
/// use simplejrpc::valid::{rule_fn, Rule};
/// use serde_json::json;
///
/// let r = rule_fn(|v| match v.and_then(|x| x.as_bool()) {
///     Some(true) => Ok(()),
///     _ => Err("must be true".into()),
/// });
/// assert!(r.check(Some(&json!(true))).is_ok());
/// ```
pub fn rule_fn<F>(f: F) -> impl Rule
where
    F: Fn(Option<&Value>) -> std::result::Result<(), String> + Send + Sync,
{
    RuleFn(f)
}

/// Closure adapter implementing [`Rule`].
struct RuleFn<F>(F);

impl<F> Rule for RuleFn<F>
where
    F: Fn(Option<&Value>) -> std::result::Result<(), String> + Send + Sync,
{
    fn check(&self, value: Option<&Value>) -> std::result::Result<(), String> {
        (self.0)(value)
    }
}

/// Validator holding an ordered list of field rules.
///
/// Rules are evaluated in registration order; all failures are collected into
/// a single [`Error::Validation`] message.
///
/// # Examples
///
/// ```
/// use simplejrpc::valid::{FieldRule, Validator};
/// use serde_json::json;
///
/// let v = Validator::new()
///     .field("id", FieldRule::Required)
///     .field("id", FieldRule::MinLength(1));
/// assert!(v.validate(&json!({"id": "x"})).is_ok());
/// ```
#[derive(Default, Clone)]
pub struct Validator {
    rules: Vec<(String, Arc<dyn Rule>)>,
}

impl Validator {
    /// Create an empty validator (no rules → always succeeds).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::valid::Validator;
    /// use serde_json::json;
    /// assert!(Validator::new().validate(&json!({})).is_ok());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a rule for `name` (fluent builder).
    ///
    /// Accepts any [`Rule`]: built-in [`FieldRule`], a custom type, or
    /// [`rule_fn`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::valid::{FieldRule, Validator};
    /// let _ = Validator::new().field("user", FieldRule::Required);
    /// ```
    pub fn field(mut self, name: impl Into<String>, rule: impl Rule + 'static) -> Self {
        self.rules.push((name.into(), Arc::new(rule)));
        self
    }

    /// Validate a JSON object against all registered rules.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Validation`] with a `; `-joined list of field failures.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::valid::{FieldRule, Validator};
    /// use serde_json::json;
    ///
    /// let v = Validator::new().field("age", FieldRule::Range { min: 0, max: 120 });
    /// assert!(v.validate(&json!({"age": -1})).is_err());
    /// ```
    pub fn validate(&self, obj: &Value) -> Result<()> {
        let mut errors = Vec::new();
        for (field, rule) in &self.rules {
            if let Err(msg) = rule.check(obj.get(field)) {
                errors.push(format!("{field}: {msg}"));
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(Error::Validation(errors.join("; ")))
        }
    }
}