| 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 |
// NOTE: We avoid using `?` here, since it would return early on error |
| 150 |
// and skip clearing `content`. By returning the result directly instead, |
| 151 |
// we ensure `content.clear()` is always called. |
| 152 |
let output = sonic_rs::from_slice(content).map_err(Into::into); |
| 153 |
|
| 154 |
content.clear(); |
| 155 |
|
| 156 |
output |
| 157 |
} |
| 158 |
|
| 159 |
async fn recv_server_error( |
| 160 |
err: &mut (impl AsyncBufRead + Unpin + Send), |
| 161 |
buffer: &mut String, |
| 162 |
language_server_name: &str, |
| 163 |
) -> Result<()> { |
| 164 |
buffer.truncate(0); |
| 165 |
if err.read_line(buffer).await? == 0 { |
| 166 |
return Err(Error::StreamClosed); |
| 167 |
}; |
| 168 |
error!("{language_server_name} err <- {buffer:?}"); |
| 169 |
|
| 170 |
Ok(()) |
| 171 |
} |
| 172 |
|
| 173 |
async fn send_payload_to_server( |
| 174 |
&self, |
| 175 |
server_stdin: &mut BufWriter<ChildStdin>, |
| 176 |
payload: Payload, |
| 177 |
) -> Result<()> { |
| 178 |
//TODO: reuse string |
| 179 |
let json = match payload { |
| 180 |
Payload::Request { chan, value } => { |
| 181 |
self.pending_requests |
| 182 |
.lock() |
| 183 |
.await |
| 184 |
.insert(value.id.clone(), chan); |
| 185 |
serde_json::to_string(&value)? |
| 186 |
} |
| 187 |
Payload::Notification(value) => serde_json::to_string(&value)?, |
| 188 |
Payload::Response(error) => serde_json::to_string(&error)?, |
| 189 |
}; |
| 190 |
self.send_string_to_server(server_stdin, json, &self.name) |
| 191 |
.await |
| 192 |
} |
| 193 |
|
| 194 |
async fn send_string_to_server( |
| 195 |
&self, |
| 196 |
server_stdin: &mut BufWriter<ChildStdin>, |
| 197 |
request: String, |
| 198 |
language_server_name: &str, |
| 199 |
) -> Result<()> { |
| 200 |
info!("{language_server_name} -> {request}"); |
| 201 |
|
| 202 |
// send the headers |
| 203 |
server_stdin |
| 204 |
.write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes()) |
| 205 |
.await?; |
| 206 |
|
| 207 |
// send the body |
| 208 |
server_stdin.write_all(request.as_bytes()).await?; |
| 209 |
|
| 210 |
server_stdin.flush().await?; |
| 211 |
|
| 212 |
Ok(()) |
| 213 |
} |
| 214 |
|
| 215 |
async fn process_server_message( |
| 216 |
&self, |
| 217 |
client_tx: &UnboundedSender<(LanguageServerId, jsonrpc::Call)>, |
| 218 |
msg: ServerMessage, |
| 219 |
language_server_name: &str, |
| 220 |
) -> Result<()> { |
| 221 |
match msg { |
| 222 |
ServerMessage::Output(output) => { |
| 223 |
self.process_request_response(output, language_server_name) |
| 224 |
.await? |
| 225 |
} |
| 226 |
ServerMessage::Call(jsonrpc::Call::MethodCall(ref method_call)) |
| 227 |
if self.shutdown_requested.load(Ordering::Acquire) => |
| 228 |
{ |
| 229 |
// After helix sends shutdown the application event loop is no longer |
| 230 |
// consuming server-to-client requests. Respond with null success so the |
| 231 |
// server is not left waiting for a reply before it sends the shutdown |
| 232 |
// response. Sending an error is intentionally avoided: servers based on |
| 233 |
// vscode-languageserver-node (including gopls) treat an error response to |
| 234 |
// client/registerCapability as fatal and abort rather than completing the |
| 235 |
// handshake. |
| 236 |
let _ = self |
| 237 |
.inject_tx |
| 238 |
.send(Payload::Response(jsonrpc::Output::Success( |
| 239 |
jsonrpc::Success { |
| 240 |
jsonrpc: Some(jsonrpc::Version::V2), |
| 241 |
id: method_call.id.clone(), |
| 242 |
result: serde_json::Value::Null, |
| 243 |
}, |
| 244 |
))); |
| 245 |
} |
| 246 |
ServerMessage::Call(call) => { |
| 247 |
client_tx |
| 248 |
.send((self.id, call)) |
| 249 |
.context("failed to send a message to server")?; |
| 250 |
} |
| 251 |
}; |
| 252 |
Ok(()) |
| 253 |
} |
| 254 |
|
| 255 |
async fn process_request_response( |
| 256 |
&self, |
| 257 |
output: jsonrpc::Output, |
| 258 |
language_server_name: &str, |
| 259 |
) -> Result<()> { |
| 260 |
let (id, result) = match output { |
| 261 |
jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => (id, Ok(result)), |
| 262 |
jsonrpc::Output::Failure(jsonrpc::Failure { id, error, .. }) => { |
| 263 |
error!("{language_server_name} <- {error}"); |
| 264 |
(id, Err(error.into())) |
| 265 |
} |
| 266 |
}; |
| 267 |
|
| 268 |
if let Some(tx) = self.pending_requests.lock().await.remove(&id) { |
| 269 |
match tx.send(result).await { |
| 270 |
Ok(_) => (), |
| 271 |
Err(_) => log::debug!( |
| 272 |
"Tried sending response into a closed channel (id={:?}), likely a fire-and-forget shutdown", |
| 273 |
id |
| 274 |
), |
| 275 |
}; |
| 276 |
} else { |
| 277 |
log::error!( |
| 278 |
"Discarding Language Server response without a request (id={:?}) {:?}", |
| 279 |
id, |
| 280 |
result |
| 281 |
); |
| 282 |
} |
| 283 |
|
| 284 |
Ok(()) |
| 285 |
} |
| 286 |
|
| 287 |
async fn recv( |
| 288 |
transport: Arc<Self>, |
| 289 |
mut server_stdout: BufReader<ChildStdout>, |
| 290 |
client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>, |
| 291 |
) { |
| 292 |
let mut recv_buffer = String::new(); |
| 293 |
let mut content_buffer = Vec::new(); |
| 294 |
loop { |
| 295 |
match Self::recv_server_message( |
| 296 |
&mut server_stdout, |
| 297 |
&mut recv_buffer, |
| 298 |
&mut content_buffer, |
| 299 |
&transport.name, |
| 300 |
) |
| 301 |
.await |
| 302 |
{ |
| 303 |
Ok(msg) => { |
| 304 |
match transport |
| 305 |
.process_server_message(&client_tx, msg, &transport.name) |
| 306 |
.await |
| 307 |
{ |
| 308 |
Ok(_) => {} |
| 309 |
Err(err) => { |
| 310 |
error!("{} err: <- {err:?}", transport.name); |
| 311 |
break; |
| 312 |
} |
| 313 |
}; |
| 314 |
} |
| 315 |
Err(err) => { |
| 316 |
if !matches!(err, Error::StreamClosed) { |
| 317 |
error!( |
| 318 |
"Exiting {} after unexpected error: {err:?}", |
| 319 |
&transport.name |
| 320 |
); |
| 321 |
} |
| 322 |
|
| 323 |
// Close any outstanding requests. |
| 324 |
for (id, tx) in transport.pending_requests.lock().await.drain() { |
| 325 |
match tx.send(Err(Error::StreamClosed)).await { |
| 326 |
Ok(_) => (), |
| 327 |
Err(_) => { |
| 328 |
error!("Could not close request on a closed channel (id={:?})", id) |
| 329 |
} |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
// Hack: inject a terminated notification so we trigger code that needs to happen after exit |
| 334 |
let notification = |
| 335 |
ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification { |
| 336 |
jsonrpc: None, |
| 337 |
method: lsp::notification::Exit::METHOD.to_string(), |
| 338 |
params: jsonrpc::Params::None, |
| 339 |
})); |
| 340 |
match transport |
| 341 |
.process_server_message(&client_tx, notification, &transport.name) |
| 342 |
.await |
| 343 |
{ |
| 344 |
Ok(_) => {} |
| 345 |
Err(err) => { |
| 346 |
error!("err: <- {:?}", err); |
| 347 |
} |
| 348 |
} |
| 349 |
break; |
| 350 |
} |
| 351 |
} |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
async fn err(transport: Arc<Self>, mut server_stderr: BufReader<ChildStderr>) { |
| 356 |
let mut recv_buffer = String::new(); |
| 357 |
loop { |
| 358 |
match Self::recv_server_error(&mut server_stderr, &mut recv_buffer, &transport.name) |
| 359 |
.await |
| 360 |
{ |
| 361 |
Ok(_) => {} |
| 362 |
Err(err) => { |
| 363 |
error!("{} err: <- {err:?}", transport.name); |
| 364 |
break; |
| 365 |
} |
| 366 |
} |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
async fn send( |
| 371 |
transport: Arc<Self>, |
| 372 |
mut server_stdin: BufWriter<ChildStdin>, |
| 373 |
client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>, |
| 374 |
mut client_rx: UnboundedReceiver<Payload>, |
| 375 |
mut inject_rx: UnboundedReceiver<Payload>, |
| 376 |
initialize_notify: Arc<Notify>, |
| 377 |
) { |
| 378 |
let mut pending_messages: Vec<Payload> = Vec::new(); |
| 379 |
let mut is_pending = true; |
| 380 |
|
| 381 |
// Pin outside the loop to avoid cancellation-safety issue: |
| 382 |
// recreating `notified()` inside `select!` can lose the permit. |
| 383 |
let notified = initialize_notify.notified(); |
| 384 |
tokio::pin!(notified); |
| 385 |
|
| 386 |
// Determine if a message is allowed to be sent early |
| 387 |
fn is_initialize(payload: &Payload) -> bool { |
| 388 |
use lsp::{ |
| 389 |
notification::Initialized, |
| 390 |
request::{Initialize, Request}, |
| 391 |
}; |
| 392 |
match payload { |
| 393 |
Payload::Request { |
| 394 |
value: jsonrpc::MethodCall { method, .. }, |
| 395 |
.. |
| 396 |
} if method == Initialize::METHOD => true, |
| 397 |
Payload::Notification(jsonrpc::Notification { method, .. }) |
| 398 |
if method == Initialized::METHOD => |
| 399 |
{ |
| 400 |
true |
| 401 |
} |
| 402 |
_ => false, |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
fn is_shutdown(payload: &Payload) -> bool { |
| 407 |
use lsp::request::{Request, Shutdown}; |
| 408 |
matches!(payload, Payload::Request { value: jsonrpc::MethodCall { method, .. }, .. } if method == Shutdown::METHOD) |
| 409 |
} |
| 410 |
|
| 411 |
fn is_exit(payload: &Payload) -> bool { |
| 412 |
use lsp::notification::{Exit, Notification}; |
| 413 |
matches!(payload, Payload::Notification(jsonrpc::Notification { method, .. }) if method == Exit::METHOD) |
| 414 |
} |
| 415 |
|
| 416 |
// TODO: events that use capabilities need to do the right thing |
| 417 |
|
| 418 |
loop { |
| 419 |
tokio::select! { |
| 420 |
biased; |
| 421 |
_ = &mut notified, if is_pending => { |
| 422 |
// server successfully initialized |
| 423 |
is_pending = false; |
| 424 |
|
| 425 |
// Hack: inject an initialized notification so we trigger code that needs to happen after init |
| 426 |
let notification = ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification { |
| 427 |
jsonrpc: None, |
| 428 |
|
| 429 |
method: lsp::notification::Initialized::METHOD.to_string(), |
| 430 |
params: jsonrpc::Params::None, |
| 431 |
})); |
| 432 |
let language_server_name = &transport.name; |
| 433 |
match transport.process_server_message(&client_tx, notification, language_server_name).await { |
| 434 |
Ok(_) => {} |
| 435 |
Err(err) => { |
| 436 |
error!("{language_server_name} err: <- {err:?}"); |
| 437 |
} |
| 438 |
} |
| 439 |
|
| 440 |
// drain the pending queue and send payloads to server |
| 441 |
for msg in pending_messages.drain(..) { |
| 442 |
log::info!("Draining pending message {:?}", msg); |
| 443 |
match transport.send_payload_to_server(&mut server_stdin, msg).await { |
| 444 |
Ok(_) => {} |
| 445 |
Err(err) => { |
| 446 |
error!("{language_server_name} err: <- {err:?}"); |
| 447 |
} |
| 448 |
} |
| 449 |
} |
| 450 |
} |
| 451 |
msg = client_rx.recv() => { |
| 452 |
if let Some(msg) = msg { |
| 453 |
if is_pending && is_shutdown(&msg) { |
| 454 |
log::info!("Language server not initialized, shutting down"); |
| 455 |
break; |
| 456 |
} else if is_pending && !is_initialize(&msg) { |
| 457 |
// ignore notifications |
| 458 |
if let Payload::Notification(_) = msg { |
| 459 |
continue; |
| 460 |
} |
| 461 |
|
| 462 |
log::info!("Language server not initialized, delaying request"); |
| 463 |
pending_messages.push(msg); |
| 464 |
} else { |
| 465 |
let is_shutdown_msg = is_shutdown(&msg); |
| 466 |
let is_exit_msg = is_exit(&msg); |
| 467 |
// Set the flag *before* flushing to stdin so that the recv task |
| 468 |
// cannot observe an unanswered server request in the window between |
| 469 |
// the kernel delivering the bytes to the server and this store. |
| 470 |
if is_shutdown_msg { |
| 471 |
transport |
| 472 |
.shutdown_requested |
| 473 |
.store(true, Ordering::Release); |
| 474 |
} |
| 475 |
match transport.send_payload_to_server(&mut server_stdin, msg).await { |
| 476 |
Ok(_) => { |
| 477 |
// `exit` is the last thing a shutting-down client sends; |
| 478 |
// signal that it has reached the server's stdin. |
| 479 |
if is_exit_msg { |
| 480 |
transport.shutdown_flushed.notify_one(); |
| 481 |
} |
| 482 |
} |
| 483 |
Err(err) => { |
| 484 |
error!("{} err: <- {err:?}", transport.name); |
| 485 |
} |
| 486 |
} |
| 487 |
} |
| 488 |
} else { |
| 489 |
// channel closed |
| 490 |
break; |
| 491 |
} |
| 492 |
} |
| 493 |
msg = inject_rx.recv() => { |
| 494 |
if let Some(msg) = msg { |
| 495 |
match transport.send_payload_to_server(&mut server_stdin, msg).await { |
| 496 |
Ok(_) => {} |
| 497 |
Err(err) => { |
| 498 |
error!("{} inject err: <- {err:?}", transport.name); |
| 499 |
} |
| 500 |
} |
| 501 |
} |
| 502 |
} |
| 503 |
} |
| 504 |
} |
| 505 |
} |
| 506 |
} |