Skip to main content

lsp_service/
client.rs

1use crossbeam_channel::{SendError, Sender};
2use std::sync::{
3	Arc,
4	atomic::{AtomicI32, Ordering},
5};
6
7use crate::{Message, Notification, Request};
8
9/// A handle for sending server-to-client messages, such as `textDocument/publishDiagnostics`.
10///
11/// Cheap to clone; clones can be moved to other threads.
12#[derive(Debug, Clone)]
13pub struct Client {
14	sender: Sender<Message>,
15	next_id: Arc<AtomicI32>,
16}
17
18impl Client {
19	pub(crate) fn new(sender: Sender<Message>) -> Self {
20		Self { sender, next_id: Arc::default() }
21	}
22
23	/// Sends the notification `N` to the client. Fails only once the connection has closed.
24	pub fn notify<N>(&self, params: N::Params) -> Result<(), SendError<Message>>
25	where
26		N: lsp_types::notification::Notification,
27	{
28		self.sender.send(Message::Notification(Notification::new::<N>(params)))
29	}
30
31	/// Sends the request `R` to the client, such as `client/registerCapability`, without waiting for its reply. The
32	/// client's reply reaches the [`Handler`](crate::Handler), which ignores it. Fails only once the connection has
33	/// closed.
34	pub fn request<R>(&self, params: R::Params) -> Result<(), SendError<Message>>
35	where
36		R: lsp_types::request::Request,
37	{
38		let id = self.next_id.fetch_add(1, Ordering::Relaxed).into();
39		self.sender.send(Message::Request(Request::new::<R>(id, params)))
40	}
41}