1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Typed params and results through `serde` (the `serde` feature): the
//! ecosystem's protocol types (`lsp-types`, MCP schema crates, your own
//! `#[derive(Deserialize)]` structs) in and out of handlers and calls.
//!
//! Values are read from the validated [`Raw`] text the endpoint already holds
//! (so the JSON budgets of [`Limits`](crate::Limits) have been applied) and
//! written as compact JSON, with `serde_json`.
use std::fmt;
use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{self, DeserializeOwned, Visitor},
};
use crate::{
error::{CallError, Error},
error_object::{ErrorCode, ErrorObject, clip_to},
handles::{Call, Peer, Responder},
id::Id,
raw::{Json, Raw},
router::{Context, Params, Router},
};
/// The `INVALID_PARAMS` error for a value that does not fit its type.
/// `serde_json` quotes the offending value, which the peer chose: the text is
/// clipped, as every peer-controlled text the crate repeats is.
fn mismatch(error: &serde_json::Error) -> ErrorObject {
let text = error.to_string();
ErrorObject::invalid_params(format!("invalid params: {}", clip_to(&text, 256)))
}
impl Params<'_> {
/// Deserializes the params into `T` (absent params read as `null`, so
/// `()` and `Option<_>` accept them).
///
/// # Errors
///
/// An `INVALID_PARAMS` [`ErrorObject`] saying what did not fit, ready to
/// return with `?`.
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Position { line: u32, character: u32 }
///
/// let router = Router::new().request("next", |_: &mut (), params, _| {
/// let p: Position = params.deserialize()?;
/// Ok(rpc_io::jsonx::json!([p.line + 1, p.character]))
/// });
/// let (tx, rx) = std::sync::mpsc::channel::<String>();
/// let mut endpoint = Endpoint::new(tx, router, ());
/// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"method":"next","params":{"line":3,"character":7}}"#)?;
/// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"result":[4,7]}"#));
/// endpoint.handle(br#"{"jsonrpc":"2.0","id":2,"method":"next","params":{"line":-1}}"#)?;
/// assert!(rx.try_recv().is_ok_and(|m| m.contains("-32602")));
/// # Ok::<(), rpc_io::Error>(())
/// ```
pub fn deserialize<'de, T: Deserialize<'de>>(&'de self) -> Result<T, ErrorObject> {
let text = self.raw().map_or("null", Raw::as_str);
serde_json::from_str(text).map_err(|e| mismatch(&e))
}
}
impl Raw<'_> {
/// Deserializes the value into `T`.
///
/// # Errors
///
/// An `INVALID_PARAMS` [`ErrorObject`] saying what did not fit.
///
/// # Examples
///
/// ```
/// let raw = rpc_io::Raw::new(r#"{"tabSize": 4}"#)?;
/// let config: std::collections::BTreeMap<String, u32> = raw.deserialize().map_err(|e| e.to_string())?;
/// assert_eq!(config["tabSize"], 4);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn deserialize<'de, T: Deserialize<'de>>(&'de self) -> Result<T, ErrorObject> {
serde_json::from_str(self.as_str()).map_err(|e| mismatch(&e))
}
}
impl Json<'static> {
/// Serializes `value` as compact JSON, to send as params, a result, or
/// error data.
///
/// # Errors
///
/// An `INTERNAL_ERROR` [`ErrorObject`] if `value` cannot be written as
/// JSON (a map with keys that are not strings, or a `Serialize` that
/// fails), ready to return from a handler with `?`.
///
/// # Examples
///
/// ```
/// use rpc_io::Json;
///
/// #[derive(serde::Serialize)]
/// struct Hover { contents: &'static str }
///
/// let json = Json::serialize(&Hover { contents: "fn f()" })?;
/// assert_eq!(json.to_string(), r#"{"contents":"fn f()"}"#);
/// # Ok::<(), rpc_io::ErrorObject>(())
/// ```
pub fn serialize<T: Serialize + ?Sized>(value: &T) -> Result<Json<'static>, ErrorObject> {
serialize(value)
.map_err(|e| ErrorObject::internal_error(format!("the value is not JSON: {e}")))
}
}
fn serialize<T: Serialize + ?Sized>(value: &T) -> Result<Json<'static>, serde_json::Error> {
serde_json::to_string(value).map(|text| Json::Raw(Raw::trusted_owned(text)))
}
/// Serializes `value` into `out` (cleared first), compact.
///
/// `serde_json` writes bytes, so the buffer's bytes are lent to it and taken
/// back as text with one UTF-8 check, keeping the buffer's allocation.
fn serialize_into<T: Serialize + ?Sized>(
out: &mut String,
value: &T,
) -> Result<(), serde_json::Error> {
let mut bytes = core::mem::take(out).into_bytes();
bytes.clear();
let written = serde_json::to_writer(&mut bytes, value);
match String::from_utf8(bytes) {
Ok(text) => *out = text,
// `serde_json` writes UTF-8; text it did not is refused, and the
// buffer is kept (emptied) for the next result.
Err(error) => {
let mut bytes = error.into_bytes();
bytes.clear();
*out = String::from_utf8(bytes).unwrap_or_default();
return written.and(Err(serde::ser::Error::custom("the value is not UTF-8")));
}
}
written
}
impl<S> Router<S> {
/// Answers requests for `method` with a handler that takes its params as
/// `P` and returns `R`, both through `serde`.
///
/// Params that do not deserialize into `P` are answered with
/// `INVALID_PARAMS` without calling the handler; a result that does not
/// serialize is answered with `INTERNAL_ERROR`.
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize)]
/// struct Add { a: i64, b: i64 }
/// #[derive(Serialize)]
/// struct Sum { sum: i64 }
///
/// let router = Router::new().request_typed("add", |_: &mut (), p: Add, _| Ok(Sum { sum: p.a + p.b }));
/// let (tx, rx) = std::sync::mpsc::channel::<String>();
/// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"add","params":{"a":2,"b":3}}"#)?;
/// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"result":{"sum":5}}"#));
/// # Ok::<(), rpc_io::Error>(())
/// ```
#[must_use]
pub fn request_typed<P, R, F>(self, method: &str, mut handler: F) -> Self
where
P: DeserializeOwned,
R: Serialize,
F: FnMut(&mut S, P, &mut Context<'_>) -> Result<R, ErrorObject> + Send + 'static,
{
// The result is written into the endpoint's reused buffer, as
// `request_json`'s is, instead of a string of its own.
self.request_into(method, move |state, params, cx, out| {
let params = params.deserialize::<P>()?;
let result = handler(state, params, cx)?;
serialize_into(out, &result)
.map_err(|e| ErrorObject::internal_error(format!("the value is not JSON: {e}")))?;
Ok(Json::Raw(Raw::trusted(out)))
})
}
/// Handles notifications for `method` with a handler that takes its
/// params as `P`, through `serde`. Params that do not deserialize are
/// reported as [`Event::InvalidParams`](crate::Event::InvalidParams) and
/// the handler is not called.
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
///
/// #[derive(serde::Deserialize)]
/// struct Opened { uri: String }
///
/// let router = Router::new().notification_typed("didOpen", |open: &mut Vec<String>, p: Opened, _| {
/// open.push(p.uri);
/// });
/// let (tx, _rx) = std::sync::mpsc::channel::<String>();
/// let mut endpoint = Endpoint::new(tx, router, Vec::new());
/// endpoint.handle(br#"{"jsonrpc":"2.0","method":"didOpen","params":{"uri":"file:///a"}}"#)?;
/// assert_eq!(endpoint.state(), &["file:///a"]);
/// # Ok::<(), rpc_io::Error>(())
/// ```
#[must_use]
pub fn notification_typed<P, F>(self, method: &str, mut handler: F) -> Self
where
P: DeserializeOwned,
F: FnMut(&mut S, P, &mut Context<'_>) + Send + 'static,
{
self.notification_with(method, move |state, params, cx| {
let params = params.deserialize::<P>()?;
handler(state, params, cx);
Ok(())
})
}
}
impl Peer {
/// Sends a notification whose params are `params`, serialized (it must
/// serialize to an array, an object, or `null` for none).
///
/// # Errors
///
/// [`Error::Serialize`] if `params` cannot be written as JSON; otherwise
/// as [`Peer::notify`].
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
///
/// #[derive(serde::Serialize)]
/// struct Log { message: &'static str }
///
/// let (tx, rx) = std::sync::mpsc::channel::<String>();
/// let endpoint = Endpoint::new(tx, Router::<()>::new(), ());
/// endpoint.peer().notify_typed("log", &Log { message: "hi" })?;
/// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","method":"log","params":{"message":"hi"}}"#));
/// # Ok::<(), rpc_io::Error>(())
/// ```
pub fn notify_typed<T: Serialize + ?Sized>(
&self,
method: &str,
params: &T,
) -> Result<(), Error> {
let params = serialize(params).map_err(|e| Error::Serialize(e.to_string()))?;
self.notify(method, params)
}
/// Sends a request whose params are `params`, serialized; see
/// [`Peer::request`]. Await or wait for the answer as a type with
/// [`Call::wait_typed`].
///
/// # Errors
///
/// [`Error::Serialize`] if `params` cannot be written as JSON; otherwise
/// as [`Peer::request`].
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
///
/// let (tx, rx) = std::sync::mpsc::channel::<String>();
/// let endpoint = Endpoint::new(tx, Router::<()>::new(), ());
/// let call = endpoint.peer().request_typed("sum", &[1, 2, 3])?;
/// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"method":"sum","params":[1,2,3]}"#));
/// # let _ = call;
/// # Ok::<(), rpc_io::Error>(())
/// ```
pub fn request_typed<T: Serialize + ?Sized>(
&self,
method: &str,
params: &T,
) -> Result<Call, Error> {
let params = serialize(params).map_err(|e| Error::Serialize(e.to_string()))?;
self.request(method, params)
}
}
impl Call {
/// Blocks for the answer, as [`wait`](Call::wait), and deserializes the
/// result into `T`.
///
/// # Errors
///
/// As [`wait`](Call::wait); a result that does not deserialize into `T`
/// is [`CallError::InvalidResponse`].
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
///
/// let (tx, _rx) = std::sync::mpsc::channel::<String>();
/// let mut endpoint = Endpoint::new(tx, Router::<()>::new(), ());
/// let call = endpoint.peer().request("sum", ())?;
/// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"result":6}"#)?;
/// assert_eq!(call.wait_typed::<u64>(), Ok(6));
/// # Ok::<(), rpc_io::Error>(())
/// ```
pub fn wait_typed<T: DeserializeOwned>(self) -> Result<T, CallError> {
let raw = self.wait()?;
raw.deserialize().map_err(CallError::InvalidResponse)
}
}
impl Responder {
/// Answers with `value`, serialized.
///
/// # Errors
///
/// [`Error::Serialize`] if `value` cannot be written as JSON: the request
/// is then answered with `INTERNAL_ERROR` instead, so it still gets its
/// one response. Otherwise as [`respond`](Responder::respond).
///
/// # Examples
///
/// ```
/// use rpc_io::{Endpoint, Router};
///
/// let router = Router::new().deferred("m", |_: &mut (), _, _, responder| {
/// responder.ok_typed(&["a", "b"]).ok();
/// });
/// let (tx, rx) = std::sync::mpsc::channel::<String>();
/// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":3,"method":"m"}"#)?;
/// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":3,"result":["a","b"]}"#));
/// # Ok::<(), rpc_io::Error>(())
/// ```
pub fn ok_typed<T: Serialize + ?Sized>(self, value: &T) -> Result<(), Error> {
match serialize(value) {
Ok(json) => self.ok(json),
Err(error) => {
let refusal =
ErrorObject::internal_error("the result could not be written as JSON");
let _answered = self.err(refusal);
Err(Error::Serialize(error.to_string()))
}
}
}
}
/// An integer, a string, `null`, or for a [`RawNumber`](Id::RawNumber) the
/// number through `serde_json::Number`: exact for integers within `u64`, the
/// nearest `f64` otherwise.
impl Serialize for Id<'_> {
fn serialize<Z: Serializer>(&self, serializer: Z) -> Result<Z::Ok, Z::Error> {
match self {
Id::Number(n) => serializer.serialize_i64(*n),
Id::String(s) => serializer.serialize_str(s),
Id::RawNumber(text) => text
.parse::<serde_json::Number>()
.map_err(serde::ser::Error::custom)?
.serialize(serializer),
Id::Null => serializer.serialize_none(),
}
}
}
/// An integer within `i64`, or a string: the ids [`Id`] holds.
impl<'de> Deserialize<'de> for Id<'static> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct IdVisitor;
impl Visitor<'_> for IdVisitor {
type Value = Id<'static>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("an integer or a string")
}
fn visit_i64<E: de::Error>(self, n: i64) -> Result<Self::Value, E> {
Ok(Id::Number(n))
}
fn visit_u64<E: de::Error>(self, n: u64) -> Result<Self::Value, E> {
i64::try_from(n)
.map(Id::Number)
.map_err(|_| E::custom("an integer id must fit in i64"))
}
fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
Ok(Id::from(s.to_owned()))
}
fn visit_string<E: de::Error>(self, s: String) -> Result<Self::Value, E> {
Ok(Id::from(s))
}
}
deserializer.deserialize_any(IdVisitor)
}
}
/// The integer.
impl Serialize for ErrorCode {
fn serialize<Z: Serializer>(&self, serializer: Z) -> Result<Z::Ok, Z::Error> {
serializer.serialize_i64(self.0)
}
}
/// An integer.
impl<'de> Deserialize<'de> for ErrorCode {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
i64::deserialize(deserializer).map(ErrorCode)
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use std::collections::BTreeMap;
use super::*;
#[test]
fn test_id_and_error_code_round_trip() {
for id in [Id::from(-7), Id::from("x\"y")] {
let text = serde_json::to_string(&id).unwrap_or_default();
assert_eq!(text, id.to_string());
assert_eq!(serde_json::from_str::<Id<'static>>(&text).ok(), Some(id));
}
assert!(serde_json::from_str::<Id<'static>>("18446744073709551615").is_err());
assert!(serde_json::from_str::<Id<'static>>("1.5").is_err());
assert_eq!(
serde_json::to_string(&Id::Null).ok().as_deref(),
Some("null")
);
let big = Id::RawNumber("18446744073709551615".into());
assert_eq!(
serde_json::to_string(&big).ok().as_deref(),
Some("18446744073709551615")
);
assert_eq!(
serde_json::to_string(&Id::RawNumber("0.5".into()))
.ok()
.as_deref(),
Some("0.5")
);
assert_eq!(
serde_json::from_str::<Id<'static>>("5").ok(),
Some(Id::from(5))
);
let code = ErrorCode::METHOD_NOT_FOUND;
assert_eq!(serde_json::to_string(&code).ok().as_deref(), Some("-32601"));
assert_eq!(serde_json::from_str::<ErrorCode>("-32601").ok(), Some(code));
}
#[test]
fn test_results_are_written_whole_into_the_reused_buffer() {
let mut out = String::from("stale");
let value = ("é\u{2028}\"\n😀", 1.5, [Some(1), None]);
assert!(serialize_into(&mut out, &value).is_ok());
assert_eq!(out, serde_json::to_string(&value).unwrap_or_default());
let mut map = BTreeMap::new();
let _none = map.insert(vec![1u8], 1u8); // non-string keys
assert!(serialize_into(&mut out, &map).is_err());
// Through a typed handler, the failure is an `INTERNAL_ERROR` answer.
let router = Router::new().request_typed("m", |_: &mut (), _: (), _| {
let mut map = BTreeMap::new();
let _none = map.insert(vec![1u8], 1u8);
Ok(map)
});
let (tx, rx) = std::sync::mpsc::channel::<String>();
let mut endpoint = crate::Endpoint::new(tx, router, ());
assert!(
endpoint
.handle(br#"{"jsonrpc":"2.0","id":1,"method":"m"}"#)
.is_ok()
);
assert!(rx.try_recv().is_ok_and(|m| m.contains("-32603")));
}
#[test]
fn test_unserializable_values_are_errors() {
let mut map = BTreeMap::new();
let _none = map.insert(vec![1u8], 1u8); // non-string keys
let error = Json::serialize(&map).err();
assert_eq!(error.map(|e| e.code()), Some(ErrorCode::INTERNAL_ERROR));
}
}