Skip to main content

lsdocs_rpc/
message.rs

1//! The msgpack-rpc envelope.
2//!
3//! Every frame holds one message, a MessagePack array:
4//!
5//! | Message      | Shape                                 |
6//! |--------------|---------------------------------------|
7//! | request      | `[0, id, method, params]`             |
8//! | response     | `[1, id, error, result]`              |
9//! | notification | `[2, method, params]`                 |
10//!
11//! `params` is an array of arguments, as msgpack-rpc specifies. lsdocs
12//! methods take one argument (the params struct), or none when the params
13//! type is `()`. A response has a nil `error` and a `result` on success, or an
14//! [`RpcError`] map and a nil `result` on failure.
15//!
16//! Decoding does not decode the params or result: they are handed on as raw
17//! MessagePack so the receiver can decode straight into its typed value.
18
19use bytes::{BufMut, Bytes, BytesMut};
20use rmp::Marker;
21use serde::{Deserialize, Serialize};
22
23use crate::RpcError;
24
25const REQUEST: u8 = 0;
26const RESPONSE: u8 = 1;
27const NOTIFICATION: u8 = 2;
28/// MessagePack `nil`.
29const NIL: &[u8] = &[0xc0];
30
31/// A decoded message. Params and results stay encoded.
32#[derive(Debug, Clone, PartialEq)]
33pub enum Message {
34    /// A request expecting a response.
35    Request {
36        /// Request id, unique among the sender's in-flight requests.
37        id: u32,
38        /// Method name.
39        method: String,
40        /// The single argument, still encoded; `nil` if there was none.
41        params: Bytes,
42    },
43    /// A response to a request.
44    Response {
45        /// Id of the request this answers.
46        id: u32,
47        /// The encoded result, or the error.
48        result: Result<Bytes, RpcError>,
49    },
50    /// A notification.
51    Notification {
52        /// Method name.
53        method: String,
54        /// The single argument, still encoded; `nil` if there was none.
55        params: Bytes,
56    },
57}
58
59/// Why a frame could not be decoded or a value encoded.
60#[derive(Debug)]
61pub struct CodecError(pub String);
62
63impl std::fmt::Display for CodecError {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.write_str(&self.0)
66    }
67}
68
69impl std::error::Error for CodecError {}
70
71fn err(msg: impl std::fmt::Display) -> CodecError {
72    CodecError(msg.to_string())
73}
74
75/// Encodes a value with the protocol's rules (structs as maps).
76fn encode_value<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, CodecError> {
77    lsdocs_protocol::msgpack::encode(value).map_err(err)
78}
79
80/// Writes `params` as the msgpack-rpc argument array: `[]` for a unit/nil
81/// value, otherwise `[params]`.
82fn put_params<T: Serialize + ?Sized>(buf: &mut BytesMut, params: &T) -> Result<(), CodecError> {
83    let value = encode_value(params)?;
84    let mut w = buf.writer();
85    if value == NIL {
86        rmp::encode::write_array_len(&mut w, 0).map_err(err)?;
87    } else {
88        rmp::encode::write_array_len(&mut w, 1).map_err(err)?;
89        w.get_mut().put_slice(&value);
90    }
91    Ok(())
92}
93
94/// Encodes a request.
95pub fn encode_request<T: Serialize + ?Sized>(
96    id: u32,
97    method: &str,
98    params: &T,
99) -> Result<Bytes, CodecError> {
100    let mut buf = BytesMut::new();
101    let mut w = (&mut buf).writer();
102    rmp::encode::write_array_len(&mut w, 4).map_err(err)?;
103    rmp::encode::write_pfix(&mut w, REQUEST).map_err(err)?;
104    rmp::encode::write_uint(&mut w, id.into()).map_err(err)?;
105    rmp::encode::write_str(&mut w, method).map_err(err)?;
106    put_params(&mut buf, params)?;
107    Ok(buf.freeze())
108}
109
110/// Encodes a notification.
111pub fn encode_notification<T: Serialize + ?Sized>(
112    method: &str,
113    params: &T,
114) -> Result<Bytes, CodecError> {
115    let mut buf = BytesMut::new();
116    let mut w = (&mut buf).writer();
117    rmp::encode::write_array_len(&mut w, 3).map_err(err)?;
118    rmp::encode::write_pfix(&mut w, NOTIFICATION).map_err(err)?;
119    rmp::encode::write_str(&mut w, method).map_err(err)?;
120    put_params(&mut buf, params)?;
121    Ok(buf.freeze())
122}
123
124/// Encodes a successful response whose result is already encoded.
125pub fn encode_response_raw(id: u32, result: &[u8]) -> Bytes {
126    let mut buf = BytesMut::with_capacity(8 + result.len());
127    put_response_header(&mut buf, id);
128    buf.put_slice(NIL);
129    buf.put_slice(result);
130    buf.freeze()
131}
132
133/// Writes `[1, id, ` of a response: the array header, the kind and the id,
134/// encoded by hand since writing to memory cannot fail.
135fn put_response_header(buf: &mut BytesMut, id: u32) {
136    buf.put_u8(0x94); // fixarray of 4
137    buf.put_u8(RESPONSE); // positive fixint
138    match id {
139        0..0x80 => buf.put_u8(id as u8),
140        0x80..=0xff => {
141            buf.put_u8(0xcc);
142            buf.put_u8(id as u8);
143        }
144        0x100..=0xffff => {
145            buf.put_u8(0xcd);
146            buf.put_u16(id as u16);
147        }
148        _ => {
149            buf.put_u8(0xce);
150            buf.put_u32(id);
151        }
152    }
153}
154
155/// Encodes a successful response.
156pub fn encode_response<T: Serialize + ?Sized>(id: u32, result: &T) -> Result<Bytes, CodecError> {
157    Ok(encode_response_raw(id, &encode_value(result)?))
158}
159
160/// Encodes an error response.
161pub fn encode_error(id: u32, error: &RpcError) -> Bytes {
162    let mut buf = BytesMut::new();
163    put_response_header(&mut buf, id);
164    match encode_value(error) {
165        Ok(error) => buf.put_slice(&error),
166        Err(_) => buf.put_slice(UNENCODABLE_ERROR),
167    }
168    buf.put_slice(NIL);
169    buf.freeze()
170}
171
172/// `{"code": -32603, "message": "unencodable error"}`, sent when an error's
173/// `data` cannot be encoded.
174const UNENCODABLE_ERROR: &[u8] = b"\x82\xa4code\xd1\x80\xa5\xa7message\xb1unencodable error";
175
176/// Decodes one frame.
177pub fn decode(frame: Bytes) -> Result<Message, CodecError> {
178    let mut rd: &[u8] = &frame;
179    let len =
180        rmp::decode::read_array_len(&mut rd).map_err(|e| err(format!("not an array: {e}")))?;
181    let kind: u8 =
182        rmp::decode::read_int(&mut rd).map_err(|e| err(format!("bad message type: {e}")))?;
183    let message = match (kind, len) {
184        (REQUEST, 4) => {
185            let id = read_id(&mut rd)?;
186            let method = read_method(&mut rd)?;
187            let params = read_params(&frame, &mut rd)?;
188            Message::Request { id, method, params }
189        }
190        (RESPONSE, 4) => {
191            let id = read_id(&mut rd)?;
192            let error = if rd.first() == Some(&0xc0) {
193                rd = &rd[1..];
194                None
195            } else {
196                let mut de = rmp_serde::Deserializer::new(&mut rd);
197                Some(
198                    RpcError::deserialize(&mut de)
199                        .map_err(|e| err(format!("bad error object: {e}")))?,
200                )
201            };
202            let result = match error {
203                Some(error) => Err(error),
204                None => Ok(slice_rest(&frame, rd)),
205            };
206            Message::Response { id, result }
207        }
208        (NOTIFICATION, 3) => {
209            let method = read_method(&mut rd)?;
210            let params = read_params(&frame, &mut rd)?;
211            Message::Notification { method, params }
212        }
213        (REQUEST | RESPONSE | NOTIFICATION, len) => {
214            return Err(err(format!("message type {kind} with {len} elements")));
215        }
216        (kind, _) => return Err(err(format!("unknown message type {kind}"))),
217    };
218    Ok(message)
219}
220
221/// The id of a request frame, if `frame` looks like a request. Used to answer
222/// a request whose params could not be decoded.
223pub fn peek_request_id(frame: &[u8]) -> Option<u32> {
224    let mut rd = frame;
225    let len = rmp::decode::read_array_len(&mut rd).ok()?;
226    let kind: u8 = rmp::decode::read_int(&mut rd).ok()?;
227    if kind != REQUEST || len != 4 {
228        return None;
229    }
230    read_id(&mut rd).ok()
231}
232
233fn read_id(rd: &mut &[u8]) -> Result<u32, CodecError> {
234    rmp::decode::read_int(rd).map_err(|e| err(format!("bad message id: {e}")))
235}
236
237fn read_method(rd: &mut &[u8]) -> Result<String, CodecError> {
238    let len =
239        rmp::decode::read_str_len(rd).map_err(|e| err(format!("bad method name: {e}")))? as usize;
240    if rd.len() < len {
241        return Err(err("truncated method name"));
242    }
243    let (name, rest) = rd.split_at(len);
244    *rd = rest;
245    String::from_utf8(name.to_vec()).map_err(|_| err("method name is not UTF-8"))
246}
247
248/// Reads the argument array header and returns the single argument.
249fn read_params(frame: &Bytes, rd: &mut &[u8]) -> Result<Bytes, CodecError> {
250    match rmp::decode::read_marker(rd).map_err(|_| err("missing params"))? {
251        Marker::FixArray(0) => Ok(Bytes::from_static(NIL)),
252        Marker::FixArray(1) => Ok(slice_rest(frame, rd)),
253        Marker::FixArray(n) => Err(err(format!("expected at most 1 argument, got {n}"))),
254        Marker::Array16 | Marker::Array32 => Err(err("expected at most 1 argument")),
255        _ => Err(err("params must be an array")),
256    }
257}
258
259/// The part of `frame` that `rest` (a suffix of it) covers, without copying.
260fn slice_rest(frame: &Bytes, rest: &[u8]) -> Bytes {
261    frame.slice(frame.len() - rest.len()..)
262}
263
264#[cfg(test)]
265mod tests {
266    #![allow(clippy::unwrap_used, clippy::panic)]
267    use super::*;
268    use crate::ErrorCode;
269    use lsdocs_protocol::{ProgramInfo, msgpack};
270
271    fn info() -> ProgramInfo {
272        ProgramInfo {
273            name: "x".into(),
274            version: "1".into(),
275        }
276    }
277
278    #[test]
279    fn request_round_trip() {
280        let frame = encode_request(7, "parse", &info()).unwrap();
281        let Message::Request { id, method, params } = decode(frame).unwrap() else {
282            panic!()
283        };
284        assert_eq!((id, method.as_str()), (7, "parse"));
285        assert_eq!(msgpack::decode::<ProgramInfo>(&params).unwrap(), info());
286    }
287
288    #[test]
289    fn request_is_a_plain_msgpack_rpc_array() {
290        // [0, 300, "m", [{"name": "x", "version": "1"}]] as decoded by a
291        // generic reader.
292        let frame = encode_request(300, "m", &info()).unwrap();
293        let value: serde_json::Value = rmp_serde::from_slice(&frame).unwrap();
294        assert_eq!(
295            value,
296            serde_json::json!([0, 300, "m", [{"name": "x", "version": "1"}]])
297        );
298    }
299
300    #[test]
301    fn unit_params_are_an_empty_array() {
302        let frame = encode_notification("initialized", &()).unwrap();
303        let value: serde_json::Value = rmp_serde::from_slice(&frame).unwrap();
304        assert_eq!(value, serde_json::json!([2, "initialized", []]));
305        let Message::Notification { params, .. } = decode(frame).unwrap() else {
306            panic!()
307        };
308        msgpack::decode::<()>(&params).unwrap();
309    }
310
311    /// The worked example in spec/wire.md.
312    #[test]
313    fn spec_example_bytes() {
314        let frame = encode_notification("initialized", &()).unwrap();
315        assert_eq!(
316            frame.as_ref(),
317            b"\x93\x02\xabinitialized\x90",
318            "update spec/wire.md if this changes"
319        );
320    }
321
322    #[test]
323    fn success_response_round_trip() {
324        let frame = encode_response(9, &info()).unwrap();
325        let value: serde_json::Value = rmp_serde::from_slice(&frame).unwrap();
326        assert_eq!(
327            value,
328            serde_json::json!([1, 9, null, {"name": "x", "version": "1"}])
329        );
330        let Message::Response { id, result } = decode(frame).unwrap() else {
331            panic!()
332        };
333        assert_eq!(id, 9);
334        assert_eq!(
335            msgpack::decode::<ProgramInfo>(&result.unwrap()).unwrap(),
336            info()
337        );
338    }
339
340    #[test]
341    fn error_response_round_trip() {
342        let error = RpcError::new(ErrorCode::METHOD_NOT_FOUND, "no such method: x");
343        let frame = encode_error(3, &error);
344        let value: serde_json::Value = rmp_serde::from_slice(&frame).unwrap();
345        assert_eq!(
346            value,
347            serde_json::json!([1, 3, {"code": -32601, "message": "no such method: x"}, null])
348        );
349        assert_eq!(
350            decode(frame).unwrap(),
351            Message::Response {
352                id: 3,
353                result: Err(error)
354            }
355        );
356    }
357
358    #[test]
359    fn hand_encoded_parts_match_rmp() {
360        let error: RpcError = rmp_serde::from_slice(UNENCODABLE_ERROR).unwrap();
361        assert_eq!(error, RpcError::internal("unencodable error"));
362        for id in [0, 0x7f, 0x80, 0xff, 0x100, 0xffff, 0x10000, u32::MAX] {
363            let frame = encode_response_raw(id, NIL);
364            let value: serde_json::Value = rmp_serde::from_slice(&frame).unwrap();
365            assert_eq!(value, serde_json::json!([1, id, null, null]));
366        }
367    }
368
369    #[test]
370    fn malformed_frames_are_rejected() {
371        let bad = |v: serde_json::Value| decode(Bytes::from(rmp_serde::to_vec(&v).unwrap()));
372        assert!(bad(serde_json::json!({"not": "an array"})).is_err());
373        assert!(bad(serde_json::json!([5, 1, "m", []])).is_err());
374        assert!(bad(serde_json::json!([0, 1, "m"])).is_err());
375        assert!(bad(serde_json::json!([0, 1, "m", [1, 2]])).is_err());
376        assert!(bad(serde_json::json!([0, -1, "m", []])).is_err());
377        assert!(bad(serde_json::json!([2, "m", {"k": 1}])).is_err());
378    }
379
380    #[test]
381    fn peek_finds_request_ids_only() {
382        assert_eq!(
383            peek_request_id(&encode_request(5, "m", &()).unwrap()),
384            Some(5)
385        );
386        assert_eq!(
387            peek_request_id(&encode_notification("m", &()).unwrap()),
388            None
389        );
390    }
391}