Debian Codegraph @

helix-lsp/src/transport.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use crate::{
2 jsonrpc,
3 lsp::{self, notification::Notification as _},
4 Error, LanguageServerId, Result,
5 };
6 use anyhow::Context;
7 use log::{error, info};
8 use serde::{Deserialize, Serialize};
9 use serde_json::Value;
10 use std::collections::HashMap;
11 use std::sync::atomic::{AtomicBool, Ordering};
12 use std::sync::Arc;
13 use tokio::{
14 io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter},
15 process::{ChildStderr, ChildStdin, ChildStdout},
16 sync::{
17 mpsc::{unbounded_channel, Sender, UnboundedReceiver, UnboundedSender},
18 Mutex, Notify,
19 },
20 };
21
22 #[derive(Debug)]
23 pub enum Payload {
24 Request {
25 chan: Sender<Result<Value>>,
26 value: jsonrpc::MethodCall,
27 },
28 Notification(jsonrpc::Notification),
29 Response(jsonrpc::Output),
30 }
31
32 /// A type representing all possible values sent from the server to the client.
33 #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
34 #[serde(deny_unknown_fields)]
35 #[serde(untagged)]
36 enum ServerMessage {
37 /// A regular JSON-RPC request output (single response).
38 Output(jsonrpc::Output),
39 /// A JSON-RPC request or notification.
40 Call(jsonrpc::Call),
41 }
42
43 #[derive(Debug)]
44 pub struct Transport {
45 id: LanguageServerId,
46 name: String,
47 pending_requests: Mutex<HashMap<jsonrpc::Id, Sender<Result<Value>>>>,
48 shutdown_requested: AtomicBool,
49 inject_tx: UnboundedSender<Payload>,
50 /// Notified once the `exit` notification has been flushed to the server's stdin
51 shutdown_flushed: Arc<Notify>,
52 }
53
54 impl Transport {
55 #[allow(clippy::type_complexity)]
56 pub fn start(
57 server_stdout: BufReader<ChildStdout>,
58 server_stdin: BufWriter<ChildStdin>,
59 server_stderr: BufReader<ChildStderr>,
60 id: LanguageServerId,
61 name: String,
62 ) -> (
63 UnboundedReceiver<(LanguageServerId, jsonrpc::Call)>,
64 UnboundedSender<Payload>,
65 Arc<Notify>,
66 Arc<Notify>,
67 ) {
68 let (client_tx, rx) = unbounded_channel();
69 let (tx, client_rx) = unbounded_channel();
70 let (inject_tx, inject_rx) = unbounded_channel();
71 let notify = Arc::new(Notify::new());
72 let shutdown_flushed = Arc::new(Notify::new());
73
74 let transport = Self {
75 id,
76 name,
77 pending_requests: Mutex::new(HashMap::default()),
78 shutdown_requested: AtomicBool::new(false),
79 inject_tx,
80 shutdown_flushed: shutdown_flushed.clone(),
81 };
82
83 let transport = Arc::new(transport);
84
85 tokio::spawn(Self::recv(
86 transport.clone(),
87 server_stdout,
88 client_tx.clone(),
89 ));
90 tokio::spawn(Self::err(transport.clone(), server_stderr));
91 tokio::spawn(Self::send(
92 transport,
93 server_stdin,
94 client_tx,
95 client_rx,
96 inject_rx,
97 notify.clone(),
98 ));
99
100 (rx, tx, notify, shutdown_flushed)
101 }
102
103 async fn recv_server_message(
104 reader: &mut (impl AsyncBufRead + Unpin + Send),
105 buffer: &mut String,
106 content: &mut Vec<u8>,
107 language_server_name: &str,
108 ) -> Result<ServerMessage> {
109 let mut content_length = None;
110 loop {
111 buffer.clear();
112 if reader.read_line(buffer).await? == 0 {
113 return Err(Error::StreamClosed);
•114 };
115
116 // debug!("<- header {:?}", buffer);
117
118 if buffer == "\r\n" {
119 // look for an empty CRLF line
120 break;
121 }
122
123 let header = buffer.trim();
124
125 let parts = header.split_once(": ");
126
127 match parts {
128 Some(("Content-Length", value)) => {
129 content_length = Some(value.parse().context("invalid content length")?);
130 }
131 Some((_, _)) => {}
132 None => {
133 // Workaround: Some non-conformant language servers will output logging and other garbage
134 // into the same stream as JSON-RPC messages. This can also happen from shell scripts that spawn
135 // the server. Skip such lines and log a warning.
136
137 // warn!("Failed to parse header: {:?}", header);
138 }
139 }
140 }
141
142 let content_length = content_length.context("missing content length")?;
143 content.resize(content_length, 0);
144 reader.read_exact(content).await?;
145 let msg = std::str::from_utf8(content).context("invalid utf8 from server")?;
146
147 info!("{language_server_name} <- {msg}");
148
•149 // try parsing as output (server response) or call (server request)
150 let output: serde_json::Result<ServerMessage> = serde_json::from_str(msg);
151
152 content.clear();
153
•154 Ok(output?)
155 }
156
157 async fn recv_server_error(
158 err: &mut (impl AsyncBufRead + Unpin + Send),
159 buffer: &mut String,
160 language_server_name: &str,
161 ) -> Result<()> {
162 buffer.truncate(0);
163 if err.read_line(buffer).await? == 0 {
164 return Err(Error::StreamClosed);
165 };
166 error!("{language_server_name} err <- {buffer:?}");
167
168 Ok(())
169 }
170
171 async fn send_payload_to_server(
172 &self,
173 server_stdin: &mut BufWriter<ChildStdin>,
174 payload: Payload,
175 ) -> Result<()> {
176 //TODO: reuse string
177 let json = match payload {
178 Payload::Request { chan, value } => {
179 self.pending_requests
180 .lock()
181 .await
182 .insert(value.id.clone(), chan);
183 serde_json::to_string(&value)?
184 }
185 Payload::Notification(value) => serde_json::to_string(&value)?,
186 Payload::Response(error) => serde_json::to_string(&error)?,
187 };
188 self.send_string_to_server(server_stdin, json, &self.name)
189 .await
190 }
191
192 async fn send_string_to_server(
193 &self,
194 server_stdin: &mut BufWriter<ChildStdin>,
195 request: String,
196 language_server_name: &str,
197 ) -> Result<()> {
198 info!("{language_server_name} -> {request}");
199
200 // send the headers
201 server_stdin
202 .write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
203 .await?;
204
205 // send the body
206 server_stdin.write_all(request.as_bytes()).await?;
207
208 server_stdin.flush().await?;
209
210 Ok(())
211 }
212
213 async fn process_server_message(
214 &self,
215 client_tx: &UnboundedSender<(LanguageServerId, jsonrpc::Call)>,
216 msg: ServerMessage,
217 language_server_name: &str,
218 ) -> Result<()> {
219 match msg {
220 ServerMessage::Output(output) => {
221 self.process_request_response(output, language_server_name)
222 .await?
223 }
224 ServerMessage::Call(jsonrpc::Call::MethodCall(ref method_call))
225 if self.shutdown_requested.load(Ordering::Acquire) =>
226 {
227 // After helix sends shutdown the application event loop is no longer
228 // consuming server-to-client requests. Respond with null success so the
229 // server is not left waiting for a reply before it sends the shutdown
230 // response. Sending an error is intentionally avoided: servers based on
231 // vscode-languageserver-node (including gopls) treat an error response to
232 // client/registerCapability as fatal and abort rather than completing the
233 // handshake.
234 let _ = self
235 .inject_tx
236 .send(Payload::Response(jsonrpc::Output::Success(
237 jsonrpc::Success {
238 jsonrpc: Some(jsonrpc::Version::V2),
239 id: method_call.id.clone(),
240 result: serde_json::Value::Null,
241 },
242 )));
243 }
244 ServerMessage::Call(call) => {
245 client_tx
246 .send((self.id, call))
247 .context("failed to send a message to server")?;
248 }
249 };
250 Ok(())
251 }
252
253 async fn process_request_response(
254 &self,
255 output: jsonrpc::Output,
256 language_server_name: &str,
257 ) -> Result<()> {
258 let (id, result) = match output {
259 jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => (id, Ok(result)),
260 jsonrpc::Output::Failure(jsonrpc::Failure { id, error, .. }) => {
261 error!("{language_server_name} <- {error}");
262 (id, Err(error.into()))
263 }
264 };
265
266 if let Some(tx) = self.pending_requests.lock().await.remove(&id) {
267 match tx.send(result).await {
268 Ok(_) => (),
269 Err(_) => log::debug!(
270 "Tried sending response into a closed channel (id={:?}), likely a fire-and-forget shutdown",
271 id
272 ),
273 };
274 } else {
275 log::error!(
276 "Discarding Language Server response without a request (id={:?}) {:?}",
277 id,
278 result
279 );
280 }
281
282 Ok(())
283 }
284
285 async fn recv(
286 transport: Arc<Self>,
287 mut server_stdout: BufReader<ChildStdout>,
288 client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>,
289 ) {
290 let mut recv_buffer = String::new();
291 let mut content_buffer = Vec::new();
292 loop {
293 match Self::recv_server_message(
294 &mut server_stdout,
295 &mut recv_buffer,
296 &mut content_buffer,
297 &transport.name,
298 )
299 .await
300 {
301 Ok(msg) => {
302 match transport
303 .process_server_message(&client_tx, msg, &transport.name)
304 .await
305 {
306 Ok(_) => {}
307 Err(err) => {
308 error!("{} err: <- {err:?}", transport.name);
309 break;
310 }
311 };
312 }
313 Err(err) => {
314 if !matches!(err, Error::StreamClosed) {
315 error!(
316 "Exiting {} after unexpected error: {err:?}",
317 &transport.name
318 );
319 }
320
321 // Close any outstanding requests.
322 for (id, tx) in transport.pending_requests.lock().await.drain() {
323 match tx.send(Err(Error::StreamClosed)).await {
324 Ok(_) => (),
325 Err(_) => {
326 error!("Could not close request on a closed channel (id={:?})", id)
327 }
328 }
329 }
330
331 // Hack: inject a terminated notification so we trigger code that needs to happen after exit
332 let notification =
333 ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification {
334 jsonrpc: None,
335 method: lsp::notification::Exit::METHOD.to_string(),
336 params: jsonrpc::Params::None,
337 }));
338 match transport
339 .process_server_message(&client_tx, notification, &transport.name)
340 .await
341 {
342 Ok(_) => {}
343 Err(err) => {
344 error!("err: <- {:?}", err);
345 }
346 }
347 break;
348 }
349 }
350 }
351 }
352
353 async fn err(transport: Arc<Self>, mut server_stderr: BufReader<ChildStderr>) {
354 let mut recv_buffer = String::new();
355 loop {
356 match Self::recv_server_error(&mut server_stderr, &mut recv_buffer, &transport.name)
357 .await
358 {
359 Ok(_) => {}
360 Err(err) => {
361 error!("{} err: <- {err:?}", transport.name);
362 break;
363 }
364 }
365 }
366 }
367
368 async fn send(
369 transport: Arc<Self>,
370 mut server_stdin: BufWriter<ChildStdin>,
371 client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>,
372 mut client_rx: UnboundedReceiver<Payload>,
373 mut inject_rx: UnboundedReceiver<Payload>,
374 initialize_notify: Arc<Notify>,
375 ) {
376 let mut pending_messages: Vec<Payload> = Vec::new();
377 let mut is_pending = true;
378
379 // Pin outside the loop to avoid cancellation-safety issue:
380 // recreating `notified()` inside `select!` can lose the permit.
381 let notified = initialize_notify.notified();
382 tokio::pin!(notified);
383
384 // Determine if a message is allowed to be sent early
385 fn is_initialize(payload: &Payload) -> bool {
386 use lsp::{
387 notification::Initialized,
388 request::{Initialize, Request},
389 };
390 match payload {
391 Payload::Request {
392 value: jsonrpc::MethodCall { method, .. },
393 ..
394 } if method == Initialize::METHOD => true,
395 Payload::Notification(jsonrpc::Notification { method, .. })
396 if method == Initialized::METHOD =>
397 {
398 true
399 }
400 _ => false,
401 }
402 }
403
404 fn is_shutdown(payload: &Payload) -> bool {
405 use lsp::request::{Request, Shutdown};
406 matches!(payload, Payload::Request { value: jsonrpc::MethodCall { method, .. }, .. } if method == Shutdown::METHOD)
407 }
408
409 fn is_exit(payload: &Payload) -> bool {
410 use lsp::notification::{Exit, Notification};
411 matches!(payload, Payload::Notification(jsonrpc::Notification { method, .. }) if method == Exit::METHOD)
412 }
413
414 // TODO: events that use capabilities need to do the right thing
415
416 loop {
417 tokio::select! {
418 biased;
419 _ = &mut notified, if is_pending => {
420 // server successfully initialized
421 is_pending = false;
422
423 // Hack: inject an initialized notification so we trigger code that needs to happen after init
424 let notification = ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification {
425 jsonrpc: None,
426
427 method: lsp::notification::Initialized::METHOD.to_string(),
428 params: jsonrpc::Params::None,
429 }));
430 let language_server_name = &transport.name;
431 match transport.process_server_message(&client_tx, notification, language_server_name).await {
432 Ok(_) => {}
433 Err(err) => {
434 error!("{language_server_name} err: <- {err:?}");
435 }
436 }
437
438 // drain the pending queue and send payloads to server
439 for msg in pending_messages.drain(..) {
440 log::info!("Draining pending message {:?}", msg);
441 match transport.send_payload_to_server(&mut server_stdin, msg).await {
442 Ok(_) => {}
443 Err(err) => {
444 error!("{language_server_name} err: <- {err:?}");
445 }
446 }
447 }
448 }
449 msg = client_rx.recv() => {
450 if let Some(msg) = msg {
451 if is_pending && is_shutdown(&msg) {
452 log::info!("Language server not initialized, shutting down");
453 break;
454 } else if is_pending && !is_initialize(&msg) {
455 // ignore notifications
456 if let Payload::Notification(_) = msg {
457 continue;
458 }
459
460 log::info!("Language server not initialized, delaying request");
461 pending_messages.push(msg);
462 } else {
463 let is_shutdown_msg = is_shutdown(&msg);
464 let is_exit_msg = is_exit(&msg);
465 // Set the flag *before* flushing to stdin so that the recv task
466 // cannot observe an unanswered server request in the window between
467 // the kernel delivering the bytes to the server and this store.
468 if is_shutdown_msg {
469 transport
470 .shutdown_requested
471 .store(true, Ordering::Release);
472 }
473 match transport.send_payload_to_server(&mut server_stdin, msg).await {
474 Ok(_) => {
475 // `exit` is the last thing a shutting-down client sends;
476 // signal that it has reached the server's stdin.
477 if is_exit_msg {
478 transport.shutdown_flushed.notify_one();
479 }
480 }
481 Err(err) => {
482 error!("{} err: <- {err:?}", transport.name);
483 }
484 }
485 }
486 } else {
487 // channel closed
488 break;
489 }
490 }
491 msg = inject_rx.recv() => {
492 if let Some(msg) = msg {
493 match transport.send_payload_to_server(&mut server_stdin, msg).await {
494 Ok(_) => {}
495 Err(err) => {
496 error!("{} inject err: <- {err:?}", transport.name);
497 }
498 }
499 }
500 }
501 }
502 }
503 }
504 }