1use serde::{Deserialize, Serialize};
4
5use crate::error::CallError;
6
7#[derive(Clone, Debug, PartialEq)]
9pub struct Notification {
10 pub method: String,
11 pub params: serde_json::Value,
12}
13
14impl Notification {
15 pub fn request_id(&self) -> Option<&str> {
17 self.params.get("request_id").and_then(|v| v.as_str())
18 }
19}
20
21#[derive(Debug)]
23pub(crate) enum Incoming {
24 Response { id: String, result: Result<serde_json::Value, CallError> },
26 Notification(Notification),
28 Request { id: serde_json::Value, method: String },
30}
31
32#[derive(Deserialize)]
33struct RawMessage {
34 #[serde(default)]
35 id: Option<serde_json::Value>,
36 #[serde(default)]
37 method: Option<String>,
38 #[serde(default)]
39 params: Option<serde_json::Value>,
40 #[serde(default)]
41 result: Option<serde_json::Value>,
42 #[serde(default)]
43 error: Option<RawError>,
44}
45
46#[derive(Deserialize)]
47struct RawError {
48 #[serde(default)]
49 code: i64,
50 #[serde(default)]
51 message: String,
52 #[serde(default)]
53 data: Option<serde_json::Value>,
54}
55
56pub(crate) fn parse(line: &str) -> Result<Incoming, CallError> {
58 let value: serde_json::Value =
59 serde_json::from_str(line).map_err(|e| CallError::Protocol(format!("invalid JSON-RPC message: {e}")))?;
60 let has_result = value.get("result").is_some();
62 let raw: RawMessage =
63 serde_json::from_value(value).map_err(|e| CallError::Protocol(format!("invalid JSON-RPC message: {e}")))?;
64 match (raw.id, raw.method) {
65 (Some(id), Some(method)) => Ok(Incoming::Request { id, method }),
66 (None, Some(method)) => {
67 Ok(Incoming::Notification(Notification { method, params: raw.params.unwrap_or(serde_json::Value::Null) }))
68 }
69 (Some(serde_json::Value::Null), None) => {
70 let detail = raw.error.map(|e| e.message).unwrap_or_else(|| "no detail".into());
73 Err(CallError::Protocol(format!("plugin could not read a request: {detail}")))
74 }
75 (Some(id), None) => {
76 let id = match id {
77 serde_json::Value::String(s) => s,
78 other => other.to_string(),
79 };
80 let result = match (raw.error, has_result) {
81 (Some(err), _) => Err(CallError::Remote { code: err.code, message: err.message, data: err.data }),
82 (None, true) => Ok(raw.result.unwrap_or(serde_json::Value::Null)),
83 (None, false) => Err(CallError::Protocol("response has neither `result` nor `error`".into())),
84 };
85 Ok(Incoming::Response { id, result })
86 }
87 (None, None) => Err(CallError::Protocol("message has neither `id` nor `method`".into())),
88 }
89}
90
91pub(crate) fn request(id: &str, method: &str, params: &serde_json::Value) -> String {
93 serde_json::json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string()
94}
95
96pub(crate) fn notification(method: &str, params: &serde_json::Value) -> String {
98 serde_json::json!({"jsonrpc": "2.0", "method": method, "params": params}).to_string()
99}
100
101pub(crate) fn method_not_found(id: &serde_json::Value, method: &str) -> String {
103 serde_json::json!({
104 "jsonrpc": "2.0",
105 "id": id,
106 "error": {"code": crate::error::METHOD_NOT_FOUND, "message": format!("host does not implement `{method}`")}
107 })
108 .to_string()
109}
110
111#[derive(Debug, Default, Deserialize, Serialize)]
113#[serde(deny_unknown_fields)]
114pub(crate) struct RunResultMsg {
115 #[serde(default)]
116 pub outputs: serde_json::Map<String, serde_json::Value>,
117 #[serde(default)]
118 pub branch: Option<String>,
119 #[serde(default)]
120 pub writes: Vec<WriteMsg>,
121 #[serde(default)]
122 pub usage: Option<graphrt_core::Usage>,
123 #[serde(default)]
124 pub metadata: serde_json::Map<String, serde_json::Value>,
125 #[serde(default)]
126 pub pause: Option<PauseMsg>,
127}
128
129#[derive(Debug, Deserialize, Serialize)]
130#[serde(deny_unknown_fields)]
131pub(crate) struct WriteMsg {
132 pub selector: graphrt_core::Selector,
133 #[serde(default)]
134 pub value: serde_json::Value,
135}
136
137#[derive(Debug, Deserialize, Serialize)]
138#[serde(deny_unknown_fields)]
139pub(crate) struct PauseMsg {
140 #[serde(default = "default_pause_kind")]
141 pub kind: String,
142 #[serde(default)]
143 pub data: serde_json::Value,
144 #[serde(default)]
145 pub state: serde_json::Value,
146}
147
148fn default_pause_kind() -> String {
149 "plugin".to_owned()
150}
151
152#[derive(Debug, Default, Deserialize)]
154#[serde(deny_unknown_fields)]
155pub(crate) struct ToolResultMsg {
156 #[serde(default)]
157 pub text: String,
158 #[serde(default)]
159 pub data: serde_json::Value,
160 #[serde(default)]
161 pub is_error: bool,
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 #[test]
169 fn classifies_messages() {
170 assert!(matches!(parse(r#"{"jsonrpc":"2.0","id":"r-1","result":{"a":1}}"#), Ok(Incoming::Response { .. })));
171 assert!(matches!(
172 parse(r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32000,"message":"x"}}"#),
173 Ok(Incoming::Response { id, result: Err(_) }) if id == "3"
174 ));
175 assert!(matches!(
176 parse(r#"{"jsonrpc":"2.0","method":"node.chunk","params":{"request_id":"r-1"}}"#),
177 Ok(Incoming::Notification(n)) if n.request_id() == Some("r-1")
178 ));
179 assert!(matches!(parse(r#"{"jsonrpc":"2.0","id":1,"method":"x"}"#), Ok(Incoming::Request { .. })));
180 assert!(parse("not json").is_err());
181 assert!(parse("{}").is_err());
182 }
183
184 #[test]
185 fn response_without_result_or_error_is_a_protocol_error() {
186 assert!(matches!(
187 parse(r#"{"jsonrpc":"2.0","id":"r-1"}"#),
188 Ok(Incoming::Response { result: Err(CallError::Protocol(_)), .. })
189 ));
190 assert!(matches!(
192 parse(r#"{"jsonrpc":"2.0","id":"r-1","result":null}"#),
193 Ok(Incoming::Response { result: Ok(serde_json::Value::Null), .. })
194 ));
195 assert!(matches!(
197 parse(r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"parse error"}}"#),
198 Err(CallError::Protocol(_))
199 ));
200 }
201
202 #[test]
203 fn result_messages_reject_unknown_fields() {
204 assert!(serde_json::from_str::<RunResultMsg>(r#"{"output":{"a":1}}"#).is_err());
205 assert!(serde_json::from_str::<RunResultMsg>(r#"{"outputs":{"a":1}}"#).is_ok());
206 assert!(serde_json::from_str::<RunResultMsg>("null").is_err());
207 assert!(serde_json::from_str::<ToolResultMsg>(r#"{"txt":"x"}"#).is_err());
208 }
209}