use super::*;
impl Display for RpcError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"JSON-RPC error {}: {}",
self.get_code(),
self.get_message()
)
}
}
impl Error for RpcError {}
impl RpcError {
pub fn parse_error() -> Self {
Self::custom(RPC_PARSE_ERROR, MSG_PARSE_ERROR, None)
}
pub fn invalid_request() -> Self {
Self::custom(RPC_INVALID_REQUEST, MSG_INVALID_REQUEST, None)
}
pub fn method_not_found() -> Self {
Self::custom(RPC_METHOD_NOT_FOUND, MSG_METHOD_NOT_FOUND, None)
}
pub fn invalid_params(data: Option<Value>) -> Self {
Self::custom(RPC_INVALID_PARAMS, MSG_INVALID_PARAMS, data)
}
pub fn internal_error(data: Option<Value>) -> Self {
Self::custom(RPC_INTERNAL_ERROR, MSG_INTERNAL_ERROR, data)
}
pub fn custom<M>(code: i64, message: M, data: Option<Value>) -> Self
where
M: Into<String>,
{
Self {
code,
message: message.into(),
data,
}
}
}
impl RpcResponse {
pub fn success(id: RpcId, result: Value) -> Self {
Self {
jsonrpc: JSONRPC_VERSION.to_owned(),
result: Some(result),
error: None,
id,
}
}
pub fn failure(id: RpcId, error: RpcError) -> Self {
Self {
jsonrpc: JSONRPC_VERSION.to_owned(),
result: None,
error: Some(error),
id,
}
}
}
impl Default for RpcConfig {
fn default() -> Self {
Self {
endpoint: DEFAULT_RPC_ENDPOINT.to_owned(),
max_body_size: DEFAULT_RPC_MAX_BODY_SIZE,
max_batch_size: DEFAULT_RPC_MAX_BATCH_SIZE,
}
}
}
impl RpcRouter {
pub fn new() -> Self {
Self::default()
}
pub fn register<N, F, Fut>(&mut self, name: N, handler: F) -> &mut Self
where
N: Into<String>,
F: Fn(Option<Value>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Value, RpcError>> + Send + 'static,
{
let Self { methods } = self;
let boxed: RpcHandler = Arc::new(move |params: Option<Value>| Box::pin(handler(params)));
methods.insert(name.into(), boxed);
self
}
pub fn has_method(&self, name: &str) -> bool {
let Self { methods } = self;
methods.contains_key(name)
}
pub fn method_names(&self) -> Vec<String> {
let Self { methods } = self;
methods.keys().cloned().collect()
}
pub async fn dispatch_value(&self, raw: Value) -> Option<RpcResponse> {
let Self { methods } = self;
let req: RpcRequest = match from_value(raw) {
Ok(parsed) => parsed,
Err(_) => {
return Some(RpcResponse::failure(
RpcId::Null,
RpcError::invalid_request(),
));
}
};
if req.get_jsonrpc() != JSONRPC_VERSION || req.get_method().is_empty() {
let id: RpcId = req.get_id().unwrap_or(RpcId::Null);
return Some(RpcResponse::failure(id, RpcError::invalid_request()));
}
let Some(handler) = methods.get(req.get_method()) else {
return req
.get_id()
.map(|id: RpcId| RpcResponse::failure(id, RpcError::method_not_found()));
};
let outcome: Result<Value, RpcError> = handler(req.get_params()).await;
let id: RpcId = req.get_id()?;
match outcome {
Ok(value) => Some(RpcResponse::success(id, value)),
Err(err) => Some(RpcResponse::failure(id, err)),
}
}
pub async fn dispatch_bytes(&self, raw: &[u8], config: &RpcConfig) -> Option<Vec<u8>> {
let parsed: Value = match from_slice(raw) {
Ok(val) => val,
Err(_) => {
let err_resp: RpcResponse =
RpcResponse::failure(RpcId::Null, RpcError::parse_error());
return Some(encode_rpc_response(&err_resp));
}
};
match parsed {
Value::Array(items) => {
if items.is_empty() {
let err_resp: RpcResponse =
RpcResponse::failure(RpcId::Null, RpcError::invalid_request());
return Some(encode_rpc_response(&err_resp));
}
if items.len() > config.get_max_batch_size() {
let err_resp: RpcResponse = RpcResponse::failure(
RpcId::Null,
RpcError::custom(RPC_INVALID_REQUEST, MSG_BATCH_TOO_LARGE, None),
);
return Some(encode_rpc_response(&err_resp));
}
let mut responses: Vec<RpcResponse> = Vec::with_capacity(items.len());
for item in items {
if let Some(resp) = self.dispatch_value(item).await {
responses.push(resp);
}
}
if responses.is_empty() {
None
} else {
Some(to_vec(&responses).unwrap_or_default())
}
}
single => self
.dispatch_value(single)
.await
.map(|resp: RpcResponse| encode_rpc_response(&resp)),
}
}
}
impl RpcPlugin {
pub fn init(config: RpcConfig, router: RpcRouter) -> &'static Self {
RPC_PLUGIN.get_or_init(|| Self { config, router })
}
pub fn get() -> Option<&'static Self> {
RPC_PLUGIN.get()
}
pub fn get_config(&self) -> &RpcConfig {
&self.config
}
pub fn get_router(&self) -> &RpcRouter {
&self.router
}
}
impl ServerHook for RpcHook {
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = RpcPlugin::get() else {
return Status::Continue;
};
let config: &RpcConfig = plugin.get_config();
if ctx.get_request().get_path() != config.get_endpoint() {
return Status::Continue;
}
if !ctx.get_request().get_method().is_post() {
ctx.get_mut_response()
.set_status_code(HttpStatus::MethodNotAllowed.code())
.set_body(Vec::new());
let wire: ResponseData = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
return Status::Reject;
}
let body: &[u8] = ctx.get_request().get_body();
if body.len() > config.get_max_body_size() {
ctx.get_mut_response()
.set_status_code(HttpStatus::PayloadTooLarge.code())
.set_body(Vec::new());
let wire: ResponseData = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
return Status::Reject;
}
match plugin.get_router().dispatch_bytes(body, config).await {
Some(payload) => {
ctx.get_mut_response()
.set_status_code(HttpStatus::Ok.code())
.set_header(CONTENT_TYPE, APPLICATION_JSON)
.set_body(payload);
}
None => {
ctx.get_mut_response()
.set_status_code(HttpStatus::NoContent.code())
.set_body(Vec::new());
}
}
let wire: ResponseData = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
Status::Reject
}
}