simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
//! Error model aligned with Go `core/gerror`.
//!
//! Business failures use numeric codes in the `200xxx` range via [`RpcCode`] or
//! custom codes from [`crate::define_rpc_codes!`] /
//! [`crate::define_rpc_codes_with_msg!`].
//!
//! Internal failures ([`Error::Io`], [`Error::Json`], …) must never be shown
//! raw to clients — use [`Error::client_message`] / [`Error::to_app_response`].
//!
//! # Examples
//!
//! ```
//! use simplejrpc::{Error, RpcCode};
//!
//! let e = Error::biz(RpcCode::BadRequest, "invalid params");
//! assert_eq!(e.code(), 200400);
//! assert!(e.is_public());
//! assert_eq!(e.client_message(), "invalid params");
//! ```
//!
//! ```
//! use simplejrpc::define_rpc_codes;
//!
//! define_rpc_codes! {
//!     /// User not found
//!     UserNotFound => 200404,
//!     /// Quota exceeded
//!     QuotaExceeded => 200429,
//! }
//! assert_eq!(UserNotFound.code(), 200404);
//! ```

use thiserror::Error as ThisError;

/// Crate-wide result alias (`Result<T, Error>`).
///
/// # Examples
///
/// ```
/// use simplejrpc::{Error, Result, RpcCode};
/// fn parse() -> Result<i32> {
///     Err(Error::biz(RpcCode::BadRequest, "bad"))
/// }
/// assert!(parse().is_err());
/// ```
pub type Result<T> = std::result::Result<T, Error>;

/// Business codes (`200xxx`). Distinct from HTTP-style [`crate::AppResponse::code`].
///
/// # Examples
///
/// ```
/// use simplejrpc::RpcCode;
/// assert_eq!(RpcCode::Ok.code(), 200_000);
/// assert_eq!(RpcCode::NotFound.message(), "Not Found");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum RpcCode {
    /// Success (Go `CodeOK`).
    Ok = 200_000,
    /// Generic internal error.
    Internal = 200_050,
    /// Bad request / validation.
    BadRequest = 200_400,
    /// Unauthorized.
    Unauthorized = 200_401,
    /// Forbidden.
    Forbidden = 200_403,
    /// Not found.
    NotFound = 200_404,
}

impl RpcCode {
    /// Numeric code value.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::RpcCode;
    /// assert_eq!(RpcCode::BadRequest.code(), 200_400);
    /// ```
    pub const fn code(self) -> i32 {
        self as i32
    }

    /// Default English message for this code.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::RpcCode;
    /// assert_eq!(RpcCode::Ok.message(), "OK");
    /// ```
    pub const fn message(self) -> &'static str {
        match self {
            Self::Ok => "OK",
            Self::Internal => "Internal Error",
            Self::BadRequest => "Bad Request",
            Self::Unauthorized => "Unauthorized",
            Self::Forbidden => "Forbidden",
            Self::NotFound => "Not Found",
        }
    }
}

/// Map an error to client-facing `code` / `msg` (i18n, remap, …).
///
/// # Examples
///
/// ```
/// use simplejrpc::error::{Error, ErrorMapping};
/// use simplejrpc::RpcCode;
///
/// struct Prefixed(Error);
///
/// impl ErrorMapping for Prefixed {
///     fn code(&self) -> i32 {
///         ErrorMapping::code(&self.0)
///     }
///     fn is_public(&self) -> bool {
///         ErrorMapping::is_public(&self.0)
///     }
///     fn client_message(&self) -> String {
///         format!("app: {}", ErrorMapping::client_message(&self.0))
///     }
/// }
///
/// let p = Prefixed(Error::biz(RpcCode::BadRequest, "bad"));
/// assert_eq!(ErrorMapping::client_message(&p), "app: bad");
/// assert_eq!(p.to_app_response("add").message, "app: bad");
/// ```
pub trait ErrorMapping: Send + Sync {
    /// Numeric code written into [`crate::AppResponse::code`] (usually `200xxx`).
    fn code(&self) -> i32;

    /// Whether the underlying message is already safe to show to clients.
    ///
    /// Public variants: [`Error::Biz`], [`Error::Validation`], [`Error::MethodNotFound`].
    fn is_public(&self) -> bool;

    /// Message for the RPC envelope `msg` field (never leak OS/SQL/panic text).
    fn client_message(&self) -> String;

    /// Build a client [`crate::AppResponse`] from this mapping.
    fn to_app_response(&self, endpoint: impl Into<String>) -> crate::AppResponse {
        crate::AppResponse::error(self.code(), self.client_message()).with_endpoint(endpoint)
    }
}

/// Unified error type for the SDK.
///
/// /// # Examples
///
/// ```
/// use simplejrpc::{Error, RpcCode};
/// let e = Error::Validation("age: too small".into());
/// assert_eq!(e.code(), RpcCode::BadRequest.code());
/// assert!(e.is_public());
/// ```
#[derive(Debug, ThisError)]
pub enum Error {
    /// Business / application exception with numeric code.
    #[error("rpc error {code}: {message}")]
    Biz {
        /// Numeric code.
        code: i32,
        /// Human readable message (safe to show when public).
        message: String,
    },

    /// I/O failure (socket, framing, etc.).
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// JSON encode/decode failure.
    #[error("json error: {0}")]
    Json(#[from] serde_json::Error),

    /// Protocol / framing violation.
    #[error("protocol error: {0}")]
    Protocol(String),

    /// Method not registered.
    #[error("method not found: {0}")]
    MethodNotFound(String),

    /// Validation failed.
    #[error("validation error: {0}")]
    Validation(String),

    /// Configuration error.
    #[error("config error: {0}")]
    Config(String),
}

impl Error {
    /// Build a business error from [`RpcCode`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::{Error, RpcCode};
    /// let e = Error::biz(RpcCode::Forbidden, "denied");
    /// assert_eq!(e.code(), 200_403);
    /// ```
    pub fn biz(code: RpcCode, message: impl Into<String>) -> Self {
        Self::Biz {
            code: code.code(),
            message: message.into(),
        }
    }

    /// Build a business error from a raw numeric code.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Error;
    /// let e = Error::biz_code(200499, "custom");
    /// assert_eq!(e.code(), 200499);
    /// ```
    pub fn biz_code(code: i32, message: impl Into<String>) -> Self {
        Self::Biz {
            code,
            message: message.into(),
        }
    }

    /// Extract the numeric code used in app envelopes.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::{Error, RpcCode};
    /// assert_eq!(Error::MethodNotFound("x".into()).code(), RpcCode::NotFound.code());
    /// ```
    pub fn code(&self) -> i32 {
        ErrorMapping::code(self)
    }

    /// Whether the **message** is already safe to show to clients.
    ///
    /// - [`Self::Biz`] / [`Self::Validation`] / [`Self::MethodNotFound`]: yes
    ///   (callers must put only user-facing text in these variants).
    /// - [`Self::Io`] / [`Self::Json`] / …: no — use [`Self::client_message`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::{Error, RpcCode};
    /// assert!(Error::biz(RpcCode::Ok, "ok").is_public());
    /// assert!(!Error::Protocol("boom".into()).is_public());
    /// ```
    pub fn is_public(&self) -> bool {
        ErrorMapping::is_public(self)
    }

    /// Message for the RPC envelope `msg` field.
    ///
    /// - Public variants → their own message (i18n / business text).
    /// - Internal variants → fixed fallback; full [`std::fmt::Display`] is for logs only.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::{sanitize::CLIENT_INTERNAL_MSG, Error};
    /// assert_eq!(Error::Protocol("x".into()).client_message(), CLIENT_INTERNAL_MSG);
    /// ```
    pub fn client_message(&self) -> String {
        ErrorMapping::client_message(self)
    }

    /// Build a client [`crate::AppResponse`] from this typed error.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::{Error, RpcCode};
    /// let resp = Error::biz(RpcCode::BadRequest, "bad").to_app_response("add");
    /// assert_eq!(resp.code, 200_400);
    /// assert_eq!(resp.meta.endpoint, "add");
    /// ```
    pub fn to_app_response(&self, endpoint: impl Into<String>) -> crate::AppResponse {
        ErrorMapping::to_app_response(self, endpoint)
    }
}

impl ErrorMapping for Error {
    fn code(&self) -> i32 {
        match self {
            Self::Biz { code, .. } => *code,
            Self::MethodNotFound(_) => RpcCode::NotFound.code(),
            Self::Validation(_) => RpcCode::BadRequest.code(),
            _ => RpcCode::Internal.code(),
        }
    }

    fn is_public(&self) -> bool {
        matches!(
            self,
            Self::Biz { .. } | Self::Validation(_) | Self::MethodNotFound(_)
        )
    }

    fn client_message(&self) -> String {
        match self {
            Self::Biz { message, .. } => message.clone(),
            Self::Validation(m) => m.clone(),
            Self::MethodNotFound(_) => RpcCode::NotFound.message().to_string(),
            other => {
                tracing::error!(error = %other, "internal rpc error (typed; not exposed to client)");
                crate::sanitize::CLIENT_INTERNAL_MSG.to_string()
            }
        }
    }
}