simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
//! Unix-socket JSON-RPC client (compatible with Go `NewRpcSimpleClient`).
//!
//! The client speaks the same `Content-Length` framing and app envelope as
//! [`crate::Server`]. Prefer [`Client::call`] when you only need `data` on
//! success; use [`Client::call_envelope`] to inspect `code` / `msg` / `meta`.
//!
//! # Examples
//!
//! ```no_run
//! use simplejrpc::Client;
//! use serde_json::json;
//!
//! # async fn demo() -> simplejrpc::Result<()> {
//! let client = Client::connect("/tmp/simplejrpc.sock").await?;
//!
//! // Success path — returns envelope `data` when code == 200
//! let pong = client.call("ping", json!({})).await?;
//!
//! // Object params
//! let sum = client.call("add", json!({"a": 1, "b": 2})).await?;
//!
//! // Full envelope (including non-200 app errors)
//! let env = client.call_envelope("ping", json!({})).await?;
//! assert_eq!(env.code, 200);
//! # let _ = (pong, sum);
//! Ok(())
//! # }
//! ```
//!
//! ## Builder style
//!
//! ```no_run
//! # async fn demo() -> simplejrpc::Result<()> {
//! use simplejrpc::Client;
//! let client = Client::builder()
//!     .socket("/tmp/simplejrpc.sock")
//!     .connect()
//!     .await?;
//! # let _ = client;
//! # Ok(())
//! # }
//! ```

use std::path::Path;
use std::sync::atomic::{AtomicI64, Ordering};

use async_trait::async_trait;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
use tokio::sync::Mutex;

use crate::codec::{encode_frame, FrameReader};
use crate::error::{Error, Result};
use crate::response::AppResponse;

/// Fluent builder for [`Client`].
///
/// # Examples
///
/// ```no_run
/// # async fn demo() -> simplejrpc::Result<()> {
/// use simplejrpc::Client;
/// let c = Client::builder().socket("/tmp/app.sock").connect().await?;
/// # let _ = c;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default)]
pub struct ClientBuilder {
    path: Option<String>,
}

impl ClientBuilder {
    /// Set the Unix socket path to dial.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Client;
    /// let _ = Client::builder().socket("/tmp/app.sock");
    /// ```
    pub fn socket(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Connect using the configured socket path.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if [`Self::socket`] was never called.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Client;
    /// let c = Client::builder().socket("/tmp/app.sock").connect().await?;
    /// # let _ = c;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect(self) -> Result<Client> {
        let path = self
            .path
            .ok_or_else(|| Error::Config("socket path required".into()))?;
        Client::connect(path).await
    }
}

/// Call API shared by [`Client`] and app wrappers (retries, logging, …).
///
/// Default [`Self::call`] returns `data` when envelope `code == 200`.
///
/// ```
/// use async_trait::async_trait;
/// use simplejrpc::client::RpcClient;
/// use simplejrpc::{AppResponse, Result};
/// use serde_json::{json, Value};
///
/// struct Stub;
///
/// #[async_trait]
/// impl RpcClient for Stub {
///     async fn call_envelope(&self, _method: &str, _params: Value) -> Result<AppResponse> {
///         Ok(AppResponse::ok(json!(7)))
///     }
/// }
///
/// # async fn demo() {
/// assert_eq!(RpcClient::call(&Stub, "x", json!({})).await.unwrap(), json!(7));
/// # }
/// ```
#[async_trait]
pub trait RpcClient: Send + Sync {
    /// Full app envelope (`code` / `msg` / `data` / `meta`).
    async fn call_envelope(&self, method: &str, params: Value) -> Result<AppResponse>;

    /// Envelope `data` when `code == 200`; otherwise [`Error::Biz`].
    async fn call(&self, method: &str, params: Value) -> Result<Value> {
        let env = self.call_envelope(method, params).await?;
        if env.code == 200 {
            Ok(env.data)
        } else {
            Err(Error::biz_code(env.code, env.message))
        }
    }
}

/// Unix-socket JSON-RPC client (one in-flight request per connection).
///
/// See the [module docs](crate::client) for examples.
pub struct Client {
    stream: Mutex<UnixStream>,
    next_id: AtomicI64,
}

impl Client {
    /// Start a [`ClientBuilder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Client;
    /// let _ = Client::builder().socket("/tmp/app.sock");
    /// ```
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Dial a Unix socket and return a connected client.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Client;
    /// let client = Client::connect("/tmp/simplejrpc.sock").await?;
    /// # let _ = client;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect(path: impl AsRef<Path>) -> Result<Self> {
        let stream = UnixStream::connect(path).await?;
        Ok(Self::from_stream(stream))
    }

    /// Wrap an existing connected stream (tests / custom dialers).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo(stream: tokio::net::UnixStream) {
    /// use simplejrpc::Client;
    /// let _ = Client::from_stream(stream);
    /// # }
    /// ```
    pub fn from_stream(stream: UnixStream) -> Self {
        Self {
            stream: Mutex::new(stream),
            next_id: AtomicI64::new(1),
        }
    }

    /// Allocate the next monotonic JSON-RPC request id.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Client;
    /// let c = Client::connect("/tmp/simplejrpc.sock").await?;
    /// assert_eq!(c.next_request_id(), 1);
    /// assert_eq!(c.next_request_id(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn next_request_id(&self) -> i64 {
        self.next_id.fetch_add(1, Ordering::SeqCst)
    }

    /// Call a method and return the app envelope **`data`** when `code == 200`.
    ///
    /// If the envelope reports a non-200 `code`, returns [`Error::Biz`] with
    /// that code and message (still a transport-level success).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Client;
    /// use serde_json::json;
    /// let c = Client::connect("/tmp/simplejrpc.sock").await?;
    /// let v = c.call("ping", json!({})).await?;
    /// # let _ = v;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn call(&self, method: &str, params: Value) -> Result<Value> {
        RpcClient::call(self, method, params).await
    }

    /// Call a method and return the full [`AppResponse`] envelope.
    ///
    /// Use this when you need `code` / `msg` / `meta` (for example `404` method
    /// missing still yields a JSON-RPC `result`, not a JSON-RPC `error`).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Client;
    /// use serde_json::json;
    /// let c = Client::connect("/tmp/simplejrpc.sock").await?;
    /// let env = c.call_envelope("missing", json!({})).await?;
    /// assert_eq!(env.code, 404);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn call_envelope(&self, method: &str, params: Value) -> Result<AppResponse> {
        RpcClient::call_envelope(self, method, params).await
    }

    /// Write one framed request and read exactly one framed response.
    ///
    /// Exposed so wrappers can customize request building while reusing the
    /// locked stream exchange.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo(c: &simplejrpc::Client) -> simplejrpc::Result<()> {
    /// use simplejrpc::client::encode_rpc_request;
    /// use serde_json::json;
    /// let framed = encode_rpc_request(1, "ping", json!({}))?;
    /// let _body = c.exchange_frame(&framed).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn exchange_frame(&self, framed: &[u8]) -> Result<Vec<u8>> {
        let mut stream = self.stream.lock().await;
        stream.write_all(framed).await?;
        read_one_frame(&mut stream).await
    }
}

#[async_trait]
impl RpcClient for Client {
    async fn call_envelope(&self, method: &str, params: Value) -> Result<AppResponse> {
        let framed = encode_rpc_request(self.next_request_id(), method, params)?;
        let resp_body = self.exchange_frame(&framed).await?;
        parse_rpc_envelope(&resp_body)
    }
}

/// Build a framed JSON-RPC request for `method` / `params`.
///
/// # Errors
///
/// Returns [`Error::Json`] if `params` cannot be serialized into the request object.
///
/// # Examples
///
/// ```
/// use simplejrpc::client::encode_rpc_request;
/// use serde_json::json;
/// let framed = encode_rpc_request(1, "ping", json!({})).unwrap();
/// assert!(framed.starts_with(b"Content-Length:"));
/// ```
pub fn encode_rpc_request(id: i64, method: &str, params: Value) -> Result<Vec<u8>> {
    let req = json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": method,
        "params": params,
    });
    Ok(encode_frame(&serde_json::to_vec(&req)?))
}

/// Read from `stream` until one complete Content-Length frame is available.
async fn read_one_frame(stream: &mut UnixStream) -> Result<Vec<u8>> {
    let mut reader = FrameReader::new();
    let mut buf = vec![0u8; 8192];
    loop {
        let n = stream.read(&mut buf).await?;
        if n == 0 {
            return Err(Error::Protocol("connection closed".into()));
        }
        reader.push(&buf[..n]);
        if let Some(frame) = reader.try_next()? {
            return Ok(frame);
        }
    }
}

/// Parse a JSON-RPC response object into an [`AppResponse`] result envelope.
fn parse_rpc_envelope(resp_body: &[u8]) -> Result<AppResponse> {
    let v: Value = serde_json::from_slice(resp_body)?;
    if let Some(err) = v.get("error") {
        return Err(Error::Protocol(format!("json-rpc error: {err}")));
    }
    let result = v
        .get("result")
        .cloned()
        .ok_or_else(|| Error::Protocol("missing result".into()))?;
    Ok(serde_json::from_value(result)?)
}