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.
58pub struct Incoming<I> {
59    pending: HashMap<RequestId, I>,
60}
61
62impl<I> fmt::Debug for Incoming<I> {
63    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64        f.write_str("Incoming")?;
65        f.debug_list().entries(self.pending.keys()).finish()
66    }
67}
68
69impl<I> Incoming<I> {
70    /// Registers a request with the given ID and data.
71    pub fn register(&mut self, id: RequestId, data: I) {
72        self.pending.insert(id, data);
73    }
74
75    /// Returns an iterator over the pending requests.
76    pub fn pending(&self) -> impl Iterator<Item = (&RequestId, &I)> {
77        self.pending.iter()
78    }
79
80    /// Checks if there are *any* pending requests.
81    ///
82    /// This is useful for testing language server.
83    pub fn has_pending(&self) -> bool {
84        !self.pending.is_empty()
85    }
86
87    /// Checks if a request with the given ID is completed.
88    pub fn is_completed(&self, id: &RequestId) -> bool {
89        !self.pending.contains_key(id)
90    }
91
92    /// Cancels a request with the given ID.
93    #[cfg(feature = "lsp")]
94    pub fn cancel(&mut self, id: RequestId) -> Option<Response> {
95        let _data = self.complete(&id)?;
96        let error = ResponseError {
97            code: ErrorCode::RequestCanceled as i32,
98            message: "canceled by client".to_string(),
99            data: None,
100        };
101        Some(Response {
102            id,
103            result: None,
104            error: Some(error),
105        })
106    }
107
108    /// Completes a request with the given ID.
109    pub fn complete(&mut self, id: &RequestId) -> Option<I> {
110        self.pending.remove(id)
111    }
112}
113
114/// The outgoing request queue.
115///
116/// It holds the next request ID and the pending requests.
117pub struct Outgoing<O> {
118    next_id: i32,
119    pending: HashMap<RequestId, O>,
120}
121
122impl<I> fmt::Debug for Outgoing<I> {
123    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
124        f.write_str("Outgoing")?;
125        f.debug_list().entries(self.pending.keys()).finish()
126    }
127}
128
129impl<O> Outgoing<O> {
130    /// Allocates a request ID.
131    pub fn alloc_request_id(&mut self) -> i32 {
132        let id = self.next_id;
133        self.next_id += 1;
134        id
135    }
136
137    /// Registers a request with the given method, params, and data.
138    #[cfg(feature = "lsp")]
139    pub fn register<P: Serialize>(&mut self, method: String, params: P, data: O) -> Request {
140        let id = RequestId::from(self.alloc_request_id());
141        self.pending.insert(id.clone(), data);
142        Request::new(id, method, params)
143    }
144
145    /// Completes a request with the given ID.
146    pub fn complete(&mut self, id: RequestId) -> Option<O> {
147        self.pending.remove(&id)
148    }
149}