use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::RpcError;
#[derive(Debug, Deserialize)]
pub struct RpcRequest {
pub jsonrpc: String,
pub method: String,
#[serde(default)]
pub params: Value,
#[serde(default, deserialize_with = "deserialize_opt_id")]
pub id: Option<Value>,
}
fn deserialize_opt_id<'de, D>(deserializer: D) -> std::result::Result<Option<Value>, D::Error>
where
D: serde::Deserializer<'de>,
{
let v = Value::deserialize(deserializer)?;
Ok(if v.is_null() { None } else { Some(v) })
}
impl RpcRequest {
pub fn is_notification(&self) -> bool {
self.id.is_none()
}
pub fn version_ok(&self) -> bool {
self.jsonrpc == "2.0"
}
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum RpcResponse {
Ok(RpcSuccess),
Err(RpcErrorBody),
}
#[derive(Debug, Serialize)]
pub struct RpcSuccess {
pub jsonrpc: &'static str,
pub id: Value,
pub result: Value,
}
#[derive(Debug, Serialize)]
pub struct RpcErrorBody {
pub jsonrpc: &'static str,
pub id: Value,
pub error: RpcErrorPayload,
}
#[derive(Debug, Serialize)]
pub struct RpcErrorPayload {
pub code: i32,
pub message: String,
}
impl RpcResponse {
pub fn ok(id: Value, result: Value) -> Self {
RpcResponse::Ok(RpcSuccess {
jsonrpc: "2.0",
id,
result,
})
}
pub fn err(id: Value, err: RpcError) -> Self {
RpcResponse::Err(RpcErrorBody {
jsonrpc: "2.0",
id,
error: RpcErrorPayload {
code: err.code(),
message: err.to_string(),
},
})
}
}
#[derive(Debug, Serialize)]
pub struct AuditNotification<'a> {
pub jsonrpc: &'static str,
pub method: &'static str,
pub params: AuditParams<'a>,
}
#[derive(Debug, Serialize)]
pub struct AuditParams<'a> {
pub ts: &'a str,
pub event: &'a str,
#[serde(flatten)]
pub fields: &'a serde_json::Map<String, Value>,
}
impl<'a> AuditNotification<'a> {
pub fn from_jsonl(
ts: &'a str,
event: &'a str,
fields: &'a serde_json::Map<String, Value>,
) -> Self {
AuditNotification {
jsonrpc: "2.0",
method: "audit",
params: AuditParams { ts, event, fields },
}
}
}