sync_ls/
req_queue.rs

1//! The request-response queue for the LSP server.
2//!
3//! This is stolen from the lsp-server crate for customization.
4
5use core::fmt;
6use std::collections::HashMap;
7
8use crate::msg::RequestId;
9
10#[cfg(feature = "lsp")]
11use crate::lsp::{Request, Response};
12#[cfg(feature = "lsp")]
13use crate::msg::{ErrorCode, ResponseError};
14#[cfg(feature = "lsp")]
15use serde::Serialize;
16
17/// Manages the set of pending requests, both incoming and outgoing.
18pub struct ReqQueue<I, O> {
19    /// The incoming requests.
20    pub incoming: Incoming<I>,
21    /// The outgoing requests.
22    pub outgoing: Outgoing<O>,
23}
24
25impl<I, O> Default for ReqQueue<I, O> {
26    fn default() -> ReqQueue<I, O> {
27        ReqQueue {
28            incoming: Incoming {
29                pending: HashMap::default(),
30            },
31            outgoing: Outgoing {
32                next_id: 0,
33                pending: HashMap::default(),
34            },
35        }
36    }
37}
38
39impl<I, O> fmt::Debug for ReqQueue<I, O> {
40    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41        f.debug_struct("ReqQueue").finish()
42    }
43}
44
45impl<I, O> ReqQueue<I, O> {
46    /// Prints states of the request queue and panics.
47    pub fn begin_panic(&self) {
48        let keys = self.incoming.pending.keys().cloned().collect::<Vec<_>>();
49        log::error!("incoming pending: {keys:?}");
50        let keys = self.outgoing.pending.keys().cloned().collect::<Vec<_>>();
51        log::error!("outgoing pending: {keys:?}");
52
53        panic!("req queue panicking");
54    }
55}
56
57/// The incoming request queue.
58#[derive(Debug)]
59pub struct Incoming<I> {
60    pending: HashMap<RequestId, I>,
61}
62
63impl<I> Incoming<I> {
64    /// Registers a request with the given ID and data.
65    pub fn register(&mut self, id: RequestId, data: I) {
66        self.pending.insert(id, data);
67    }
68
69    /// Checks if there are *any* pending requests.
70    ///
71    /// This is useful for testing language server.
72    pub fn has_pending(&self) -> bool {
73        !self.pending.is_empty()
74    }
75
76    /// Checks if a request with the given ID is completed.
77    pub fn is_completed(&self, id: &RequestId) -> bool {
78        !self.pending.contains_key(id)
79    }
80
81    /// Cancels a request with the given ID.
82    #[cfg(feature = "lsp")]
83    pub fn cancel(&mut self, id: RequestId) -> Option<Response> {
84        let _data = self.complete(&id)?;
85        let error = ResponseError {
86            code: ErrorCode::RequestCanceled as i32,
87            message: "canceled by client".to_string(),
88            data: None,
89        };
90        Some(Response {
91            id,
92            result: None,
93            error: Some(error),
94        })
95    }
96
97    /// Completes a request with the given ID.
98    pub fn complete(&mut self, id: &RequestId) -> Option<I> {
99        self.pending.remove(id)
100    }
101}
102
103/// The outgoing request queue.
104///
105/// It holds the next request ID and the pending requests.
106#[derive(Debug)]
107pub struct Outgoing<O> {
108    next_id: i32,
109    pending: HashMap<RequestId, O>,
110}
111
112impl<O> Outgoing<O> {
113    /// Allocates a request ID.
114    pub fn alloc_request_id(&mut self) -> i32 {
115        let id = self.next_id;
116        self.next_id += 1;
117        id
118    }
119
120    /// Registers a request with the given method, params, and data.
121    #[cfg(feature = "lsp")]
122    pub fn register<P: Serialize>(&mut self, method: String, params: P, data: O) -> Request {
123        let id = RequestId::from(self.alloc_request_id());
124        self.pending.insert(id.clone(), data);
125        Request::new(id, method, params)
126    }
127
128    /// Completes a request with the given ID.
129    pub fn complete(&mut self, id: RequestId) -> Option<O> {
130        self.pending.remove(&id)
131    }
132}