Skip to main content

lsp_server/
req_queue.rs

1use std::collections::HashMap;
2
3use crate::{ErrorCode, Request, RequestId, Response, ResponseError};
4
5/// Manages the set of pending requests, both incoming and outgoing.
6#[derive(Debug)]
7pub struct ReqQueue<I, O> {
8    pub incoming: Incoming<I>,
9    pub outgoing: Outgoing<O>,
10}
11
12impl<I, O> Default for ReqQueue<I, O> {
13    fn default() -> ReqQueue<I, O> {
14        ReqQueue {
15            incoming: Incoming { pending: HashMap::default() },
16            outgoing: Outgoing { next_id: 0, pending: HashMap::default() },
17        }
18    }
19}
20
21impl<I, O> ReqQueue<I, O> {
22    pub fn has_pending(&self) -> bool {
23        self.incoming.has_pending() || self.outgoing.has_pending()
24    }
25}
26
27#[derive(Debug)]
28pub struct Incoming<I> {
29    pending: HashMap<RequestId, I>,
30}
31
32#[derive(Debug)]
33pub struct Outgoing<O> {
34    next_id: i32,
35    pending: HashMap<RequestId, O>,
36}
37
38impl<I> Incoming<I> {
39    pub fn register(&mut self, id: RequestId, data: I) {
40        self.pending.insert(id, data);
41    }
42
43    pub fn cancel(&mut self, id: RequestId) -> Option<Response> {
44        let _data = self.complete(&id)?;
45        let error = ResponseError {
46            code: ErrorCode::RequestCanceled as i32,
47            message: "canceled by client".to_owned(),
48            data: None,
49        };
50        Some(Response { id, result: None, error: Some(error) })
51    }
52
53    pub fn complete(&mut self, id: &RequestId) -> Option<I> {
54        self.pending.remove(id)
55    }
56
57    pub fn is_completed(&self, id: &RequestId) -> bool {
58        !self.pending.contains_key(id)
59    }
60
61    pub fn has_pending(&self) -> bool {
62        !self.pending.is_empty()
63    }
64}
65
66impl<O> Outgoing<O> {
67    pub fn register<P: serde::Serialize>(&mut self, method: String, params: P, data: O) -> Request {
68        let id = RequestId::from(self.next_id);
69        self.pending.insert(id.clone(), data);
70        self.next_id += 1;
71        Request::new(id, method, params)
72    }
73
74    pub fn complete(&mut self, id: RequestId) -> Option<O> {
75        self.pending.remove(&id)
76    }
77
78    pub fn has_pending(&self) -> bool {
79        !self.pending.is_empty()
80    }
81}