Skip to main content

lsdocs_rpc/
peer.rs

1//! The symmetric RPC endpoint.
2
3use std::collections::HashMap;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
7use std::sync::{Arc, Mutex, PoisonError};
8use std::time::Duration;
9
10use bytes::Bytes;
11use futures_util::{SinkExt, StreamExt};
12use lsdocs_protocol::{CancelParams, Notification, Request, msgpack, notification::Cancel};
13use serde::{Serialize, de::DeserializeOwned};
14use tokio::sync::{Notify, Semaphore, mpsc, oneshot};
15use tokio::task::{AbortHandle, JoinSet};
16use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec};
17
18use crate::message::{self, CodecError, Message};
19use crate::transport::{self, BoxWriter, Transport};
20use crate::{Error, ErrorCode, RpcError};
21
22type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
23type RequestHandler =
24    Arc<dyn Fn(Bytes, Peer) -> BoxFuture<Result<Vec<u8>, RpcError>> + Send + Sync>;
25type NotificationHandler = Arc<dyn Fn(Bytes, &Peer) + Send + Sync>;
26
27/// Settings for a connection.
28#[derive(Debug, Clone)]
29pub struct Options {
30    /// Largest frame accepted or sent, in bytes.
31    pub max_frame_len: usize,
32    /// How long an outgoing request waits for its response before failing
33    /// with [`Error::Timeout`] and being cancelled. `None` waits forever.
34    pub request_timeout: Option<Duration>,
35    /// Most incoming requests handled at once; further ones wait. `None` is
36    /// unlimited. Notifications are not limited.
37    pub max_concurrency: Option<usize>,
38    /// Outgoing frames queued before senders wait.
39    pub send_queue: usize,
40}
41
42impl Default for Options {
43    fn default() -> Self {
44        Self {
45            max_frame_len: transport::DEFAULT_MAX_FRAME_LEN,
46            request_timeout: None,
47            max_concurrency: None,
48            send_queue: 64,
49        }
50    }
51}
52
53/// Handlers for incoming requests and notifications, keyed by method.
54///
55/// A request with no handler is answered with
56/// [`ErrorCode::METHOD_NOT_FOUND`]; a notification with no handler is
57/// ignored. `$/cancel` is handled by the connection itself.
58#[derive(Clone, Default)]
59pub struct Router {
60    requests: HashMap<String, RequestHandler>,
61    notifications: HashMap<String, NotificationHandler>,
62}
63
64impl std::fmt::Debug for Router {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("Router")
67            .field("requests", &self.requests.keys().collect::<Vec<_>>())
68            .field(
69                "notifications",
70                &self.notifications.keys().collect::<Vec<_>>(),
71            )
72            .finish()
73    }
74}
75
76impl Router {
77    /// An empty router.
78    pub fn new() -> Self {
79        Self::default()
80    }
81
82    /// Handles request `R`. The handler gets the decoded params and a
83    /// [`Peer`] for calling back the other side. Params that fail to decode
84    /// are answered with [`ErrorCode::INVALID_PARAMS`] without calling it.
85    pub fn request<R, F, Fut>(mut self, handler: F) -> Self
86    where
87        R: Request,
88        R::Params: Send + 'static,
89        F: Fn(R::Params, Peer) -> Fut + Send + Sync + 'static,
90        Fut: Future<Output = Result<R::Result, RpcError>> + Send + 'static,
91    {
92        let handler: RequestHandler = Arc::new(
93            move |raw: Bytes, peer: Peer| match msgpack::decode::<R::Params>(&raw) {
94                Ok(params) => {
95                    let fut = handler(params, peer);
96                    Box::pin(async move {
97                        let result = fut.await?;
98                        msgpack::encode(&result).map_err(|e| {
99                            RpcError::internal(format!("failed to encode result: {e}"))
100                        })
101                    }) as BoxFuture<_>
102                }
103                Err(e) => Box::pin(std::future::ready(Err(RpcError::new(
104                    ErrorCode::INVALID_PARAMS,
105                    format!("invalid params for `{}`: {e}", R::METHOD),
106                )))),
107            },
108        );
109        self.requests.insert(R::METHOD.to_owned(), handler);
110        self
111    }
112
113    /// Handles notification `N`. Notification handlers run one at a time, in
114    /// arrival order, on the connection's task, so they should be quick;
115    /// spawn a task for slow work. Params that fail to decode are logged and
116    /// dropped.
117    pub fn notification<N, F>(mut self, handler: F) -> Self
118    where
119        N: Notification,
120        F: Fn(N::Params, &Peer) + Send + Sync + 'static,
121    {
122        let handler: NotificationHandler =
123            Arc::new(
124                move |raw: Bytes, peer: &Peer| match msgpack::decode::<N::Params>(&raw) {
125                    Ok(params) => handler(params, peer),
126                    Err(e) => tracing::warn!(
127                        method = N::METHOD,
128                        "dropping notification with invalid params: {e}"
129                    ),
130                },
131            );
132        self.notifications.insert(N::METHOD.to_owned(), handler);
133        self
134    }
135}
136
137/// One end of a connection. Cheap to clone; all clones share the
138/// connection.
139#[derive(Clone)]
140pub struct Peer {
141    inner: Arc<Inner>,
142}
143
144struct Inner {
145    /// Queue to the writer task; `None` once the connection is shutting down.
146    tx: Mutex<Option<mpsc::Sender<Bytes>>>,
147    /// Outgoing requests awaiting a response.
148    pending: Mutex<HashMap<u32, oneshot::Sender<Result<Bytes, RpcError>>>>,
149    next_id: AtomicU32,
150    closing: AtomicBool,
151    close: Notify,
152    options: Options,
153}
154
155impl std::fmt::Debug for Peer {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("Peer")
158            .field("closing", &self.inner.closing.load(Ordering::Relaxed))
159            .finish_non_exhaustive()
160    }
161}
162
163/// Creates a connection over `transport`. Returns the [`Peer`] for sending
164/// and the [`Connection`] that must be run (usually spawned) for anything to
165/// happen.
166pub fn connect(transport: Transport, router: Router, options: Options) -> (Peer, Connection) {
167    let (tx, rx) = mpsc::channel(options.send_queue.max(1));
168    let peer = Peer {
169        inner: Arc::new(Inner {
170            tx: Mutex::new(Some(tx)),
171            pending: Mutex::new(HashMap::new()),
172            next_id: AtomicU32::new(1),
173            closing: AtomicBool::new(false),
174            close: Notify::new(),
175            options,
176        }),
177    };
178    let connection = Connection {
179        peer: peer.clone(),
180        transport,
181        router,
182        rx,
183    };
184    (peer, connection)
185}
186
187impl Peer {
188    /// Sends request `R` and waits for its result.
189    pub async fn request<R: Request>(&self, params: &R::Params) -> Result<R::Result, Error> {
190        self.call(R::METHOD, params).await
191    }
192
193    /// Sends a request by method name and waits for its result.
194    ///
195    /// If the returned future is dropped before the response arrives, or
196    /// [`Options::request_timeout`] passes, `$/cancel` is sent for it.
197    pub async fn call<P, T>(&self, method: &str, params: &P) -> Result<T, Error>
198    where
199        P: Serialize + ?Sized,
200        T: DeserializeOwned,
201    {
202        let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
203        let frame = message::encode_request(id, method, params)?;
204        let (tx, rx) = oneshot::channel();
205        self.inner
206            .pending
207            .lock()
208            .unwrap_or_else(PoisonError::into_inner)
209            .insert(id, tx);
210        let mut guard = CancelOnDrop {
211            peer: self,
212            id,
213            armed: true,
214        };
215        if self.inner.closing.load(Ordering::SeqCst) {
216            return Err(Error::Closed);
217        }
218        if let Err(e) = self.send(frame).await {
219            // Never sent, so there is nothing to cancel.
220            guard.armed = false;
221            return Err(e);
222        }
223        let response = match self.inner.options.request_timeout {
224            Some(limit) => match tokio::time::timeout(limit, rx).await {
225                Ok(response) => response,
226                Err(_) => return Err(Error::Timeout),
227            },
228            None => rx.await,
229        };
230        guard.armed = false;
231        let bytes = response
232            .map_err(|_| Error::Closed)?
233            .map_err(Error::Remote)?;
234        msgpack::decode(&bytes)
235            .map_err(|e| Error::Codec(CodecError(format!("invalid result for `{method}`: {e}"))))
236    }
237
238    /// Sends notification `N`.
239    pub async fn notify<N: Notification>(&self, params: &N::Params) -> Result<(), Error> {
240        self.notify_raw(N::METHOD, params).await
241    }
242
243    /// Sends a notification by method name.
244    pub async fn notify_raw<P: Serialize + ?Sized>(
245        &self,
246        method: &str,
247        params: &P,
248    ) -> Result<(), Error> {
249        self.send(message::encode_notification(method, params)?)
250            .await
251    }
252
253    /// Asks the connection to stop reading and shut down gracefully. In-flight
254    /// incoming requests still finish and are answered; outgoing requests
255    /// still waiting fail with [`Error::Closed`].
256    pub fn close(&self) {
257        self.inner.closing.store(true, Ordering::SeqCst);
258        self.inner.close.notify_one();
259    }
260
261    /// Whether the connection has started shutting down.
262    pub fn is_closed(&self) -> bool {
263        self.inner.closing.load(Ordering::SeqCst)
264    }
265
266    async fn send(&self, frame: Bytes) -> Result<(), Error> {
267        let limit = self.inner.options.max_frame_len;
268        if frame.len() > limit {
269            return Err(Error::Codec(CodecError(format!(
270                "message of {} bytes exceeds the {limit} byte frame limit",
271                frame.len()
272            ))));
273        }
274        let tx = self
275            .inner
276            .tx
277            .lock()
278            .unwrap_or_else(PoisonError::into_inner)
279            .clone()
280            .ok_or(Error::Closed)?;
281        tx.send(frame).await.map_err(|_| Error::Closed)
282    }
283
284    fn try_send(&self, frame: Bytes) {
285        if let Some(tx) = self
286            .inner
287            .tx
288            .lock()
289            .unwrap_or_else(PoisonError::into_inner)
290            .as_ref()
291        {
292            let _ = tx.try_send(frame);
293        }
294    }
295}
296
297/// Cancels an outgoing request that is abandoned before its response.
298struct CancelOnDrop<'a> {
299    peer: &'a Peer,
300    id: u32,
301    armed: bool,
302}
303
304impl Drop for CancelOnDrop<'_> {
305    fn drop(&mut self) {
306        let was_pending = self
307            .peer
308            .inner
309            .pending
310            .lock()
311            .unwrap_or_else(PoisonError::into_inner)
312            .remove(&self.id)
313            .is_some();
314        if self.armed
315            && was_pending
316            && let Ok(frame) =
317                message::encode_notification(Cancel::METHOD, &CancelParams { id: self.id })
318        {
319            self.peer.try_send(frame);
320        }
321    }
322}
323
324/// Drives a connection: reads and dispatches incoming messages and writes
325/// outgoing ones. Created by [`connect`].
326pub struct Connection {
327    peer: Peer,
328    transport: Transport,
329    router: Router,
330    rx: mpsc::Receiver<Bytes>,
331}
332
333impl std::fmt::Debug for Connection {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.debug_struct("Connection").finish_non_exhaustive()
336    }
337}
338
339/// Bookkeeping for incoming requests being handled.
340struct Running {
341    tasks: JoinSet<()>,
342    by_request: HashMap<u32, AbortHandle>,
343    by_task: HashMap<tokio::task::Id, u32>,
344}
345
346impl Connection {
347    /// Runs until the other side closes the stream, the transport fails, or
348    /// [`Peer::close`] is called. Then waits for in-flight incoming requests
349    /// to finish and flushes everything queued before returning.
350    pub async fn run(self) -> Result<(), Error> {
351        let Connection {
352            peer,
353            transport,
354            router,
355            rx,
356        } = self;
357        let options = peer.inner.options.clone();
358        let mut reader = FramedRead::new(transport.reader, transport::codec(options.max_frame_len));
359        let writer = FramedWrite::new(transport.writer, transport::codec(options.max_frame_len));
360        let write_task = tokio::spawn(write_loop(writer, rx, peer.clone()));
361        let limit = options
362            .max_concurrency
363            .map(|n| Arc::new(Semaphore::new(n.max(1))));
364        let mut running = Running {
365            tasks: JoinSet::new(),
366            by_request: HashMap::new(),
367            by_task: HashMap::new(),
368        };
369
370        let read_result = loop {
371            tokio::select! {
372                frame = reader.next() => match frame {
373                    None => break Ok(()),
374                    Some(Err(e)) => break Err(e),
375                    Some(Ok(frame)) => {
376                        let frame = frame.freeze();
377                        crate::trace::frame("recv", &frame);
378                        dispatch(frame, &peer, &router, &limit, &mut running).await;
379                    }
380                },
381                Some(joined) = running.tasks.join_next_with_id(), if !running.tasks.is_empty() => {
382                    let task = match joined {
383                        Ok((task, ())) => task,
384                        Err(e) => e.id(),
385                    };
386                    if let Some(id) = running.by_task.remove(&task) {
387                        running.by_request.remove(&id);
388                    }
389                }
390                () = peer.inner.close.notified() => break Ok(()),
391            }
392        };
393
394        // Stop new outgoing requests, then fail the ones still waiting.
395        peer.inner.closing.store(true, Ordering::SeqCst);
396        peer.inner
397            .pending
398            .lock()
399            .unwrap_or_else(PoisonError::into_inner)
400            .clear();
401        // Let in-flight handlers finish and queue their responses.
402        while running.tasks.join_next().await.is_some() {}
403        // Closing the queue lets the writer drain it and shut down.
404        drop(
405            peer.inner
406                .tx
407                .lock()
408                .unwrap_or_else(PoisonError::into_inner)
409                .take(),
410        );
411        let write_result = write_task
412            .await
413            .map_err(|e| Error::Io(std::io::Error::other(e)))?;
414
415        read_result.map_err(Error::Io)?;
416        write_result.map_err(Error::Io)
417    }
418}
419
420async fn dispatch(
421    frame: Bytes,
422    peer: &Peer,
423    router: &Router,
424    limit: &Option<Arc<Semaphore>>,
425    running: &mut Running,
426) {
427    let message = match message::decode(frame.clone()) {
428        Ok(message) => message,
429        Err(e) => {
430            tracing::warn!("dropping malformed message: {e}");
431            if let Some(id) = message::peek_request_id(&frame) {
432                let error = RpcError::new(ErrorCode::INVALID_REQUEST, e.to_string());
433                let _ = peer.send(message::encode_error(id, &error)).await;
434            }
435            return;
436        }
437    };
438    match message {
439        Message::Request { id, method, params } => {
440            let Some(handler) = router.requests.get(&method) else {
441                let error = RpcError::new(
442                    ErrorCode::METHOD_NOT_FOUND,
443                    format!("no handler for `{method}`"),
444                );
445                let _ = peer.send(message::encode_error(id, &error)).await;
446                return;
447            };
448            let fut = handler(params, peer.clone());
449            let responder = peer.clone();
450            let limit = limit.clone();
451            let handle = running.tasks.spawn(async move {
452                // The semaphore is never closed; if it were, the limit
453                // would just stop applying.
454                let _permit = match limit {
455                    Some(limit) => limit.acquire_owned().await.ok(),
456                    None => None,
457                };
458                let frame = match fut.await {
459                    Ok(result) => message::encode_response_raw(id, &result),
460                    Err(error) => message::encode_error(id, &error),
461                };
462                if let Err(Error::Codec(e)) = responder.send(frame).await {
463                    // The result was too large to send; say so instead.
464                    let error = RpcError::internal(e.to_string());
465                    let _ = responder.send(message::encode_error(id, &error)).await;
466                }
467            });
468            running.by_task.insert(handle.id(), id);
469            running.by_request.insert(id, handle);
470        }
471        Message::Notification { method, params } if method == Cancel::METHOD => {
472            let Ok(CancelParams { id }) = msgpack::decode(&params) else {
473                tracing::warn!("dropping `$/cancel` with invalid params");
474                return;
475            };
476            if let Some(handle) = running.by_request.remove(&id) {
477                handle.abort();
478                let error = RpcError::new(ErrorCode::REQUEST_CANCELLED, "request cancelled");
479                let _ = peer.send(message::encode_error(id, &error)).await;
480            }
481        }
482        Message::Notification { method, params } => match router.notifications.get(&method) {
483            Some(handler) => handler(params, peer),
484            None => tracing::debug!(%method, "ignoring notification with no handler"),
485        },
486        Message::Response { id, result } => {
487            let waiter = peer
488                .inner
489                .pending
490                .lock()
491                .unwrap_or_else(PoisonError::into_inner)
492                .remove(&id);
493            match waiter {
494                Some(waiter) => {
495                    let _ = waiter.send(result);
496                }
497                None => tracing::debug!(id, "ignoring response to unknown or abandoned request"),
498            }
499        }
500    }
501}
502
503/// Writes queued frames until the queue closes. If writing fails, the whole
504/// connection is closed so nothing waits on a response that cannot come.
505async fn write_loop(
506    mut sink: FramedWrite<BoxWriter, LengthDelimitedCodec>,
507    mut rx: mpsc::Receiver<Bytes>,
508    peer: Peer,
509) -> std::io::Result<()> {
510    let result = async {
511        while let Some(frame) = rx.recv().await {
512            crate::trace::frame("send", &frame);
513            sink.send(frame).await?;
514        }
515        SinkExt::<Bytes>::close(&mut sink).await
516    }
517    .await;
518    if result.is_err() {
519        peer.close();
520    }
521    result
522}