Debian Codegraph @

helix-lsp/src/jsonrpc.rs

raw symbols SCIP
1 //! An implementation of the JSONRPC 2.0 spec types
2
3 // Upstream implementation: https://github.com/paritytech/jsonrpc/tree/38af3c9439aa75481805edf6c05c6622a5ab1e70/core/src/types
4 // Changes from upstream:
5 // * unused functions (almost all non-trait-implementation functions) have been removed
6 // * `#[serde(deny_unknown_fields)]` annotations have been removed on types for compatibility.
7 // (For examples https://github.com/helix-editor/helix/issues/2786, https://github.com/helix-editor/helix/issues/15078)
8 // * some variable names have been lengthened for readability
9
10 use serde::de::{self, DeserializeOwned, Visitor};
11 use serde::{Deserialize, Serialize};
12 use serde_json::Value;
13
14 // https://www.jsonrpc.org/specification#error_object
15 #[derive(Debug, PartialEq, Eq, Clone)]
16 pub enum ErrorCode {
17 ParseError,
18 InvalidRequest,
19 MethodNotFound,
20 InvalidParams,
21 InternalError,
22 ServerError(i64),
23 }
24
25 impl ErrorCode {
26 pub fn code(&self) -> i64 {
27 match *self {
28 ErrorCode::ParseError => -32700,
29 ErrorCode::InvalidRequest => -32600,
30 ErrorCode::MethodNotFound => -32601,
31 ErrorCode::InvalidParams => -32602,
32 ErrorCode::InternalError => -32603,
33 ErrorCode::ServerError(code) => code,
34 }
35 }
36 }
37
38 impl From<i64> for ErrorCode {
39 fn from(code: i64) -> Self {
40 match code {
41 -32700 => ErrorCode::ParseError,
42 -32600 => ErrorCode::InvalidRequest,
43 -32601 => ErrorCode::MethodNotFound,
44 -32602 => ErrorCode::InvalidParams,
45 -32603 => ErrorCode::InternalError,
46 code => ErrorCode::ServerError(code),
47 }
48 }
49 }
50
51 impl<'de> Deserialize<'de> for ErrorCode {
52 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
53 where
54 D: serde::Deserializer<'de>,
55 {
56 let code: i64 = Deserialize::deserialize(deserializer)?;
57 Ok(ErrorCode::from(code))
58 }
59 }
60
61 impl Serialize for ErrorCode {
62 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
63 where
64 S: serde::Serializer,
65 {
66 serializer.serialize_i64(self.code())
67 }
68 }
69
70 #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
71 pub struct Error {
72 pub code: ErrorCode,
73 pub message: String,
74 #[serde(skip_serializing_if = "Option::is_none")]
75 pub data: Option<Value>,
76 }
77
78 impl Error {
79 pub fn invalid_params<M>(message: M) -> Self
80 where
81 M: Into<String>,
82 {
83 Error {
84 code: ErrorCode::InvalidParams,
85 message: message.into(),
86 data: None,
87 }
88 }
89 }
90
91 impl std::fmt::Display for Error {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 write!(f, "{:?}: {}", self.code, self.message)
94 }
95 }
96
97 impl std::error::Error for Error {}
98
99 // https://www.jsonrpc.org/specification#request_object
100
101 /// Request ID
102 #[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize, Serialize)]
103 #[serde(untagged)]
104 pub enum Id {
105 Null,
106 Num(#[serde(deserialize_with = "deserialize_jsonrpc_id_num")] u64),
107 Str(String),
108 }
109
110 fn deserialize_jsonrpc_id_num<'de, D>(deserializer: D) -> Result<u64, D::Error>
111 where
112 D: serde::Deserializer<'de>,
113 {
114 let num = serde_json::Number::deserialize(deserializer)?;
115
116 if let Some(val) = num.as_u64() {
117 return Ok(val);
118 };
119
120 // Accept floats as long as they represent positive whole numbers.
121 // The JSONRPC spec says "Numbers SHOULD NOT contain fractional parts" so we should try to
122 // accept them if possible. The JavaScript type system lumps integers and floats together so
123 // some languages may serialize integer IDs as floats with a zeroed fractional part.
124 // See <https://github.com/helix-editor/helix/issues/12367>.
125 if let Some(val) = num
126 .as_f64()
127 .filter(|f| f.is_sign_positive() && f.fract() == 0.0)
128 {
129 return Ok(val as u64);
130 }
131
132 Err(de::Error::custom(
133 "number must be integer or float representing a whole number in valid u64 range",
134 ))
135 }
136
137 impl std::fmt::Display for Id {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 match self {
140 Id::Null => f.write_str("null"),
141 Id::Num(num) => write!(f, "{}", num),
142 Id::Str(string) => f.write_str(string),
143 }
144 }
145 }
146
147 /// Protocol Version
148 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
149 pub enum Version {
150 V2,
151 }
152
153 impl Serialize for Version {
154 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
155 where
156 S: serde::Serializer,
157 {
158 match *self {
159 Version::V2 => serializer.serialize_str("2.0"),
160 }
161 }
162 }
163
164 struct VersionVisitor;
165
166 impl Visitor<'_> for VersionVisitor {
167 type Value = Version;
168
169 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
170 formatter.write_str("a string")
171 }
172 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
173 where
174 E: de::Error,
175 {
176 match value {
177 "2.0" => Ok(Version::V2),
178 _ => Err(de::Error::custom("invalid version")),
179 }
180 }
181 }
182
183 impl<'de> Deserialize<'de> for Version {
184 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
185 where
186 D: serde::Deserializer<'de>,
187 {
188 deserializer.deserialize_identifier(VersionVisitor)
189 }
190 }
191
192 #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
193 #[serde(untagged)]
194 pub enum Params {
195 None,
196 Array(Vec<Value>),
197 Map(serde_json::Map<String, Value>),
198 }
199
200 impl Params {
201 pub fn parse<D>(self) -> Result<D, Error>
202 where
203 D: DeserializeOwned,
204 {
205 let value: Value = self.into();
206 serde_json::from_value(value)
207 .map_err(|err| Error::invalid_params(format!("Invalid params: {}.", err)))
208 }
209
210 pub fn is_none(&self) -> bool {
211 self == &Params::None
212 }
213 }
214
215 impl From<Params> for Value {
216 fn from(params: Params) -> Value {
217 match params {
218 Params::Array(vec) => Value::Array(vec),
219 Params::Map(map) => Value::Object(map),
220 Params::None => Value::Null,
221 }
222 }
223 }
224
225 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
226 pub struct MethodCall {
227 pub jsonrpc: Option<Version>,
228 pub method: String,
229 #[serde(default = "default_params", skip_serializing_if = "Params::is_none")]
230 pub params: Params,
231 pub id: Id,
232 }
233
234 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
235 pub struct Notification {
236 pub jsonrpc: Option<Version>,
237 pub method: String,
238 #[serde(default = "default_params", skip_serializing_if = "Params::is_none")]
239 pub params: Params,
240 }
241
242 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
243 #[serde(deny_unknown_fields)]
244 #[serde(untagged)]
245 pub enum Call {
246 MethodCall(MethodCall),
247 Notification(Notification),
248 Invalid {
249 // We can attempt to salvage the id out of the invalid request
250 // for better debugging
251 #[serde(default = "default_id")]
252 id: Id,
253 },
254 }
255
256 fn default_params() -> Params {
257 Params::None
258 }
259
260 fn default_id() -> Id {
261 Id::Null
262 }
263
264 impl From<MethodCall> for Call {
265 fn from(method_call: MethodCall) -> Self {
266 Call::MethodCall(method_call)
267 }
268 }
269
270 impl From<Notification> for Call {
271 fn from(notification: Notification) -> Self {
272 Call::Notification(notification)
273 }
274 }
275
276 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
277 #[serde(deny_unknown_fields)]
278 #[serde(untagged)]
279 pub enum Request {
280 Single(Call),
281 Batch(Vec<Call>),
282 }
283
284 // https://www.jsonrpc.org/specification#response_object
285
286 #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
287 pub struct Success {
288 #[serde(skip_serializing_if = "Option::is_none")]
289 pub jsonrpc: Option<Version>,
290 pub result: Value,
291 pub id: Id,
292 }
293
294 #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
295 pub struct Failure {
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub jsonrpc: Option<Version>,
298 pub error: Error,
299 pub id: Id,
300 }
301
302 // Note that failure comes first because we're not using
303 // #[serde(deny_unknown_field)]: we want a request that contains
304 // both `result` and `error` to be a `Failure`.
305 #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
306 #[serde(untagged)]
307 pub enum Output {
308 Failure(Failure),
309 Success(Success),
310 }
311
312 impl From<Output> for Result<Value, Error> {
313 fn from(output: Output) -> Self {
314 match output {
315 Output::Success(success) => Ok(success.result),
316 Output::Failure(failure) => Err(failure.error),
317 }
318 }
319 }
320
321 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
322 #[serde(untagged)]
323 pub enum Response {
324 Single(Output),
325 Batch(Vec<Output>),
326 }
327
328 impl From<Failure> for Response {
329 fn from(failure: Failure) -> Self {
330 Response::Single(Output::Failure(failure))
331 }
332 }
333
334 impl From<Success> for Response {
335 fn from(success: Success) -> Self {
336 Response::Single(Output::Success(success))
337 }
338 }
339
340 #[test]
341 fn method_call_serialize() {
342 use serde_json;
343
344 let m = MethodCall {
345 jsonrpc: Some(Version::V2),
346 method: "update".to_owned(),
347 params: Params::Array(vec![Value::from(1), Value::from(2)]),
348 id: Id::Num(1),
349 };
350
351 let serialized = serde_json::to_string(&m).unwrap();
352 assert_eq!(
353 serialized,
354 r#"{"jsonrpc":"2.0","method":"update","params":[1,2],"id":1}"#
355 );
356 }
357
358 #[test]
359 fn notification_serialize() {
360 use serde_json;
361
362 let n = Notification {
363 jsonrpc: Some(Version::V2),
364 method: "update".to_owned(),
365 params: Params::Array(vec![Value::from(1), Value::from(2)]),
366 };
367
368 let serialized = serde_json::to_string(&n).unwrap();
369 assert_eq!(
370 serialized,
371 r#"{"jsonrpc":"2.0","method":"update","params":[1,2]}"#
372 );
373 }
374
375 #[test]
376 fn serialize_skip_none_params() {
377 use serde_json;
378
379 let m = MethodCall {
380 jsonrpc: Some(Version::V2),
381 method: "shutdown".to_owned(),
382 params: Params::None,
383 id: Id::Num(1),
384 };
385
386 let serialized = serde_json::to_string(&m).unwrap();
387 assert_eq!(
388 serialized,
389 r#"{"jsonrpc":"2.0","method":"shutdown","id":1}"#
390 );
391
392 let n = Notification {
393 jsonrpc: Some(Version::V2),
394 method: "exit".to_owned(),
395 params: Params::None,
396 };
397
398 let serialized = serde_json::to_string(&n).unwrap();
399 assert_eq!(serialized, r#"{"jsonrpc":"2.0","method":"exit"}"#);
400 }
401
402 #[test]
403 fn id_deserialize() {
404 use serde_json;
405
406 let id = r#"8"#;
407 let deserialized: Id = serde_json::from_str(id).unwrap();
408 assert_eq!(deserialized, Id::Num(8));
409
410 let id = r#"4.0"#;
411 let deserialized: Id = serde_json::from_str(id).unwrap();
412 assert_eq!(deserialized, Id::Num(4));
413
414 let id = r#"0.01"#;
415 assert!(serde_json::from_str::<Id>(id).is_err());
416 }
417
418 #[test]
419 fn success_output_deserialize() {
420 use serde_json;
421
422 let dso = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
423
424 let deserialized: Output = serde_json::from_str(dso).unwrap();
425 assert_eq!(
426 deserialized,
427 Output::Success(Success {
428 jsonrpc: Some(Version::V2),
429 result: Value::from(1),
430 id: Id::Num(1)
431 })
432 );
433 }
434
435 #[test]
436 fn success_output_deserialize_with_extra_fields() {
437 use serde_json::{self, json};
438
439 // https://github.com/helix-editor/helix/issues/2786
440 let dso = r#"{"jsonrpc":"2.0","result":1,"id":1,"requestMethod":"initialize"}"#;
441
442 let deserialized: Output = serde_json::from_str(dso).unwrap();
443 assert_eq!(
444 deserialized,
445 Output::Success(Success {
446 jsonrpc: Some(Version::V2),
447 result: Value::from(1),
448 id: Id::Num(1)
449 })
450 );
451
452 // https://github.com/helix-editor/helix/issues/15078
453 let json = r#"{"traceparent":"00-84b1954eb787286f09bf07937689f8cb-5f78c8b6ed6bc71a-00","jsonrpc":"2.0","method":"window/logMessage","params":{"type":5,"message":"Initialized"}}"#;
454 assert_eq!(
455 serde_json::from_str::<Notification>(json).unwrap(),
456 Notification {
457 jsonrpc: Some(Version::V2),
458 method: "window/logMessage".to_owned(),
459 params: Params::Map(
460 json!({"type":5,"message":"Initialized"})
461 .as_object()
462 .unwrap()
463 .clone()
464 ),
465 }
466 );
467 }