simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
//! Application response envelope (`gsock.Response`).
//!
//! JSON-RPC **result** payload shape:
//!
//! ```json
//! { "code": 200, "msg": "OK", "data": ..., "meta": { "endpoint": "ping", "close": 0 } }
//! ```
//!
//! Like the Go library, handler failures are usually returned **inside** this
//! envelope as a successful JSON-RPC `result` (not as a JSON-RPC `error` object).
//!
//! # Examples
//!
//! ```
//! use simplejrpc::AppResponse;
//! use serde_json::json;
//!
//! let ok = AppResponse::ok(json!({"pong": true}))
//!     .with_endpoint("ping")
//!     .with_close(0);
//! assert_eq!(ok.code, 200);
//! assert_eq!(ok.meta.endpoint, "ping");
//!
//! let err = AppResponse::error(400, "bad params").with_message("invalid");
//! assert!(err.data.is_null());
//! assert_eq!(err.message, "invalid");
//! ```

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Envelope metadata (`endpoint`, `close`).
///
/// ```
/// use simplejrpc::response::Meta;
/// let m = Meta { endpoint: "ping".into(), close: 0 };
/// assert_eq!(m.close, 0);
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Meta {
    /// Method / endpoint name recorded for clients and logs.
    #[serde(default)]
    pub endpoint: String,
    /// `0` keep the connection open, `1` hint the peer may close after this message.
    #[serde(default)]
    pub close: i32,
}

/// Read helpers for [`AppResponse`] wrappers.
///
/// # Examples
///
///
/// ```
/// use simplejrpc::response::{AppResponse, AppResponseView, Meta};
/// use serde_json::{json, Value};
///
/// struct Sanitized(AppResponse);
///
/// impl AppResponseView for Sanitized {
///     fn code(&self) -> i32 { self.0.code }
///     fn data(&self) -> &Value { &self.0.data }
///     fn message(&self) -> &str {
///         if self.0.code >= 500 { "internal error" } else { &self.0.message }
///     }
///     fn meta(&self) -> &Meta { &self.0.meta }
/// }
///
/// let s = Sanitized(AppResponse::error(500, "db panic"));
/// assert_eq!(AppResponseView::message(&s), "internal error");
/// assert_eq!(s.to_app_response().message, "internal error");
/// ```
pub trait AppResponseView: Send + Sync {
    /// Status code (`200`, `404`, or a `200xxx` business code).
    fn code(&self) -> i32;
    /// Payload (`data`).
    fn data(&self) -> &Value;
    /// Message (`msg`).
    fn message(&self) -> &str;
    /// Meta block.
    fn meta(&self) -> &Meta;

    /// `code == 200`.
    fn is_ok(&self) -> bool {
        self.code() == 200
    }

    /// Build an [`AppResponse`] from the view getters.
    fn to_app_response(&self) -> AppResponse {
        AppResponse::from_parts(
            self.code(),
            self.data().clone(),
            self.message().to_string(),
            self.meta().clone(),
        )
    }
}

/// Mutable / fluent builders for [`AppResponse`] envelopes.
///
/// Fluent helpers consume `self` by value (builder style). Override them in
/// wrappers to enforce policies (e.g. always set `meta.close = 1`).
///
/// # Examples
///
/// ```
/// use simplejrpc::response::{AppResponse, AppResponseMut, AppResponseView};
/// use serde_json::json;
///
/// let r = AppResponseMut::with_endpoint(AppResponse::ok(json!(1)), "add");
/// assert_eq!(AppResponseView::meta(&r).endpoint, "add");
/// ```
pub trait AppResponseMut: AppResponseView {
    /// Replace the envelope status code.
    fn set_code(&mut self, code: i32);
    /// Replace the business payload.
    fn set_data(&mut self, data: Value);
    /// Replace the human message (`msg`).
    fn set_message(&mut self, message: impl Into<String>);
    /// Replace the entire [`Meta`] block.
    fn set_meta(&mut self, meta: Meta);
    /// Mutable access to metadata (endpoint / close).
    fn meta_mut(&mut self) -> &mut Meta;

    /// Set [`Meta::endpoint`] (fluent, consumes `self`).
    fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self
    where
        Self: Sized,
    {
        self.meta_mut().endpoint = endpoint.into();
        self
    }

    /// Set [`Meta::close`] (fluent, consumes `self`).
    fn with_close(mut self, close: i32) -> Self
    where
        Self: Sized,
    {
        self.meta_mut().close = close;
        self
    }

    /// Replace data (fluent, consumes `self`).
    fn with_data(mut self, data: Value) -> Self
    where
        Self: Sized,
    {
        self.set_data(data);
        self
    }

    /// Replace message (fluent, consumes `self`).
    fn with_message(mut self, message: impl Into<String>) -> Self
    where
        Self: Sized,
    {
        self.set_message(message);
        self
    }
}

/// Standardized app-level response placed in JSON-RPC `result`.
///
/// Implements [`AppResponseView`] / [`AppResponseMut`] so application crates can wrap
/// or override helpers Public fields are for serde and call-site convenience.
///
/// # Examples
///
/// ```
/// use simplejrpc::AppResponse;
/// use serde_json::json;
/// let r = AppResponse::ok(json!(1));
/// assert_eq!(r.code, 200);
/// assert_eq!(r.data, json!(1));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AppResponse {
    /// HTTP-style status code (`200` success, `400`/`404`/… for app errors).
    pub code: i32,
    /// Business payload (null on error envelopes).
    pub data: Value,
    /// Human message (`msg` in JSON).
    #[serde(rename = "msg")]
    pub message: String,
    /// Optional metadata (endpoint name, close hint).
    pub meta: Meta,
}

impl Default for AppResponse {
    fn default() -> Self {
        Self::ok(Value::Null)
    }
}

impl AppResponse {
    /// Build a success envelope (`code = 200`, `msg = "OK"`).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// let r = AppResponse::ok(json!("pong"));
    /// assert_eq!(r.code, 200);
    /// assert_eq!(r.data, json!("pong"));
    /// ```
    pub fn ok(data: Value) -> Self {
        Self::from_parts(200, data, "OK".into(), Meta::default())
    }

    /// Build an error envelope (`data` is always JSON null).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// let r = AppResponse::error(404, "Not Found");
    /// assert_eq!(r.code, 404);
    /// assert!(r.data.is_null());
    /// ```
    pub fn error(code: i32, message: impl Into<String>) -> Self {
        Self::from_parts(code, Value::Null, message.into(), Meta::default())
    }

    /// Build from raw parts.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::response::{AppResponse, Meta};
    /// use serde_json::json;
    /// let r = AppResponse::from_parts(200, json!(1), "OK".into(), Meta::default());
    /// assert!(r.is_ok());
    /// ```
    pub fn from_parts(code: i32, data: Value, message: String, meta: Meta) -> Self {
        Self {
            code,
            data,
            message,
            meta,
        }
    }

    /// Split into raw parts (pair with [`Self::from_parts`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// let (code, data, msg, meta) = AppResponse::ok(json!(1)).into_parts();
    /// assert_eq!(code, 200);
    /// assert_eq!(data, json!(1));
    /// assert_eq!(msg, "OK");
    /// assert_eq!(meta.close, 0);
    /// ```
    pub fn into_parts(self) -> (i32, Value, String, Meta) {
        (self.code, self.data, self.message, self.meta)
    }

    /// Whether [`Self::code`] is `200`.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// assert!(AppResponse::ok(json!(null)).is_ok());
    /// assert!(!AppResponse::error(400, "x").is_ok());
    /// ```
    pub fn is_ok(&self) -> bool {
        AppResponseView::is_ok(self)
    }

    /// Set [`Meta::endpoint`] (fluent).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// let r = AppResponse::ok(json!(null)).with_endpoint("add");
    /// assert_eq!(r.meta.endpoint, "add");
    /// ```
    pub fn with_endpoint(self, endpoint: impl Into<String>) -> Self {
        AppResponseMut::with_endpoint(self, endpoint)
    }

    /// Set [`Meta::close`] (fluent).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// let r = AppResponse::ok(json!(null)).with_close(1);
    /// assert_eq!(r.meta.close, 1);
    /// ```
    pub fn with_close(self, close: i32) -> Self {
        AppResponseMut::with_close(self, close)
    }

    /// Replace [`Self::data`] (fluent).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// let r = AppResponse::ok(json!(null)).with_data(json!([1, 2]));
    /// assert_eq!(r.data, json!([1, 2]));
    /// ```
    pub fn with_data(self, data: Value) -> Self {
        AppResponseMut::with_data(self, data)
    }

    /// Replace [`Self::message`] (fluent).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::AppResponse;
    /// use serde_json::json;
    /// let r = AppResponse::ok(json!(null)).with_message("done");
    /// assert_eq!(r.message, "done");
    /// ```
    pub fn with_message(self, message: impl Into<String>) -> Self {
        AppResponseMut::with_message(self, message)
    }
}

impl AppResponseView for AppResponse {
    fn code(&self) -> i32 {
        self.code
    }

    fn data(&self) -> &Value {
        &self.data
    }

    fn message(&self) -> &str {
        &self.message
    }

    fn meta(&self) -> &Meta {
        &self.meta
    }
}

impl AppResponseMut for AppResponse {
    fn set_code(&mut self, code: i32) {
        self.code = code;
    }

    fn set_data(&mut self, data: Value) {
        self.data = data;
    }

    fn set_message(&mut self, message: impl Into<String>) {
        self.message = message.into();
    }

    fn set_meta(&mut self, meta: Meta) {
        self.meta = meta;
    }

    fn meta_mut(&mut self) -> &mut Meta {
        &mut self.meta
    }
}