simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
//! JSON configuration with optional environment prefix (compatible with Go `core/config`).
//!
//! # Features
//!
//! - Load from JSON file or in-memory [`serde_json::Value`]
//! - Environment scopes: [`EnvScope::Test`] / [`EnvScope::Dev`] / [`EnvScope::Prod`]
//! - Dotted path access: `logger.level`
//!
//! # Examples
//!
//! ```
//! use simplejrpc::config::{Config, ConfigBuilder, EnvScope};
//! use serde_json::json;
//!
//! let cfg = ConfigBuilder::new()
//!     .env(EnvScope::Test)
//!     .from_value(json!({
//!         "test": {
//!             "logger": { "level": "info" },
//!             "jsonrpc": { "sockets": "rpc.sock" }
//!         }
//!     }))
//!     .build()
//!     .unwrap();
//!
//! assert_eq!(cfg.get_str("logger.level").unwrap(), "info");
//! assert_eq!(cfg.get_str("jsonrpc.sockets").unwrap(), "rpc.sock");
//!
//! // Without env prefix, use absolute dotted paths:
//! let raw = Config::from_value(json!({"a":{"b":1}}));
//! assert_eq!(raw.get_i64("a.b").unwrap(), 1);
//! ```

use std::fs;
use std::path::{Path, PathBuf};

use serde_json::Value;

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

/// Environment scope prefix applied before dotted paths.
///
/// # Examples
///
/// ```
/// use simplejrpc::config::EnvScope;
/// assert_eq!(EnvScope::default(), EnvScope::None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EnvScope {
    /// Look up under `test.*`.
    Test,
    /// Look up under `dev.*`.
    Dev,
    /// Look up under `prod.*`.
    Prod,
    /// No prefix — paths are absolute from the JSON root.
    #[default]
    None,
}

impl EnvScope {
    /// Prefix segment used in dotted lookups (`test` / `dev` / `prod`), or `None`.
    fn as_str(self) -> Option<&'static str> {
        match self {
            Self::Test => Some("test"),
            Self::Dev => Some("dev"),
            Self::Prod => Some("prod"),
            Self::None => None,
        }
    }
}

/// Fluent builder for [`Config`].
///
/// # Examples
///
/// ```
/// use simplejrpc::config::{ConfigBuilder, EnvScope};
/// use serde_json::json;
/// let cfg = ConfigBuilder::new()
///     .env(EnvScope::Dev)
///     .from_value(json!({"dev":{"n":1}}))
///     .build()
///     .unwrap();
/// assert_eq!(cfg.get_i64("n").unwrap(), 1);
/// ```
#[derive(Debug, Default)]
pub struct ConfigBuilder {
    env: EnvScope,
    value: Option<Value>,
    path: Option<PathBuf>,
}

impl ConfigBuilder {
    /// Create a builder (default env = [`EnvScope::None`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::ConfigBuilder;
    /// let _ = ConfigBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            env: EnvScope::None,
            ..Self::default()
        }
    }

    /// Set the environment scope prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::{ConfigBuilder, EnvScope};
    /// let _ = ConfigBuilder::new().env(EnvScope::Prod);
    /// ```
    pub fn env(mut self, env: EnvScope) -> Self {
        self.env = env;
        self
    }

    /// Load configuration from an in-memory JSON value.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::ConfigBuilder;
    /// use serde_json::json;
    /// let cfg = ConfigBuilder::new().from_value(json!({"x":1})).build().unwrap();
    /// assert_eq!(cfg.get_i64("x").unwrap(), 1);
    /// ```
    pub fn from_value(mut self, v: Value) -> Self {
        self.value = Some(v);
        self
    }

    /// Load configuration from a JSON file path.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use simplejrpc::config::ConfigBuilder;
    /// let cfg = ConfigBuilder::new().from_file("config.json").build().unwrap();
    /// # let _ = cfg;
    /// ```
    pub fn from_file(mut self, path: impl AsRef<Path>) -> Self {
        self.path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Build the [`Config`], reading the file if needed.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] when neither [`Self::from_value`] nor
    /// [`Self::from_file`] was provided.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::ConfigBuilder;
    /// use serde_json::json;
    /// assert!(ConfigBuilder::new().build().is_err());
    /// assert!(ConfigBuilder::new().from_value(json!({})).build().is_ok());
    /// ```
    pub fn build(self) -> Result<Config> {
        let value = if let Some(v) = self.value {
            v
        } else if let Some(path) = self.path {
            let text = fs::read_to_string(path)?;
            serde_json::from_str(&text)?
        } else {
            return Err(Error::Config("no config source".into()));
        };
        Ok(Config {
            env: self.env,
            root: value,
        })
    }
}

/// Loaded configuration with optional env-prefix lookups.
///
/// # Examples
///
/// ```
/// use simplejrpc::config::Config;
/// use serde_json::json;
/// let cfg = Config::from_value(json!({"flag": true}));
/// assert!(cfg.get_bool("flag").unwrap());
/// ```
#[derive(Debug, Clone)]
pub struct Config {
    env: EnvScope,
    root: Value,
}

impl Config {
    /// Wrap a raw JSON value without an env prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::Config;
    /// use serde_json::json;
    /// let cfg = Config::from_value(json!({"k":"v"}));
    /// assert_eq!(cfg.get_str("k").unwrap(), "v");
    /// ```
    pub fn from_value(root: Value) -> Self {
        Self {
            env: EnvScope::None,
            root,
        }
    }

    /// Start a [`ConfigBuilder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::Config;
    /// let _ = Config::builder();
    /// ```
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }

    /// Resolve a dotted path relative to the env prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::Config;
    /// use serde_json::json;
    /// let cfg = Config::from_value(json!({"a":{"b":true}}));
    /// assert_eq!(cfg.get("a.b").unwrap(), &json!(true));
    /// ```
    pub fn get(&self, path: &str) -> Result<&Value> {
        let full = match self.env.as_str() {
            Some(prefix) => format!("{prefix}.{path}"),
            None => path.to_string(),
        };
        lookup(&self.root, &full).ok_or_else(|| Error::Config(format!("key not found: {full}")))
    }

    /// Get a string value at `path`.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::Config;
    /// use serde_json::json;
    /// let cfg = Config::from_value(json!({"name":"zack"}));
    /// assert_eq!(cfg.get_str("name").unwrap(), "zack");
    /// ```
    pub fn get_str(&self, path: &str) -> Result<String> {
        self.get(path)?
            .as_str()
            .map(|s| s.to_string())
            .ok_or_else(|| Error::Config(format!("{path} is not a string")))
    }

    /// Get an `i64` value at `path`.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::Config;
    /// use serde_json::json;
    /// let cfg = Config::from_value(json!({"n":7}));
    /// assert_eq!(cfg.get_i64("n").unwrap(), 7);
    /// ```
    pub fn get_i64(&self, path: &str) -> Result<i64> {
        self.get(path)?
            .as_i64()
            .ok_or_else(|| Error::Config(format!("{path} is not an integer")))
    }

    /// Get a `bool` value at `path`.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::config::Config;
    /// use serde_json::json;
    /// let cfg = Config::from_value(json!({"on":false}));
    /// assert!(!cfg.get_bool("on").unwrap());
    /// ```
    pub fn get_bool(&self, path: &str) -> Result<bool> {
        self.get(path)?
            .as_bool()
            .ok_or_else(|| Error::Config(format!("{path} is not a bool")))
    }
}

/// Walk a JSON object tree by dotted path (`a.b.c`); returns `None` on miss.
fn lookup<'a>(root: &'a Value, dotted: &str) -> Option<&'a Value> {
    let mut cur = root;
    for part in dotted.split('.') {
        cur = cur.get(part)?;
    }
    Some(cur)
}