use crate::models::PendingCall;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Default)]
pub struct JsonRpcCorrelator {
inner: Arc<Mutex<HashMap<String, PendingCall>>>,
}
impl JsonRpcCorrelator {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn register(&self, id: String, call: PendingCall) {
self.inner.lock().unwrap().insert(id, call);
}
pub fn match_response(&self, id: &str) -> Option<PendingCall> {
self.inner.lock().unwrap().remove(id)
}
pub fn pending_count(&self) -> usize {
self.inner.lock().unwrap().len()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub code: &'static str,
pub detail: String,
}
fn violation(code: &'static str, detail: impl Into<String>) -> Violation {
Violation {
code,
detail: detail.into(),
}
}
pub fn validate_frame(value: &serde_json::Value) -> Vec<Violation> {
let mut found = Vec::new();
match value.get("jsonrpc").and_then(|v| v.as_str()) {
Some("2.0") => {}
Some(other) => found.push(violation("bad_version", format!("jsonrpc={other}"))),
None => found.push(violation("missing_version", "jsonrpc field is missing")),
}
let has_method = value.get("method").is_some();
let has_result = value.get("result").is_some();
let has_error = value.get("error").is_some();
if has_result && has_error {
found.push(violation(
"both_result_and_error",
"response has both result and error",
));
}
if has_method {
let empty = value
.get("method")
.and_then(|v| v.as_str())
.map(str::is_empty)
.unwrap_or(true);
if empty {
found.push(violation(
"invalid_method",
"method is missing or not a non-empty string",
));
}
if let Some(params) = value.get("params")
&& !params.is_object()
&& !params.is_array()
{
found.push(violation(
"invalid_params",
"params must be an object or array",
));
}
} else if !has_result && !has_error {
found.push(violation(
"unknown_frame_type",
"frame has neither method, result, nor error",
));
}
if let Some(id) = value.get("id")
&& !matches!(
id,
serde_json::Value::String(_) | serde_json::Value::Number(_) | serde_json::Value::Null
)
{
found.push(violation(
"invalid_id",
"id must be a string, number, or null",
));
}
found
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn register_and_match() {
let c = JsonRpcCorrelator::new();
c.register(
"1".to_string(),
PendingCall {
started_at: Instant::now(),
method: "tools/list".to_string(),
tool_name: None,
req_bytes: 10,
req_tokens: 3,
req_preview: None,
},
);
assert_eq!(c.pending_count(), 1);
let popped = c.match_response("1");
assert!(popped.is_some());
assert_eq!(popped.unwrap().method, "tools/list");
assert!(c.match_response("1").is_none());
assert_eq!(c.pending_count(), 0);
}
#[test]
fn match_unknown_id_returns_none() {
let c = JsonRpcCorrelator::new();
assert!(c.match_response("nope").is_none());
}
#[test]
fn correlator_is_cloneable() {
let c1 = JsonRpcCorrelator::new();
c1.register("1".to_string(), PendingCall::default());
let c2 = c1.clone();
assert_eq!(c2.pending_count(), 1);
assert!(c2.match_response("1").is_some());
}
fn codes(value: serde_json::Value) -> Vec<&'static str> {
validate_frame(&value).into_iter().map(|v| v.code).collect()
}
#[test]
fn valid_request_has_no_violations() {
let v = serde_json::json!({
"jsonrpc": "2.0", "id": "1", "method": "tools/call",
"params": { "name": "read_file" }
});
assert!(codes(v).is_empty());
}
#[test]
fn valid_response_has_no_violations() {
let v = serde_json::json!({"jsonrpc": "2.0", "id": 1, "result": {}});
assert!(codes(v).is_empty());
}
#[test]
fn invalid_version_is_reported() {
let v = serde_json::json!({"jsonrpc": "1.0", "id": "1", "method": "tools/list"});
assert!(codes(v).contains(&"bad_version"));
let v = serde_json::json!({"id": "1", "method": "tools/list"});
assert!(codes(v).contains(&"missing_version"));
}
#[test]
fn response_with_result_and_error_is_reported() {
let v = serde_json::json!({
"jsonrpc": "2.0", "id": "1", "result": {}, "error": {"code": -1, "message": "x"}
});
assert!(codes(v).contains(&"both_result_and_error"));
}
#[test]
fn invalid_params_and_id_are_reported() {
let v = serde_json::json!({
"jsonrpc": "2.0", "id": true, "method": "tools/list", "params": "oops"
});
let found = codes(v);
assert!(found.contains(&"invalid_params"), "{found:?}");
assert!(found.contains(&"invalid_id"), "{found:?}");
}
#[test]
fn empty_method_and_unknown_frame_are_reported() {
let v = serde_json::json!({"jsonrpc": "2.0", "id": "1", "method": ""});
assert!(codes(v).contains(&"invalid_method"));
let v = serde_json::json!({"jsonrpc": "2.0", "id": "1"});
assert!(codes(v).contains(&"unknown_frame_type"));
}
}