use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use async_trait::async_trait;
use parking_lot::RwLock;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{UnixListener, UnixStream};
use tracing::{debug, error, info};
use crate::codec::{encode_frame, FrameReader};
use crate::error::{Error, Result};
use crate::middleware::{Middleware, MiddlewareChain};
use crate::response::AppResponse;
pub trait RequestView: Send + Sync {
fn method(&self) -> &str;
fn params_raw(&self) -> &Value;
fn id(&self) -> &Value;
fn extension(&self, key: &str) -> Option<&Value>;
fn params<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
serde_json::from_value(self.params_raw().clone()).map_err(Error::from)
}
fn param_i64(&self, key: &str) -> Option<i64> {
self.params_raw().get(key)?.as_i64()
}
fn param_str(&self, key: &str) -> Option<&str> {
self.params_raw().get(key)?.as_str()
}
}
pub trait RequestMut: RequestView {
fn set_extension(&mut self, key: impl Into<String>, value: Value);
fn params_mut(&mut self) -> &mut Value;
fn extensions_mut(&mut self) -> &mut HashMap<String, Value>;
}
#[derive(Debug, Clone)]
pub struct Request {
method: String,
params: Value,
id: Value,
extensions: HashMap<String, Value>,
}
impl Request {
pub fn new(method: impl Into<String>, params: Value, id: Value) -> Self {
Self::from_parts(method.into(), params, id, HashMap::new())
}
pub fn from_parts(
method: String,
params: Value,
id: Value,
extensions: HashMap<String, Value>,
) -> Self {
Self {
method,
params,
id,
extensions,
}
}
pub fn into_parts(self) -> (String, Value, Value, HashMap<String, Value>) {
(self.method, self.params, self.id, self.extensions)
}
pub fn method(&self) -> &str {
&self.method
}
pub fn params_raw(&self) -> &Value {
&self.params
}
pub fn params<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
serde_json::from_value(self.params.clone()).map_err(Error::from)
}
pub fn param_i64(&self, key: &str) -> Option<i64> {
self.params.get(key)?.as_i64()
}
pub fn param_str(&self, key: &str) -> Option<&str> {
self.params.get(key)?.as_str()
}
pub fn id(&self) -> &Value {
&self.id
}
pub fn set_extension(&mut self, key: impl Into<String>, value: Value) {
self.extensions.insert(key.into(), value);
}
pub fn extension(&self, key: &str) -> Option<&Value> {
self.extensions.get(key)
}
pub fn params_mut(&mut self) -> &mut Value {
&mut self.params
}
pub fn extensions_mut(&mut self) -> &mut HashMap<String, Value> {
&mut self.extensions
}
}
impl RequestView for Request {
fn method(&self) -> &str {
&self.method
}
fn params_raw(&self) -> &Value {
&self.params
}
fn id(&self) -> &Value {
&self.id
}
fn extension(&self, key: &str) -> Option<&Value> {
self.extensions.get(key)
}
}
impl RequestMut for Request {
fn set_extension(&mut self, key: impl Into<String>, value: Value) {
self.extensions.insert(key.into(), value);
}
fn params_mut(&mut self) -> &mut Value {
&mut self.params
}
fn extensions_mut(&mut self) -> &mut HashMap<String, Value> {
&mut self.extensions
}
}
#[async_trait]
pub trait RpcHandler: Send + Sync {
async fn handle(&self, req: Request) -> Result<Value>;
}
pub type HandlerFn =
Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>> + Send + Sync>;
struct ClosureHandler<F>(F);
#[async_trait]
impl<F, Fut> RpcHandler for ClosureHandler<F>
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Value>> + Send + 'static,
{
async fn handle(&self, req: Request) -> Result<Value> {
(self.0)(req).await
}
}
#[derive(Default)]
pub struct ServerBuilder {
handlers: HashMap<String, Arc<dyn RpcHandler>>,
middlewares: MiddlewareChain,
}
impl ServerBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn register<F, Fut>(mut self, method: impl Into<String>, f: F) -> Self
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Value>> + Send + 'static,
{
self.handlers
.insert(method.into(), Arc::new(ClosureHandler(f)));
self
}
pub fn register_handler(mut self, method: impl Into<String>, h: Arc<dyn RpcHandler>) -> Self {
self.handlers.insert(method.into(), h);
self
}
pub fn with_middleware(mut self, mw: Arc<dyn Middleware>) -> Self {
self.middlewares.push(mw);
self
}
pub fn build(self) -> Server {
Server {
handlers: RwLock::new(self.handlers),
middlewares: self.middlewares,
}
}
}
pub struct Server {
handlers: RwLock<HashMap<String, Arc<dyn RpcHandler>>>,
middlewares: MiddlewareChain,
}
impl Server {
pub fn builder() -> ServerBuilder {
ServerBuilder::new()
}
pub fn insert_handler(&self, method: impl Into<String>, h: Arc<dyn RpcHandler>) {
self.handlers.write().insert(method.into(), h);
}
pub async fn serve(self, socket_path: impl AsRef<Path>) -> Result<()> {
let path = socket_path.as_ref();
let listener = bind_unix_listener(path).await?;
info!(?path, "simplejrpc listening");
let server = Arc::new(self);
loop {
let (stream, _) = listener.accept().await?;
let srv = Arc::clone(&server);
tokio::spawn(async move {
if let Err(e) = srv.handle_connection(stream).await {
error!(error = %e, "connection closed with error");
}
});
}
}
pub async fn serve_with_shutdown(
self,
socket_path: impl AsRef<Path>,
mut shutdown: tokio::sync::watch::Receiver<bool>,
) -> Result<()> {
let path = socket_path.as_ref();
let listener = bind_unix_listener(path).await?;
let server = Arc::new(self);
loop {
tokio::select! {
_ = shutdown.changed() => {
if *shutdown.borrow() {
info!("shutdown signal");
break;
}
}
accepted = listener.accept() => {
let (stream, _) = accepted?;
spawn_connection(Arc::clone(&server), stream);
}
}
}
let _ = tokio::fs::remove_file(path).await;
Ok(())
}
async fn handle_connection(self: Arc<Self>, mut stream: UnixStream) -> Result<()> {
let mut reader = FrameReader::new();
let mut buf = vec![0u8; 8192];
loop {
let n = stream.read(&mut buf).await?;
if n == 0 {
break;
}
reader.push(&buf[..n]);
self.write_pending_responses(&mut reader, &mut stream)
.await?;
}
Ok(())
}
async fn write_pending_responses(
self: &Arc<Self>,
reader: &mut FrameReader,
stream: &mut UnixStream,
) -> Result<()> {
while let Some(body) = reader.try_next()? {
let response_body = self.dispatch_raw(&body).await?;
stream.write_all(&encode_frame(&response_body)).await?;
}
Ok(())
}
async fn dispatch_raw(&self, body: &[u8]) -> Result<Vec<u8>> {
let (id, method, mut request) = parse_incoming_rpc(body)?;
debug!(%method, "dispatch");
self.middlewares.run_request(&mut request).await;
let app = self.invoke_method(&method, request).await;
let app = self.finish_response(app, &method).await;
encode_rpc_result(id, app)
}
async fn invoke_method(&self, method: &str, request: Request) -> AppResponse {
let handler = self.handlers.read().get(method).cloned();
match handler {
None => AppResponse::error(404, "Not Found").with_endpoint(method),
Some(h) => run_handler_catch_panic(method, h, request).await,
}
}
async fn finish_response(&self, app: AppResponse, method: &str) -> AppResponse {
match self.middlewares.run_response(app).await {
Ok(a) => a,
Err(e) => {
error!(error = %e, method = %method, "response middleware failed");
internal_app_error(method)
}
}
}
}
fn parse_incoming_rpc(body: &[u8]) -> Result<(Value, String, Request)> {
let req_val: Value = serde_json::from_slice(body)?;
let id = req_val.get("id").cloned().unwrap_or(Value::Null);
let method = req_val
.get("method")
.and_then(|m| m.as_str())
.unwrap_or("")
.to_string();
let params = req_val.get("params").cloned().unwrap_or(Value::Null);
let request = Request::new(method.clone(), params, id.clone());
Ok((id, method, request))
}
async fn bind_unix_listener(path: &Path) -> Result<UnixListener> {
if path.exists() {
let _ = tokio::fs::remove_file(path).await;
}
Ok(UnixListener::bind(path)?)
}
fn spawn_connection(server: Arc<Server>, stream: UnixStream) {
tokio::spawn(async move {
let _ = server.handle_connection(stream).await;
});
}
async fn run_handler_catch_panic(
method: &str,
handler: Arc<dyn RpcHandler>,
request: Request,
) -> AppResponse {
match tokio::task::spawn(async move { handler.handle(request).await }).await {
Ok(Ok(data)) => AppResponse::ok(data).with_endpoint(method),
Ok(Err(e)) => e.to_app_response(method),
Err(join_err) => {
error!(
error = %join_err,
method = %method,
"rpc handler panicked (caught); details logged only"
);
internal_app_error(method)
}
}
}
fn internal_app_error(method: &str) -> AppResponse {
AppResponse::error(
crate::RpcCode::Internal.code(),
crate::sanitize::CLIENT_INTERNAL_MSG,
)
.with_endpoint(method)
}
fn encode_rpc_result(id: Value, app: AppResponse) -> Result<Vec<u8>> {
let rpc = json!({
"jsonrpc": "2.0",
"id": id,
"result": app,
});
Ok(serde_json::to_vec(&rpc)?)
}