use async_trait::async_trait;
use dig_rpc_protocol::{ErrorCode, Method, RpcError};
use serde_json::Value;
#[async_trait]
pub trait RpcHandler: Send + Sync + 'static {
async fn handle(&self, method: Method, params: Value) -> Result<Value, RpcError> {
let _ = params;
Err(RpcError::of(
ErrorCode::MethodNotFound,
format!("method {} not implemented by this node", method.name()),
))
}
async fn healthz(&self) -> Result<(), RpcError> {
Ok(())
}
fn version(&self) -> String {
env!("CARGO_PKG_VERSION").to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Blank;
impl RpcHandler for Blank {}
#[tokio::test]
async fn default_handler_rejects_with_method_not_found() {
let h = Blank;
let err = h.handle(Method::GetContent, Value::Null).await.unwrap_err();
assert_eq!(err.code, ErrorCode::MethodNotFound);
assert!(err.message.contains("dig.getContent"));
}
#[tokio::test]
async fn defaults() {
let h = Blank;
assert!(h.healthz().await.is_ok());
assert!(!h.version().is_empty());
}
}