1use serde::{Deserialize, Serialize};
25use serde_json::{Value, json};
26
27pub const JSON_RPC_VERSION: &str = "2.0";
28pub const PROTOCOL_VERSION: u32 = 1;
29pub const METHOD_AGENT_INFO: &str = "agent.info";
30pub const METHOD_DEVICES_LIST: &str = "devices.list";
31
32pub const ERROR_PARSE: i32 = -32700;
33pub const ERROR_INVALID_REQUEST: i32 = -32600;
34pub const ERROR_METHOD_NOT_FOUND: i32 = -32601;
35pub const ERROR_INVALID_PARAMS: i32 = -32602;
36pub const ERROR_INTERNAL: i32 = -32603;
37pub const ERROR_PROTOCOL_VERSION: i32 = -32001;
38
39#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
40pub struct Request {
41 pub jsonrpc: String,
42 pub method: String,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub params: Option<Value>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub id: Option<Value>,
47}
48
49impl Request {
50 pub fn new(method: impl Into<String>, id: Value) -> Self {
51 Self {
52 jsonrpc: JSON_RPC_VERSION.into(),
53 method: method.into(),
54 params: Some(json!({ "protocol_version": PROTOCOL_VERSION })),
55 id: Some(id),
56 }
57 }
58
59 pub fn protocol_version(&self) -> Option<u32> {
60 self.params
61 .as_ref()?
62 .as_object()?
63 .get("protocol_version")?
64 .as_u64()?
65 .try_into()
66 .ok()
67 }
68}
69
70#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
71pub struct Response {
72 pub jsonrpc: String,
73 pub id: Value,
74 #[serde(skip_serializing_if = "Option::is_none")]
75 pub result: Option<ResponseResult>,
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub error: Option<RpcError>,
78}
79
80impl Response {
81 pub fn success(id: Value, result: ResponseResult) -> Self {
82 Self {
83 jsonrpc: JSON_RPC_VERSION.into(),
84 id,
85 result: Some(result),
86 error: None,
87 }
88 }
89
90 pub fn failure(id: Value, code: i32, message: impl Into<String>) -> Self {
91 Self {
92 jsonrpc: JSON_RPC_VERSION.into(),
93 id,
94 result: None,
95 error: Some(RpcError {
96 code,
97 message: message.into(),
98 data: None,
99 }),
100 }
101 }
102
103 pub fn failure_with_data(
104 id: Value,
105 code: i32,
106 message: impl Into<String>,
107 data: Value,
108 ) -> Self {
109 Self {
110 jsonrpc: JSON_RPC_VERSION.into(),
111 id,
112 result: None,
113 error: Some(RpcError {
114 code,
115 message: message.into(),
116 data: Some(data),
117 }),
118 }
119 }
120}
121
122#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
123#[serde(tag = "kind", rename_all = "kebab-case")]
124pub enum ResponseResult {
125 AgentInfo(AgentInfo),
126 DeviceList(DeviceList),
127}
128
129#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
130pub struct AgentInfo {
131 pub protocol_version: u32,
132 pub agent_version: String,
133 pub access_mode: String,
134 pub transport: String,
135}
136
137#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
138pub struct DeviceList {
139 pub protocol_version: u32,
140 pub devices: Vec<DeviceSummary>,
141 pub interface_count: usize,
142}
143
144#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
145pub struct DeviceSummary {
146 pub display_name: String,
147 pub vid: u16,
148 pub pid: u16,
149 pub interface_count: usize,
150 pub vendor_interface_count: usize,
151 pub support_label: String,
152 pub support_detail: String,
153 pub capabilities: Vec<String>,
154 pub evidence_label: String,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub evidence_source_count: Option<usize>,
160 pub control_available: bool,
161}
162
163impl DeviceSummary {
164 pub fn usb_identity(&self) -> String {
165 format!("{:04X}:{:04X}", self.vid, self.pid)
166 }
167}
168
169#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
170pub struct RpcError {
171 pub code: i32,
172 pub message: String,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub data: Option<Value>,
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[test]
182 fn creates_a_versioned_json_rpc_request() {
183 let request = Request::new(METHOD_DEVICES_LIST, json!(7));
184 let encoded = serde_json::to_value(&request).unwrap();
185
186 assert_eq!(encoded["jsonrpc"], JSON_RPC_VERSION);
187 assert_eq!(encoded["id"], 7);
188 assert_eq!(encoded["params"]["protocol_version"], PROTOCOL_VERSION);
189 assert_eq!(request.protocol_version(), Some(PROTOCOL_VERSION));
190 }
191
192 #[test]
193 fn accepts_legacy_device_summaries_without_localization_metadata() {
194 let old = json!({
195 "display_name": "Razer Test", "vid": 5426, "pid": 153,
196 "interface_count": 1, "vendor_interface_count": 1,
197 "support_label": "Detected", "support_detail": "Legacy detail",
198 "capabilities": ["DPI"], "evidence_label": "Legacy evidence",
199 "control_available": false
200 });
201 let mut device: DeviceSummary = serde_json::from_value(old.clone()).unwrap();
202 assert_eq!(device.evidence_source_count, None);
203 assert_eq!(serde_json::to_value(&device).unwrap(), old);
204 device.evidence_source_count = Some(3);
205 assert_eq!(
206 serde_json::to_value(&device).unwrap()["evidence_source_count"],
207 3
208 );
209 }
210
211 #[test]
212 fn success_and_error_responses_are_mutually_exclusive() {
213 let success = Response::success(
214 json!(1),
215 ResponseResult::AgentInfo(AgentInfo {
216 protocol_version: PROTOCOL_VERSION,
217 agent_version: "0.1.0".into(),
218 access_mode: "descriptor-only".into(),
219 transport: "stdio-child".into(),
220 }),
221 );
222 let failure = Response::failure(Value::Null, ERROR_PARSE, "Parse error");
223
224 assert!(success.result.is_some());
225 assert!(success.error.is_none());
226 assert!(failure.result.is_none());
227 assert!(failure.error.is_some());
228 }
229}