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;
#[derive(Debug, Default)]
pub struct ClientBuilder {
path: Option<String>,
}
impl ClientBuilder {
pub fn socket(mut self, path: impl Into<String>) -> Self {
self.path = Some(path.into());
self
}
pub async fn connect(self) -> Result<Client> {
let path = self
.path
.ok_or_else(|| Error::Config("socket path required".into()))?;
Client::connect(path).await
}
}
#[async_trait]
pub trait RpcClient: Send + Sync {
async fn call_envelope(&self, method: &str, params: Value) -> Result<AppResponse>;
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))
}
}
}
pub struct Client {
stream: Mutex<UnixStream>,
next_id: AtomicI64,
}
impl Client {
pub fn builder() -> ClientBuilder {
ClientBuilder::default()
}
pub async fn connect(path: impl AsRef<Path>) -> Result<Self> {
let stream = UnixStream::connect(path).await?;
Ok(Self::from_stream(stream))
}
pub fn from_stream(stream: UnixStream) -> Self {
Self {
stream: Mutex::new(stream),
next_id: AtomicI64::new(1),
}
}
pub fn next_request_id(&self) -> i64 {
self.next_id.fetch_add(1, Ordering::SeqCst)
}
pub async fn call(&self, method: &str, params: Value) -> Result<Value> {
RpcClient::call(self, method, params).await
}
pub async fn call_envelope(&self, method: &str, params: Value) -> Result<AppResponse> {
RpcClient::call_envelope(self, method, params).await
}
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)
}
}
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)?))
}
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);
}
}
}
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)?)
}