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
63/// The outgoing request queue.
64///
65/// It holds the next request ID and the pending requests.
66#[derive(Debug)]
67pub struct Outgoing<O> {
68    next_id: i32,
69    pending: HashMap<RequestId, O>,
70}
71
72impl<I> Incoming<I> {
73    /// Registers a request with the given ID and data.
74    pub fn register(&mut self, id: RequestId, data: I) {
75        self.pending.insert(id, data);
76    }
77
78    /// Checks if there are *any* pending requests.
79    ///
80    /// This is useful for testing language server.
81    pub fn has_pending(&self) -> bool {
82        !self.pending.is_empty()
83    }
84
85    /// Checks if a request with the given ID is completed.
86    pub fn is_completed(&self, id: &RequestId) -> bool {
87        !self.pending.contains_key(id)
88    }
89
90    /// Cancels a request with the given ID.
91    #[cfg(feature = "lsp")]
92    pub fn cancel(&mut self, id: RequestId) -> Option<Response> {
93        let _data = self.complete(&id)?;
94        let error = ResponseError {
95            code: ErrorCode::RequestCanceled as i32,
96            message: "canceled by client".to_string(),
97            data: None,
98        };
99        Some(Response {
100            id,
101            result: None,
102            error: Some(error),
103        })
104    }
105
106    /// Completes a request with the given ID.
107    pub fn complete(&mut self, id: &RequestId) -> Option<I> {
108        self.pending.remove(id)
109    }
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}