Skip to main content

lsdocs_rpc/
lib.rs

1//! MessagePack RPC envelope, framing, codec, peer and transports.
2//!
3//! - [`message`]: the msgpack-rpc envelope (`[0, id, method, params]` etc.).
4//! - [`transport`]: length-prefixed framing and the stdio, pipe and in-memory
5//!   transports, including stdout protection for plugins.
6//! - [`Peer`] and [`Connection`]: a symmetric endpoint. Either side can send
7//!   requests and notifications; incoming ones are dispatched through a
8//!   [`Router`].
9//!
10//! The wire format is specified in `spec/wire.md`.
11//!
12//! ```no_run
13//! # async fn demo() -> Result<(), lsdocs_rpc::Error> {
14//! use lsdocs_protocol::{notification, request};
15//! use lsdocs_rpc::{Options, Router, transport};
16//!
17//! let router = Router::new()
18//!     .notification::<notification::Log, _>(|params, _peer| {
19//!         eprintln!("plugin says: {}", params.message);
20//!     });
21//! let (peer, connection) = lsdocs_rpc::connect(transport::memory().0, router, Options::default());
22//! tokio::spawn(connection.run());
23//! peer.request::<request::Shutdown>(&()).await?;
24//! # Ok(()) }
25//! ```
26
27use std::fmt;
28
29use serde::{Deserialize, Serialize};
30
31pub mod message;
32mod peer;
33pub mod trace;
34pub mod transport;
35
36pub use peer::{Connection, Options, Peer, Router, connect};
37
38/// Error codes used in [`RpcError::code`]. They follow JSON-RPC and LSP.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
40#[serde(transparent)]
41pub struct ErrorCode(pub i32);
42
43impl ErrorCode {
44    /// The message could not be decoded.
45    pub const PARSE_ERROR: Self = Self(-32700);
46    /// The message is not a valid request.
47    pub const INVALID_REQUEST: Self = Self(-32600);
48    /// The receiver has no handler for the method.
49    pub const METHOD_NOT_FOUND: Self = Self(-32601);
50    /// The params could not be decoded into the method's params type.
51    pub const INVALID_PARAMS: Self = Self(-32602);
52    /// The handler failed for a reason of its own.
53    pub const INTERNAL_ERROR: Self = Self(-32603);
54    /// The request was cancelled with `$/cancel`.
55    pub const REQUEST_CANCELLED: Self = Self(-32800);
56}
57
58/// An error sent in a response.
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
60pub struct RpcError {
61    /// Kind of error; see [`ErrorCode`].
62    pub code: ErrorCode,
63    /// Human-readable description.
64    pub message: String,
65    /// Extra structured detail.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub data: Option<serde_json::Value>,
68}
69
70impl RpcError {
71    /// Creates an error without extra data.
72    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
73        Self {
74            code,
75            message: message.into(),
76            data: None,
77        }
78    }
79
80    /// An [`ErrorCode::INTERNAL_ERROR`] with the given message.
81    pub fn internal(message: impl Into<String>) -> Self {
82        Self::new(ErrorCode::INTERNAL_ERROR, message)
83    }
84}
85
86impl fmt::Display for RpcError {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "{} (code {})", self.message, self.code.0)
89    }
90}
91
92impl std::error::Error for RpcError {}
93
94/// Why a call on a [`Peer`] failed.
95#[derive(Debug)]
96pub enum Error {
97    /// The other side answered with an error.
98    Remote(RpcError),
99    /// The connection is closed, or closed before a response arrived.
100    Closed,
101    /// No response arrived within [`Options::request_timeout`]. The request
102    /// was cancelled.
103    Timeout,
104    /// The params could not be encoded or the result could not be decoded.
105    Codec(message::CodecError),
106    /// Reading or writing the transport failed.
107    Io(std::io::Error),
108}
109
110impl fmt::Display for Error {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Error::Remote(e) => write!(f, "remote error: {e}"),
114            Error::Closed => f.write_str("connection closed"),
115            Error::Timeout => f.write_str("request timed out"),
116            Error::Codec(e) => write!(f, "codec error: {e}"),
117            Error::Io(e) => write!(f, "transport error: {e}"),
118        }
119    }
120}
121
122impl std::error::Error for Error {
123    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
124        match self {
125            Error::Remote(e) => Some(e),
126            Error::Codec(e) => Some(e),
127            Error::Io(e) => Some(e),
128            Error::Closed | Error::Timeout => None,
129        }
130    }
131}
132
133impl From<message::CodecError> for Error {
134    fn from(e: message::CodecError) -> Self {
135        Error::Codec(e)
136    }
137}