| 1 | //! Thin JSON-RPC over stdio client for LSP servers. |
| 2 | //! |
| 3 | //! We deliberately do **not** depend on `tower-lsp` — it is a server-side |
| 4 | //! framework and dragging it in here would add hundreds of unnecessary |
| 5 | //! transitive dependencies and slow down `cargo build` for every contributor. |
| 6 | //! The LSP wire protocol is small enough that handling it ourselves is a |
| 7 | //! self-contained ~400 LOC and lets us keep total control of the spawn |
| 8 | //! lifecycle, timeouts, and the async surface. |
| 9 | //! |
| 10 | //! Architecture: |
| 11 | //! |
| 12 | //! - [`LspTransport`] is the trait the [`super::LspManager`] talks to. The |
| 13 | //! real implementation is [`StdioLspTransport`] (forks an LSP server with |
| 14 | //! `tokio::process::Command`); tests use `FakeTransport`. |
| 15 | //! - [`StdioLspTransport`] runs three tokio tasks: a reader, a writer, and |
| 16 | //! the public API. Communication uses tokio mpsc channels. |
| 17 | //! - We parse `Content-Length`-framed JSON-RPC and route inbound messages |
| 18 | //! either to a per-request response slot (for replies) or to the |
| 19 | //! diagnostics queue (for `textDocument/publishDiagnostics` notifications). |
| 20 | //! |
| 21 | //! The transport is one-shot per file in MVP form: the manager spawns a |
| 22 | //! transport on demand for a language and reuses it. We do not implement |
| 23 | //! workspace sync beyond didOpen/didChange because the goal is "post-edit |
| 24 | //! diagnostics," not full IDE smartness. |
| 25 | |
| 26 | use std::collections::HashMap; |
| 27 | use std::path::{Path, PathBuf}; |
| 28 | use std::process::Stdio; |
| 29 | use std::sync::Arc; |
| 30 | use std::time::Duration; |
| 31 | |
| 32 | use anyhow::{Context, Result, anyhow}; |
| 33 | use async_trait::async_trait; |
| 34 | use serde_json::{Value, json}; |
| 35 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; |
| 36 | use tokio::process::{Child, Command}; |
| 37 | use tokio::sync::Mutex as AsyncMutex; |
| 38 | use tokio::sync::{mpsc, oneshot}; |
| 39 | use tokio::time::timeout; |
| 40 | |
| 41 | use super::diagnostics::{Diagnostic, Severity}; |
| 42 | use codewhale_runtime::process_tree::{ProcessTree, spawn_contained_tokio}; |
| 43 | use codewhale_util::utils::spawn_supervised; |
| 44 | |
| 45 | const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(5); |
| 46 | const MAX_LSP_HEADER_BYTES: usize = 8 * 1024; |
| 47 | const MAX_LSP_FRAME_BYTES: usize = 16 * 1024 * 1024; |
| 48 | |
| 49 | /// A publication retains the server's document version instead of pretending |
| 50 | /// that a matching URI alone proves which text was checked. |
| 51 | #[derive(Debug)] |
| 52 | pub struct DiagnosticPublication { |
| 53 | pub items: Vec<Diagnostic>, |
| 54 | pub document_version: Option<i64>, |
| 55 | pub diagnostic_version: Option<i64>, |
| 56 | } |
| 57 | |
| 58 | impl DiagnosticPublication { |
| 59 | #[must_use] |
| 60 | pub fn freshness(&self) -> &'static str { |
| 61 | if self.document_version.is_some() && self.document_version == self.diagnostic_version { |
| 62 | "verified" |
| 63 | } else { |
| 64 | "unverified" |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // Diagnostic-only transports have no document-version proof. Existing callers |
| 70 | // may still use their results, but must not claim freshness from an empty list. |
| 71 | impl From<Vec<Diagnostic>> for DiagnosticPublication { |
| 72 | fn from(items: Vec<Diagnostic>) -> Self { |
| 73 | Self { |
| 74 | items, |
| 75 | document_version: None, |
| 76 | diagnostic_version: None, |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Source synchronization proof for a semantic reply. Legacy transports keep |
| 82 | /// the raw result but cannot assert which document version served it. |
| 83 | #[derive(Debug)] |
| 84 | pub struct SemanticReply { |
| 85 | pub result: Value, |
| 86 | pub document_version: Option<i64>, |
| 87 | } |
| 88 | |
| 89 | /// Trait the LSP manager talks to. A real LSP server speaks this via stdio; |
| 90 | /// tests use an in-process fake. |
| 91 | #[async_trait] |
| 92 | pub trait LspTransport: Send + Sync { |
| 93 | /// Notify the server that a file was opened or its contents updated, then |
| 94 | /// wait up to `wait` for a `publishDiagnostics` notification for that |
| 95 | /// file. Returns the diagnostics list (possibly empty). Implementations |
| 96 | /// must NOT block past `wait`. |
| 97 | async fn diagnostics_for( |
| 98 | &self, |
| 99 | path: &Path, |
| 100 | text: &str, |
| 101 | wait: Duration, |
| 102 | ) -> Result<DiagnosticPublication>; |
| 103 | |
| 104 | /// Send a JSON-RPC request and wait up to `wait` for the reply. |
| 105 | /// |
| 106 | /// Default returns "unsupported" so diagnostic-only fakes keep working. |
| 107 | /// Real transports implement this for go-to-definition, symbols, and |
| 108 | /// references without spawning a second server lifecycle. |
| 109 | async fn request(&self, _method: &str, _params: Value, _wait: Duration) -> Result<Value> { |
| 110 | Err(anyhow!("LSP request not supported by this transport")) |
| 111 | } |
| 112 | |
| 113 | /// Synchronize and query one document atomically when the transport can |
| 114 | /// prove that ordering. Diagnostic-only/legacy transports stay unverified. |
| 115 | async fn request_for_document( |
| 116 | &self, |
| 117 | path: &Path, |
| 118 | text: &str, |
| 119 | method: &str, |
| 120 | params: Value, |
| 121 | wait: Duration, |
| 122 | ) -> Result<SemanticReply> { |
| 123 | timeout(wait, async { |
| 124 | self.ensure_open(path, text).await?; |
| 125 | Ok(SemanticReply { |
| 126 | result: self.request(method, params, wait).await?, |
| 127 | document_version: None, |
| 128 | }) |
| 129 | }) |
| 130 | .await |
| 131 | .map_err(|_| anyhow!("LSP semantic request timed out"))? |
| 132 | } |
| 133 | |
| 134 | /// Ensure `path` is open with `text` (didOpen/didChange) so position-based |
| 135 | /// requests can target it. Default is a no-op; real transports track opens. |
| 136 | async fn ensure_open(&self, _path: &Path, _text: &str) -> Result<()> { |
| 137 | Ok(()) |
| 138 | } |
| 139 | |
| 140 | /// A closed transport is never valid cache evidence. Diagnostic-only |
| 141 | /// in-process implementations remain usable until their owner removes them. |
| 142 | fn is_alive(&self) -> bool { |
| 143 | true |
| 144 | } |
| 145 | |
| 146 | /// Best-effort shutdown. Called via `LspManager::shutdown_all`. |
| 147 | async fn shutdown(&self); |
| 148 | } |
| 149 | |
| 150 | type DiagnosticMessage = (PathBuf, Option<i64>, Vec<Diagnostic>); |
| 151 | |
| 152 | /// Stdio-backed transport. Spawns the LSP server as a child process and |
| 153 | /// pipes JSON-RPC over stdin/stdout. Stderr is drained without retaining or |
| 154 | /// exposing arbitrary server output. |
| 155 | pub struct StdioLspTransport { |
| 156 | /// JoinHandle for the running server. Held so the child stays alive for |
| 157 | /// the transport's lifetime; consumed during `shutdown`. |
| 158 | child: Arc<AsyncMutex<Option<Child>>>, |
| 159 | tree: Option<Arc<ProcessTree>>, |
| 160 | tasks: Vec<tokio::task::JoinHandle<()>>, |
| 161 | /// Outgoing message sender to the writer task. |
| 162 | tx_outbound: mpsc::Sender<Vec<u8>>, |
| 163 | /// Inbound diagnostics queue. We push every `publishDiagnostics` |
| 164 | /// notification into here and the public API drains the relevant entries. |
| 165 | diagnostics_gate: AsyncMutex<()>, |
| 166 | diagnostics_rx: AsyncMutex<mpsc::Receiver<DiagnosticMessage>>, |
| 167 | /// Map of in-flight request id -> reply slot for model-facing intelligence |
| 168 | /// requests (definition, references, symbols). |
| 169 | pending: Arc<AsyncMutex<HashMap<i64, oneshot::Sender<Value>>>>, |
| 170 | /// Monotonic request id counter for JSON-RPC request/reply methods. |
| 171 | next_id: AsyncMutex<i64>, |
| 172 | /// Language id passed in `textDocument/didOpen` (e.g. "rust"). |
| 173 | language_id: String, |
| 174 | /// Track which files we have opened so the second touch sends |
| 175 | /// `didChange` instead of `didOpen`. |
| 176 | opened: AsyncMutex<HashMap<PathBuf, i64>>, |
| 177 | } |
| 178 | |
| 179 | impl StdioLspTransport { |
| 180 | /// Spawn `command args…` and run the LSP `initialize` handshake. Returns |
| 181 | /// `Err` immediately if the binary is not on PATH or `initialize` fails. |
| 182 | pub(crate) async fn spawn( |
| 183 | command: &str, |
| 184 | args: &[String], |
| 185 | language_id: &str, |
| 186 | workspace: PathBuf, |
| 187 | ) -> Result<Self> { |
| 188 | Self::spawn_with_timeout(command, args, language_id, workspace, INITIALIZE_TIMEOUT).await |
| 189 | } |
| 190 | |
| 191 | async fn spawn_with_timeout( |
| 192 | command: &str, |
| 193 | args: &[String], |
| 194 | language_id: &str, |
| 195 | workspace: PathBuf, |
| 196 | initialize_wait: Duration, |
| 197 | ) -> Result<Self> { |
| 198 | let mut cmd = Command::new(command); |
| 199 | cmd.args(args); |
| 200 | cmd.current_dir(&workspace); |
| 201 | // Language servers execute workspace code (rust-analyzer runs build |
| 202 | // scripts and proc-macros), so they start from the sanitized child |
| 203 | // environment like `exec_shell`. |
| 204 | codewhale_runtime::child_env::apply_to_tokio_command( |
| 205 | &mut cmd, |
| 206 | std::iter::empty::<(&str, &str)>(), |
| 207 | ); |
| 208 | cmd.stdin(Stdio::piped()); |
| 209 | cmd.stdout(Stdio::piped()); |
| 210 | cmd.stderr(Stdio::piped()); |
| 211 | |
| 212 | let (mut child, tree) = spawn_contained_tokio(&mut cmd) |
| 213 | .with_context(|| format!("failed to spawn LSP server `{command}`"))?; |
| 214 | let tree = Arc::new(tree); |
| 215 | |
| 216 | let stdin = child |
| 217 | .stdin |
| 218 | .take() |
| 219 | .context("LSP child has no stdin handle")?; |
| 220 | let stdout = child |
| 221 | .stdout |
| 222 | .take() |
| 223 | .context("LSP child has no stdout handle")?; |
| 224 | |
| 225 | let mut stderr = child |
| 226 | .stderr |
| 227 | .take() |
| 228 | .context("LSP child has no stderr handle")?; |
| 229 | let stderr_task = |
| 230 | spawn_supervised("lsp-stderr", std::panic::Location::caller(), async move { |
| 231 | // Drain bytes, not lines: even a single unbounded log line must |
| 232 | // neither block the child nor accumulate in host memory. |
| 233 | let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await; |
| 234 | }); |
| 235 | |
| 236 | let (tx_outbound, rx_outbound) = mpsc::channel::<Vec<u8>>(64); |
| 237 | let (tx_inbound, rx_inbound) = mpsc::channel::<Value>(64); |
| 238 | let (tx_diag, rx_diag) = mpsc::channel::<DiagnosticMessage>(64); |
| 239 | |
| 240 | // Writer task: drain outbound channel, frame with Content-Length, write to stdin. |
| 241 | let writer_task = spawn_supervised( |
| 242 | "lsp-writer", |
| 243 | std::panic::Location::caller(), |
| 244 | writer_task(stdin, rx_outbound), |
| 245 | ); |
| 246 | // Reader task: parse Content-Length frames from stdout, push to inbound queue. |
| 247 | let reader_task = spawn_supervised( |
| 248 | "lsp-reader", |
| 249 | std::panic::Location::caller(), |
| 250 | reader_task(stdout, tx_inbound), |
| 251 | ); |
| 252 | // Inbound dispatcher: routes notifications to `tx_diag`, replies to a |
| 253 | // pending map. We keep the pending map for completeness even though |
| 254 | // diagnostics polling itself does not reuse it. |
| 255 | let pending: Arc<AsyncMutex<HashMap<i64, oneshot::Sender<Value>>>> = |
| 256 | Arc::new(AsyncMutex::new(HashMap::new())); |
| 257 | let child = Arc::new(AsyncMutex::new(Some(child))); |
| 258 | let dispatcher_child = child.clone(); |
| 259 | let dispatcher_tree = tree.clone(); |
| 260 | let dispatcher_pending = pending.clone(); |
| 261 | let dispatcher_outbound = tx_outbound.clone(); |
| 262 | let dispatcher_task = spawn_supervised( |
| 263 | "lsp-dispatcher", |
| 264 | std::panic::Location::caller(), |
| 265 | async move { |
| 266 | dispatcher_task(rx_inbound, tx_diag, dispatcher_outbound, dispatcher_pending).await; |
| 267 | let _ = dispatcher_tree.kill(); |
| 268 | if let Some(mut child) = dispatcher_child.lock().await.take() { |
| 269 | let _ = child.start_kill(); |
| 270 | let _ = child.wait().await; |
| 271 | dispatcher_tree.disarm(); |
| 272 | } |
| 273 | }, |
| 274 | ); |
| 275 | |
| 276 | let transport = Self { |
| 277 | child, |
| 278 | tree: Some(tree), |
| 279 | tasks: vec![stderr_task, writer_task, reader_task, dispatcher_task], |
| 280 | tx_outbound, |
| 281 | diagnostics_gate: AsyncMutex::new(()), |
| 282 | diagnostics_rx: AsyncMutex::new(rx_diag), |
| 283 | pending, |
| 284 | next_id: AsyncMutex::new(1), |
| 285 | language_id: language_id.to_string(), |
| 286 | opened: AsyncMutex::new(HashMap::new()), |
| 287 | }; |
| 288 | let result = transport.request("initialize", json!({ |
| 289 | "processId": std::process::id(), |
| 290 | "rootUri": uri_from_path(&workspace), |
| 291 | "capabilities": { |
| 292 | "general": { "positionEncodings": ["utf-16"] }, |
| 293 | "textDocument": { |
| 294 | "publishDiagnostics": { "relatedInformation": false, "versionSupport": true } |
| 295 | } |
| 296 | }, |
| 297 | "workspaceFolders": [{"uri": uri_from_path(&workspace), "name": "workspace"}] |
| 298 | }), initialize_wait).await.context("LSP initialization failed")?; |
| 299 | if !result.get("capabilities").is_some_and(Value::is_object) { |
| 300 | return Err(anyhow!( |
| 301 | "LSP initialize response is missing server capabilities" |
| 302 | )); |
| 303 | } |
| 304 | if result |
| 305 | .pointer("/capabilities/positionEncoding") |
| 306 | .is_some_and(|encoding| encoding.as_str() != Some("utf-16")) |
| 307 | { |
| 308 | return Err(anyhow!("LSP server must use UTF-16 positions")); |
| 309 | } |
| 310 | timeout( |
| 311 | initialize_wait, |
| 312 | send_message( |
| 313 | &transport.tx_outbound, |
| 314 | &json!({ |
| 315 | "jsonrpc": "2.0", "method": "initialized", "params": {} |
| 316 | }), |
| 317 | ), |
| 318 | ) |
| 319 | .await |
| 320 | .map_err(|_| anyhow!("LSP initialized notification timed out"))??; |
| 321 | Ok(transport) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | impl Drop for StdioLspTransport { |
| 326 | fn drop(&mut self) { |
| 327 | for task in &self.tasks { |
| 328 | task.abort(); |
| 329 | } |
| 330 | if let Some(tree) = &self.tree { |
| 331 | let _ = tree.kill(); |
| 332 | } |
| 333 | if let Ok(mut child) = self.child.try_lock() |
| 334 | && let Some(child) = child.as_mut() |
| 335 | { |
| 336 | let _ = child.start_kill(); |
| 337 | } |
| 338 | // If shutdown/dispatcher currently owns the child, abort releases |
| 339 | // its local Child and kill_on_drop remains the final fallback. |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | impl StdioLspTransport { |
| 344 | async fn open_or_change(&self, path: &Path, text: &str) -> Result<(String, i64)> { |
| 345 | let path_buf = path.to_path_buf(); |
| 346 | let uri = uri_from_path(&path_buf); |
| 347 | let mut opened = self.opened.lock().await; |
| 348 | let is_new = !opened.contains_key(&path_buf); |
| 349 | let new_version = opened.get(&path_buf).copied().unwrap_or(0) + 1; |
| 350 | |
| 351 | let payload = if is_new { |
| 352 | let language_id = if self.language_id == "typescript" |
| 353 | && path |
| 354 | .extension() |
| 355 | .is_some_and(|extension| extension.eq_ignore_ascii_case("tsx")) |
| 356 | { |
| 357 | "typescriptreact" |
| 358 | } else { |
| 359 | &self.language_id |
| 360 | }; |
| 361 | json!({ |
| 362 | "jsonrpc": "2.0", |
| 363 | "method": "textDocument/didOpen", |
| 364 | "params": { |
| 365 | "textDocument": { |
| 366 | "uri": uri.clone(), |
| 367 | "languageId": language_id, |
| 368 | "version": new_version, |
| 369 | "text": text |
| 370 | } |
| 371 | } |
| 372 | }) |
| 373 | } else { |
| 374 | json!({ |
| 375 | "jsonrpc": "2.0", |
| 376 | "method": "textDocument/didChange", |
| 377 | "params": { |
| 378 | "textDocument": { |
| 379 | "uri": uri.clone(), |
| 380 | "version": new_version |
| 381 | }, |
| 382 | "contentChanges": [{ "text": text }] |
| 383 | } |
| 384 | }) |
| 385 | }; |
| 386 | send_message(&self.tx_outbound, &payload).await?; |
| 387 | opened.insert(path_buf, new_version); |
| 388 | Ok((uri, new_version)) |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | #[async_trait] |
| 393 | impl LspTransport for StdioLspTransport { |
| 394 | fn is_alive(&self) -> bool { |
| 395 | // stderr may close independently. The writer, reader and dispatcher |
| 396 | // are the protocol lifetime; none may have exited or been aborted. |
| 397 | !self.tx_outbound.is_closed() && self.tasks.iter().skip(1).all(|task| !task.is_finished()) |
| 398 | } |
| 399 | |
| 400 | async fn diagnostics_for( |
| 401 | &self, |
| 402 | path: &Path, |
| 403 | text: &str, |
| 404 | wait: Duration, |
| 405 | ) -> Result<DiagnosticPublication> { |
| 406 | // One receiver cannot serve concurrent polling safely: serialize the |
| 407 | // open/version/send/wait transaction, including semantic ensure_open. |
| 408 | let deadline = tokio::time::Instant::now() + wait; |
| 409 | let _gate = timeout(wait, self.diagnostics_gate.lock()) |
| 410 | .await |
| 411 | .map_err(|_| anyhow!("LSP diagnostics timed out waiting for another document"))?; |
| 412 | let path_buf = path.to_path_buf(); |
| 413 | let (_, version) = timeout( |
| 414 | deadline.saturating_duration_since(tokio::time::Instant::now()), |
| 415 | self.open_or_change(path, text), |
| 416 | ) |
| 417 | .await |
| 418 | .map_err(|_| anyhow!("LSP diagnostics timed out sending document"))??; |
| 419 | loop { |
| 420 | let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 421 | if remaining.is_zero() { |
| 422 | return Err(anyhow!( |
| 423 | "LSP diagnostics timed out before a current publication" |
| 424 | )); |
| 425 | } |
| 426 | let mut rx = self.diagnostics_rx.lock().await; |
| 427 | let (file, published_version, items) = match timeout(remaining, rx.recv()).await { |
| 428 | Ok(Some(item)) => item, |
| 429 | Ok(None) => { |
| 430 | return Err(anyhow!( |
| 431 | "LSP diagnostics channel closed before publishDiagnostics" |
| 432 | )); |
| 433 | } |
| 434 | Err(_) => { |
| 435 | return Err(anyhow!( |
| 436 | "LSP diagnostics timed out before a current publication" |
| 437 | )); |
| 438 | } |
| 439 | }; |
| 440 | if file != path_buf || published_version.is_some_and(|published| published != version) { |
| 441 | continue; |
| 442 | } |
| 443 | return Ok(DiagnosticPublication { |
| 444 | items, |
| 445 | document_version: Some(version), |
| 446 | diagnostic_version: published_version, |
| 447 | }); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | async fn request_for_document( |
| 452 | &self, |
| 453 | path: &Path, |
| 454 | text: &str, |
| 455 | method: &str, |
| 456 | params: Value, |
| 457 | wait: Duration, |
| 458 | ) -> Result<SemanticReply> { |
| 459 | let deadline = tokio::time::Instant::now() + wait; |
| 460 | let _gate = timeout(wait, self.diagnostics_gate.lock()) |
| 461 | .await |
| 462 | .map_err(|_| anyhow!("LSP semantic request timed out waiting for another document"))?; |
| 463 | let (_, version) = timeout( |
| 464 | deadline.saturating_duration_since(tokio::time::Instant::now()), |
| 465 | self.open_or_change(path, text), |
| 466 | ) |
| 467 | .await |
| 468 | .map_err(|_| anyhow!("LSP semantic request timed out sending document"))??; |
| 469 | let result = self |
| 470 | .request( |
| 471 | method, |
| 472 | params, |
| 473 | deadline.saturating_duration_since(tokio::time::Instant::now()), |
| 474 | ) |
| 475 | .await?; |
| 476 | Ok(SemanticReply { |
| 477 | result, |
| 478 | document_version: Some(version), |
| 479 | }) |
| 480 | } |
| 481 | |
| 482 | async fn ensure_open(&self, path: &Path, text: &str) -> Result<()> { |
| 483 | let _gate = self.diagnostics_gate.lock().await; |
| 484 | self.open_or_change(path, text).await?; |
| 485 | Ok(()) |
| 486 | } |
| 487 | |
| 488 | async fn request(&self, method: &str, params: Value, wait: Duration) -> Result<Value> { |
| 489 | let id = { |
| 490 | let mut next = self.next_id.lock().await; |
| 491 | let id = *next; |
| 492 | *next = next.saturating_add(1); |
| 493 | id |
| 494 | }; |
| 495 | let (tx, rx) = oneshot::channel(); |
| 496 | { |
| 497 | let mut pending = self.pending.lock().await; |
| 498 | pending.insert(id, tx); |
| 499 | } |
| 500 | let payload = json!({ |
| 501 | "jsonrpc": "2.0", |
| 502 | "id": id, |
| 503 | "method": method, |
| 504 | "params": params, |
| 505 | }); |
| 506 | // The deadline includes queue backpressure, not just the reply. |
| 507 | let response = timeout(wait, async { |
| 508 | send_message(&self.tx_outbound, &payload).await?; |
| 509 | rx.await.map_err(|_| anyhow!("LSP request channel closed")) |
| 510 | }) |
| 511 | .await; |
| 512 | self.pending.lock().await.remove(&id); |
| 513 | match response { |
| 514 | Ok(Ok(reply)) => { |
| 515 | if let Some(error) = reply.get("error") { |
| 516 | let message = error |
| 517 | .get("message") |
| 518 | .and_then(Value::as_str) |
| 519 | .unwrap_or("LSP request failed"); |
| 520 | return Err(anyhow!("{message}")); |
| 521 | } |
| 522 | reply |
| 523 | .get("result") |
| 524 | .cloned() |
| 525 | .ok_or_else(|| anyhow!("LSP response has no result")) |
| 526 | } |
| 527 | Ok(Err(error)) => Err(error), |
| 528 | Err(_) => Err(anyhow!("LSP request timed out for {method}")), |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | async fn shutdown(&self) { |
| 533 | if let Some(tree) = &self.tree { |
| 534 | let _ = tree.kill(); |
| 535 | } |
| 536 | let mut child = self.child.lock().await; |
| 537 | if let Some(mut c) = child.take() { |
| 538 | let _ = c.start_kill(); |
| 539 | let _ = c.wait().await; |
| 540 | if let Some(tree) = &self.tree { |
| 541 | tree.disarm(); |
| 542 | } |
| 543 | } |
| 544 | for task in &self.tasks { |
| 545 | task.abort(); |
| 546 | } |
| 547 | self.pending.lock().await.clear(); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | /// Send a JSON value as one Content-Length-framed JSON-RPC message. |
| 552 | async fn send_message(tx: &mpsc::Sender<Vec<u8>>, value: &Value) -> Result<()> { |
| 553 | tx.send(frame_message(value)?) |
| 554 | .await |
| 555 | .map_err(|_| anyhow!("LSP outbound channel closed"))?; |
| 556 | Ok(()) |
| 557 | } |
| 558 | |
| 559 | fn frame_message(value: &Value) -> Result<Vec<u8>> { |
| 560 | let body = serde_json::to_vec(value).context("serialize LSP message")?; |
| 561 | let header = format!("Content-Length: {}\r\n\r\n", body.len()); |
| 562 | let mut frame = Vec::with_capacity(header.len() + body.len()); |
| 563 | frame.extend_from_slice(header.as_bytes()); |
| 564 | frame.extend_from_slice(&body); |
| 565 | Ok(frame) |
| 566 | } |
| 567 | |
| 568 | /// Background task that drains the outbound queue and writes each frame to |
| 569 | /// the LSP server's stdin. Exits cleanly when the channel closes. |
| 570 | async fn writer_task(mut stdin: tokio::process::ChildStdin, mut rx: mpsc::Receiver<Vec<u8>>) { |
| 571 | while let Some(frame) = rx.recv().await { |
| 572 | if stdin.write_all(&frame).await.is_err() { |
| 573 | break; |
| 574 | } |
| 575 | if stdin.flush().await.is_err() { |
| 576 | break; |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | /// Background task that parses `Content-Length`-framed JSON-RPC frames from |
| 582 | /// the LSP server's stdout. Pushes each parsed JSON value to `tx`. Exits |
| 583 | /// when stdout closes or a frame is malformed (we choose to fail closed |
| 584 | /// rather than risk hanging). |
| 585 | async fn reader_task(mut stdout: impl AsyncRead + Unpin, tx: mpsc::Sender<Value>) { |
| 586 | let mut buf: Vec<u8> = Vec::with_capacity(8 * 1024); |
| 587 | let mut tmp = [0u8; 4096]; |
| 588 | loop { |
| 589 | let n = match stdout.read(&mut tmp).await { |
| 590 | Ok(0) => return, |
| 591 | Ok(n) => n, |
| 592 | Err(_) => return, |
| 593 | }; |
| 594 | buf.extend_from_slice(&tmp[..n]); |
| 595 | loop { |
| 596 | let (header_end, content_length) = match parse_header(&buf) { |
| 597 | Ok(Some(frame)) => frame, |
| 598 | Ok(None) => break, |
| 599 | Err(_) => return, |
| 600 | }; |
| 601 | // Both operands are bounded by parse_header. |
| 602 | let frame_end = header_end + content_length; |
| 603 | if buf.len() < frame_end { |
| 604 | break; |
| 605 | } |
| 606 | let value = match serde_json::from_slice::<Value>(&buf[header_end..frame_end]) { |
| 607 | Ok(value) => value, |
| 608 | Err(_) => return, |
| 609 | }; |
| 610 | buf.drain(..frame_end); |
| 611 | if tx.send(value).await.is_err() { |
| 612 | return; |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | /// Distinguish incomplete headers from malformed or oversized frames so a |
| 619 | /// broken server cannot cause an indefinitely growing input buffer. |
| 620 | fn parse_header(buf: &[u8]) -> Result<Option<(usize, usize)>> { |
| 621 | let Some(pos) = buf.windows(4).position(|window| window == b"\r\n\r\n") else { |
| 622 | if buf.len() > MAX_LSP_HEADER_BYTES { |
| 623 | return Err(anyhow!("LSP header exceeds size limit")); |
| 624 | } |
| 625 | return Ok(None); |
| 626 | }; |
| 627 | if pos + 4 > MAX_LSP_HEADER_BYTES { |
| 628 | return Err(anyhow!("LSP header exceeds size limit")); |
| 629 | } |
| 630 | let header = std::str::from_utf8(&buf[..pos]).context("invalid LSP header encoding")?; |
| 631 | let mut content_length = None; |
| 632 | for line in header.split("\r\n") { |
| 633 | let (name, value) = line.split_once(':').context("malformed LSP header")?; |
| 634 | if name.eq_ignore_ascii_case("Content-Length") { |
| 635 | if content_length.is_some() { |
| 636 | return Err(anyhow!("duplicate LSP Content-Length")); |
| 637 | } |
| 638 | let length = value |
| 639 | .trim() |
| 640 | .parse::<usize>() |
| 641 | .context("invalid LSP Content-Length")?; |
| 642 | if length == 0 || length > MAX_LSP_FRAME_BYTES { |
| 643 | return Err(anyhow!("LSP frame exceeds size limit or is empty")); |
| 644 | } |
| 645 | content_length = Some(length); |
| 646 | } |
| 647 | } |
| 648 | Ok(Some(( |
| 649 | pos + 4, |
| 650 | content_length.context("missing LSP Content-Length")?, |
| 651 | ))) |
| 652 | } |
| 653 | |
| 654 | /// Background task that consumes inbound JSON values, classifies them as |
| 655 | /// notifications/responses, and routes accordingly. |
| 656 | async fn dispatcher_task( |
| 657 | mut rx: mpsc::Receiver<Value>, |
| 658 | tx_diag: mpsc::Sender<DiagnosticMessage>, |
| 659 | tx_outbound: mpsc::Sender<Vec<u8>>, |
| 660 | pending: Arc<AsyncMutex<HashMap<i64, oneshot::Sender<Value>>>>, |
| 661 | ) { |
| 662 | while let Some(value) = rx.recv().await { |
| 663 | // Notifications have a `method` and no `id`. |
| 664 | let method = value.get("method").and_then(|v| v.as_str()); |
| 665 | if method == Some("textDocument/publishDiagnostics") { |
| 666 | if let Some(publication) = parse_publish_diagnostics(&value) { |
| 667 | // Do not let an unconsumed diagnostics burst prevent reply |
| 668 | // delivery or EOF cleanup. Overflow closes this transport's |
| 669 | // dispatcher, giving callers an explicit channel error. |
| 670 | if tx_diag.try_send(publication).is_err() { |
| 671 | break; |
| 672 | } |
| 673 | } |
| 674 | continue; |
| 675 | } |
| 676 | if let Some(method) = method { |
| 677 | if let Some(id) = value.get("id") { |
| 678 | let reply = json!({ |
| 679 | "jsonrpc": "2.0", |
| 680 | "id": id, |
| 681 | "error": {"code": -32601, "message": format!("unsupported method {method}")}, |
| 682 | }); |
| 683 | if let Ok(frame) = frame_message(&reply) { |
| 684 | let _ = tx_outbound.try_send(frame); |
| 685 | } |
| 686 | } |
| 687 | continue; |
| 688 | } |
| 689 | // Replies have an `id` and a `result` or `error`. |
| 690 | if let Some(id) = value.get("id").and_then(|v| v.as_i64()) { |
| 691 | let mut map = pending.lock().await; |
| 692 | if let Some(slot) = map.remove(&id) { |
| 693 | let _ = slot.send(value); |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | // Reader EOF/malformed frames and queue overflow wake every pending |
| 698 | // request immediately instead of leaving reply slots until their timeout. |
| 699 | pending.lock().await.clear(); |
| 700 | } |
| 701 | |
| 702 | /// Decode a `textDocument/publishDiagnostics` notification. |
| 703 | fn parse_publish_diagnostics(value: &Value) -> Option<DiagnosticMessage> { |
| 704 | let params = value.get("params")?; |
| 705 | let uri = params.get("uri")?.as_str()?; |
| 706 | let path = path_from_uri(uri)?; |
| 707 | let version = match params.get("version") { |
| 708 | None | Some(Value::Null) => None, |
| 709 | Some(value) => Some(value.as_i64()?), |
| 710 | }; |
| 711 | let raw = params.get("diagnostics")?.as_array()?; |
| 712 | let mut out = Vec::with_capacity(raw.len()); |
| 713 | for d in raw { |
| 714 | let range = d.get("range")?; |
| 715 | let start = range.get("start")?; |
| 716 | let line = u32::try_from(start.get("line")?.as_u64()?) |
| 717 | .ok()? |
| 718 | .checked_add(1)?; |
| 719 | let column = u32::try_from(start.get("character")?.as_u64()?) |
| 720 | .ok()? |
| 721 | .checked_add(1)?; |
| 722 | let severity = Severity::from_lsp(d.get("severity").and_then(|v| v.as_i64())) |
| 723 | .unwrap_or(Severity::Error); |
| 724 | let message = d |
| 725 | .get("message") |
| 726 | .and_then(|v| v.as_str()) |
| 727 | .unwrap_or("") |
| 728 | .to_string(); |
| 729 | out.push(Diagnostic { |
| 730 | line, |
| 731 | column, |
| 732 | severity, |
| 733 | message, |
| 734 | }); |
| 735 | } |
| 736 | Some((path, version, out)) |
| 737 | } |
| 738 | |
| 739 | /// Encode an absolute filesystem path without following its links. |
| 740 | pub fn uri_from_path(path: &Path) -> String { |
| 741 | reqwest::Url::from_file_path(path) |
| 742 | .map(|url| url.to_string()) |
| 743 | .unwrap_or_default() |
| 744 | } |
| 745 | |
| 746 | /// File URLs only: no network authority, query or fragment. Decoding happens |
| 747 | /// before the workspace no-follow opener validates the target path. |
| 748 | pub(super) fn path_from_uri(uri: &str) -> Option<PathBuf> { |
| 749 | let url = reqwest::Url::parse(uri).ok()?; |
| 750 | if url.scheme() != "file" |
| 751 | || url.host_str().is_some_and(|host| !host.is_empty()) |
| 752 | || !url.username().is_empty() |
| 753 | || url.password().is_some() |
| 754 | || url.port().is_some() |
| 755 | || url.query().is_some() |
| 756 | || url.fragment().is_some() |
| 757 | { |
| 758 | return None; |
| 759 | } |
| 760 | url.to_file_path().ok() |
| 761 | } |
| 762 | |
| 763 | #[cfg(test)] |
| 764 | pub(super) mod tests { |
| 765 | use super::*; |
| 766 | |
| 767 | fn fixture_path(name: &str) -> PathBuf { |
| 768 | std::env::temp_dir() |
| 769 | .join("codewhale-lsp-fixture") |
| 770 | .join(name) |
| 771 | } |
| 772 | |
| 773 | #[test] |
| 774 | fn parses_lsp_header() { |
| 775 | let frame = b"Content-Length: 5\r\n\r\nhello"; |
| 776 | let (end, len) = parse_header(frame) |
| 777 | .expect("valid header") |
| 778 | .expect("header parses"); |
| 779 | assert_eq!(end, 21); |
| 780 | assert_eq!(len, 5); |
| 781 | } |
| 782 | |
| 783 | #[test] |
| 784 | fn parse_header_returns_none_when_truncated() { |
| 785 | let frame = b"Content-Length: 5\r\nMissingTerm"; |
| 786 | assert!(parse_header(frame).unwrap().is_none()); |
| 787 | } |
| 788 | |
| 789 | #[test] |
| 790 | fn parses_publish_diagnostics_payload() { |
| 791 | let payload = json!({ |
| 792 | "jsonrpc": "2.0", |
| 793 | "method": "textDocument/publishDiagnostics", |
| 794 | "params": { |
| 795 | "uri": uri_from_path(&fixture_path("foo.rs")), |
| 796 | "diagnostics": [ |
| 797 | { |
| 798 | "range": { |
| 799 | "start": { "line": 11, "character": 7 }, |
| 800 | "end": { "line": 11, "character": 8 } |
| 801 | }, |
| 802 | "severity": 1, |
| 803 | "message": "missing semicolon" |
| 804 | } |
| 805 | ] |
| 806 | } |
| 807 | }); |
| 808 | let (path, version, diags) = parse_publish_diagnostics(&payload).expect("parses"); |
| 809 | assert_eq!(path, fixture_path("foo.rs")); |
| 810 | assert_eq!(version, None); |
| 811 | assert_eq!(diags.len(), 1); |
| 812 | assert_eq!(diags[0].line, 12); |
| 813 | assert_eq!(diags[0].column, 8); |
| 814 | assert_eq!(diags[0].severity, Severity::Error); |
| 815 | assert_eq!(diags[0].message, "missing semicolon"); |
| 816 | } |
| 817 | |
| 818 | #[tokio::test] |
| 819 | async fn server_request_sharing_a_pending_id_is_answered_not_taken_as_the_reply() { |
| 820 | let (tx_in, rx_in) = mpsc::channel(4); |
| 821 | let (tx_out, mut rx_out) = mpsc::channel::<Vec<u8>>(4); |
| 822 | let (tx_diag, _rx_diag) = mpsc::channel(4); |
| 823 | let pending = Arc::new(AsyncMutex::new(HashMap::new())); |
| 824 | let (reply_tx, reply_rx) = oneshot::channel(); |
| 825 | pending.lock().await.insert(2, reply_tx); |
| 826 | let dispatcher = tokio::spawn(dispatcher_task(rx_in, tx_diag, tx_out, pending)); |
| 827 | tx_in |
| 828 | .send(json!({"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[]}})) |
| 829 | .await |
| 830 | .unwrap(); |
| 831 | tx_in |
| 832 | .send(json!({"jsonrpc":"2.0","id":2,"result":"definition"})) |
| 833 | .await |
| 834 | .unwrap(); |
| 835 | assert_eq!(reply_rx.await.unwrap()["result"], "definition"); |
| 836 | let answer = next_document(&mut rx_out).await; |
| 837 | assert_eq!(answer["id"], 2); |
| 838 | assert_eq!(answer["error"]["code"], -32601); |
| 839 | drop(tx_in); |
| 840 | dispatcher.await.unwrap(); |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn round_trips_uri_path() { |
| 845 | let path = fixture_path("example/foo.rs"); |
| 846 | let uri = uri_from_path(&path); |
| 847 | assert_eq!(path_from_uri(&uri), Some(path)); |
| 848 | } |
| 849 | |
| 850 | #[tokio::test] |
| 851 | async fn closed_diagnostics_channel_is_an_error_not_an_empty_result() { |
| 852 | let (tx_outbound, _rx_outbound) = mpsc::channel(1); |
| 853 | let (tx_diag, rx_diag) = mpsc::channel(1); |
| 854 | drop(tx_diag); |
| 855 | let transport = StdioLspTransport { |
| 856 | child: Arc::new(AsyncMutex::new(None)), |
| 857 | tree: None, |
| 858 | tasks: Vec::new(), |
| 859 | tx_outbound, |
| 860 | diagnostics_gate: AsyncMutex::new(()), |
| 861 | diagnostics_rx: AsyncMutex::new(rx_diag), |
| 862 | pending: Arc::new(AsyncMutex::new(HashMap::new())), |
| 863 | next_id: AsyncMutex::new(1), |
| 864 | language_id: "rust".to_string(), |
| 865 | opened: AsyncMutex::new(HashMap::new()), |
| 866 | }; |
| 867 | |
| 868 | let error = transport |
| 869 | .diagnostics_for( |
| 870 | &fixture_path("closed-channel.rs"), |
| 871 | "fn main() {}\n", |
| 872 | Duration::from_secs(5), |
| 873 | ) |
| 874 | .await |
| 875 | .expect_err("a closed transport must not look like an empty lint result"); |
| 876 | |
| 877 | assert!( |
| 878 | error.to_string().contains("diagnostics channel closed"), |
| 879 | "unexpected error: {error}" |
| 880 | ); |
| 881 | } |
| 882 | |
| 883 | fn diagnostic_fixture() -> ( |
| 884 | StdioLspTransport, |
| 885 | mpsc::Receiver<Vec<u8>>, |
| 886 | mpsc::Sender<DiagnosticMessage>, |
| 887 | ) { |
| 888 | let (tx_outbound, rx_outbound) = mpsc::channel(8); |
| 889 | let (tx_diag, rx_diag) = mpsc::channel(8); |
| 890 | ( |
| 891 | StdioLspTransport { |
| 892 | child: Arc::new(AsyncMutex::new(None)), |
| 893 | tree: None, |
| 894 | tasks: Vec::new(), |
| 895 | tx_outbound, |
| 896 | diagnostics_gate: AsyncMutex::new(()), |
| 897 | diagnostics_rx: AsyncMutex::new(rx_diag), |
| 898 | pending: Arc::new(AsyncMutex::new(HashMap::new())), |
| 899 | next_id: AsyncMutex::new(1), |
| 900 | language_id: "rust".into(), |
| 901 | opened: AsyncMutex::new(HashMap::new()), |
| 902 | }, |
| 903 | rx_outbound, |
| 904 | tx_diag, |
| 905 | ) |
| 906 | } |
| 907 | |
| 908 | async fn next_document(rx: &mut mpsc::Receiver<Vec<u8>>) -> Value { |
| 909 | let frame = rx.recv().await.unwrap(); |
| 910 | let (start, _) = parse_header(&frame).unwrap().unwrap(); |
| 911 | serde_json::from_slice::<Value>(&frame[start..]).unwrap() |
| 912 | } |
| 913 | |
| 914 | fn diagnostic(line: u32) -> Diagnostic { |
| 915 | Diagnostic { |
| 916 | line, |
| 917 | column: 1, |
| 918 | severity: Severity::Error, |
| 919 | message: "fixture".into(), |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | #[tokio::test] |
| 924 | async fn diagnostic_freshness_rejects_old_version_and_accepts_current_empty_publication() { |
| 925 | let (transport, mut outbound, diag) = diagnostic_fixture(); |
| 926 | let server = tokio::spawn(async move { |
| 927 | let first = next_document(&mut outbound).await; |
| 928 | assert_eq!(first["method"], "textDocument/didOpen"); |
| 929 | assert_eq!(first["params"]["textDocument"]["version"], 1); |
| 930 | let path = |
| 931 | path_from_uri(first["params"]["textDocument"]["uri"].as_str().unwrap()).unwrap(); |
| 932 | diag.send((path.clone(), Some(1), vec![diagnostic(1)])) |
| 933 | .await |
| 934 | .unwrap(); |
| 935 | let second = next_document(&mut outbound).await; |
| 936 | assert_eq!(second["method"], "textDocument/didChange"); |
| 937 | assert_eq!(second["params"]["textDocument"]["version"], 2); |
| 938 | assert_eq!(second["params"]["contentChanges"][0]["text"], "new 🐋 text"); |
| 939 | diag.send((path.clone(), Some(1), vec![diagnostic(99)])) |
| 940 | .await |
| 941 | .unwrap(); |
| 942 | diag.send((path, Some(2), vec![])).await.unwrap(); |
| 943 | }); |
| 944 | let path = &fixture_path("freshness.rs"); |
| 945 | let first = transport |
| 946 | .diagnostics_for(path, "old text", Duration::from_secs(1)) |
| 947 | .await |
| 948 | .unwrap(); |
| 949 | assert_eq!(first.freshness(), "verified"); |
| 950 | assert_eq!(first.items[0].line, 1); |
| 951 | let second = transport |
| 952 | .diagnostics_for(path, "new 🐋 text", Duration::from_secs(1)) |
| 953 | .await |
| 954 | .unwrap(); |
| 955 | assert_eq!(second.freshness(), "verified"); |
| 956 | assert_eq!(second.document_version, Some(2)); |
| 957 | assert_eq!(second.diagnostic_version, Some(2)); |
| 958 | assert!( |
| 959 | second.items.is_empty(), |
| 960 | "old error must not apply to the new text" |
| 961 | ); |
| 962 | server.await.unwrap(); |
| 963 | } |
| 964 | |
| 965 | #[tokio::test] |
| 966 | async fn diagnostic_freshness_serializes_concurrent_file_requests() { |
| 967 | let (transport, mut outbound, diag) = diagnostic_fixture(); |
| 968 | let server = tokio::spawn(async move { |
| 969 | for _ in 0..2 { |
| 970 | let request = next_document(&mut outbound).await; |
| 971 | assert!( |
| 972 | matches!(outbound.try_recv(), Err(mpsc::error::TryRecvError::Empty)), |
| 973 | "second file must not advance before this publication" |
| 974 | ); |
| 975 | let path = |
| 976 | path_from_uri(request["params"]["textDocument"]["uri"].as_str().unwrap()) |
| 977 | .unwrap(); |
| 978 | let line = if path.ends_with("one.rs") { 1 } else { 2 }; |
| 979 | diag.send((fixture_path("unrelated.rs"), Some(1), vec![diagnostic(99)])) |
| 980 | .await |
| 981 | .unwrap(); |
| 982 | diag.send((path, Some(1), vec![diagnostic(line)])) |
| 983 | .await |
| 984 | .unwrap(); |
| 985 | } |
| 986 | }); |
| 987 | let one_path = fixture_path("one.rs"); |
| 988 | let two_path = fixture_path("two.rs"); |
| 989 | let (one, two) = tokio::join!( |
| 990 | transport.diagnostics_for(&one_path, "one", Duration::from_secs(1)), |
| 991 | transport.diagnostics_for(&two_path, "two", Duration::from_secs(1)), |
| 992 | ); |
| 993 | assert_eq!(one.unwrap().items[0].line, 1); |
| 994 | assert_eq!(two.unwrap().items[0].line, 2); |
| 995 | server.await.unwrap(); |
| 996 | } |
| 997 | |
| 998 | #[tokio::test] |
| 999 | async fn diagnostic_freshness_unversioned_is_unverified_and_silence_is_error() { |
| 1000 | let (transport, mut outbound, diag) = diagnostic_fixture(); |
| 1001 | let server = tokio::spawn(async move { |
| 1002 | let request = next_document(&mut outbound).await; |
| 1003 | let path = |
| 1004 | path_from_uri(request["params"]["textDocument"]["uri"].as_str().unwrap()).unwrap(); |
| 1005 | diag.send((path, None, vec![])).await.unwrap(); |
| 1006 | // Keep the channels alive while the second request times out. |
| 1007 | let _ = next_document(&mut outbound).await; |
| 1008 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 1009 | }); |
| 1010 | let response = transport |
| 1011 | .diagnostics_for( |
| 1012 | &fixture_path("unversioned.rs"), |
| 1013 | "text", |
| 1014 | Duration::from_secs(1), |
| 1015 | ) |
| 1016 | .await |
| 1017 | .unwrap(); |
| 1018 | assert_eq!(response.freshness(), "unverified"); |
| 1019 | assert_eq!(response.diagnostic_version, None); |
| 1020 | assert!( |
| 1021 | transport |
| 1022 | .diagnostics_for( |
| 1023 | &fixture_path("silent.rs"), |
| 1024 | "text", |
| 1025 | Duration::from_millis(10) |
| 1026 | ) |
| 1027 | .await |
| 1028 | .unwrap_err() |
| 1029 | .to_string() |
| 1030 | .contains("timed out") |
| 1031 | ); |
| 1032 | server.abort(); |
| 1033 | } |
| 1034 | |
| 1035 | #[test] |
| 1036 | fn diagnostic_freshness_parser_retains_version_and_rejects_malformed_version() { |
| 1037 | let mut payload = json!({"params":{"uri":uri_from_path(&fixture_path("version.rs")),"version":4,"diagnostics":[]}}); |
| 1038 | assert_eq!(parse_publish_diagnostics(&payload).unwrap().1, Some(4)); |
| 1039 | payload["params"]["version"] = json!("4"); |
| 1040 | assert!(parse_publish_diagnostics(&payload).is_none()); |
| 1041 | } |
| 1042 | #[cfg(unix)] |
| 1043 | pub const STDIO_FIXTURE: &str = r#" |
| 1044 | import json, os, select, sys, time |
| 1045 | mode, pid_path = sys.argv[1:] |
| 1046 | input_stream = os.fdopen(0, 'rb', buffering=0) |
| 1047 | with open(pid_path, 'a' if mode == 'cache' else 'w') as f: |
| 1048 | if mode == 'cwd': |
| 1049 | f.write(os.getcwd()) |
| 1050 | else: |
| 1051 | f.write(str(os.getpid()) + ('\n' if mode == 'cache' else '')) |
| 1052 | def read(): |
| 1053 | headers = {} |
| 1054 | while True: |
| 1055 | line = input_stream.readline() |
| 1056 | if not line: |
| 1057 | raise SystemExit(0) |
| 1058 | if line == b'\r\n': |
| 1059 | break |
| 1060 | key, value = line.decode().split(':', 1) |
| 1061 | headers[key.lower()] = value.strip() |
| 1062 | body = b'' |
| 1063 | length = int(headers['content-length']) |
| 1064 | while len(body) < length: |
| 1065 | chunk = input_stream.read(length - len(body)) |
| 1066 | if not chunk: |
| 1067 | raise SystemExit(0) |
| 1068 | body += chunk |
| 1069 | return json.loads(body) |
| 1070 | def send(value): |
| 1071 | body = json.dumps(value).encode() |
| 1072 | sys.stdout.buffer.write(('Content-Length: %d\r\n\r\n' % len(body)).encode() + body) |
| 1073 | sys.stdout.buffer.flush() |
| 1074 | request = read() |
| 1075 | assert request['method'] == 'initialize' |
| 1076 | if mode == 'eof': |
| 1077 | raise SystemExit(0) |
| 1078 | if mode == 'silence': |
| 1079 | time.sleep(60) |
| 1080 | if mode == 'error': |
| 1081 | send({'jsonrpc':'2.0','id':request['id'],'error':{'code':-32002,'message':'fixture rejected initialization'}}) |
| 1082 | time.sleep(60) |
| 1083 | if mode == 'delayed' and select.select([input_stream], [], [], 0.1)[0]: |
| 1084 | send({'jsonrpc':'2.0','id':request['id'],'error':{'code':-32002,'message':'notification arrived before initialize reply'}}) |
| 1085 | raise SystemExit(1) |
| 1086 | if mode == 'stderr': |
| 1087 | for _ in range(64): |
| 1088 | os.write(2, b'x' * 32768) |
| 1089 | send({'jsonrpc':'2.0','id':request['id'],'result':{'capabilities':{}}}) |
| 1090 | assert read()['method'] == 'initialized' |
| 1091 | while True: |
| 1092 | request = read() |
| 1093 | if request.get('method') == 'fixture/exit': |
| 1094 | raise SystemExit(0) |
| 1095 | if request.get('method') == 'fixture/overflow': |
| 1096 | for _ in range(80): |
| 1097 | send({'jsonrpc':'2.0','method':'textDocument/publishDiagnostics','params':{'uri':'file:///tmp/overflow.rs','version':1,'diagnostics':[]}}) |
| 1098 | time.sleep(60) |
| 1099 | elif 'id' in request: |
| 1100 | send({'jsonrpc':'2.0','id':request['id'],'result':{'ready':True}}) |
| 1101 | "#; |
| 1102 | |
| 1103 | #[cfg(unix)] |
| 1104 | async fn spawn_stdio_fixture( |
| 1105 | mode: &str, |
| 1106 | root: &Path, |
| 1107 | wait: Duration, |
| 1108 | ) -> Result<StdioLspTransport> { |
| 1109 | StdioLspTransport::spawn_with_timeout( |
| 1110 | "python3", |
| 1111 | &[ |
| 1112 | "-u".into(), |
| 1113 | "-c".into(), |
| 1114 | STDIO_FIXTURE.into(), |
| 1115 | mode.into(), |
| 1116 | root.join("pid").to_string_lossy().into_owned(), |
| 1117 | ], |
| 1118 | "rust", |
| 1119 | root.to_path_buf(), |
| 1120 | wait, |
| 1121 | ) |
| 1122 | .await |
| 1123 | } |
| 1124 | |
| 1125 | #[cfg(unix)] |
| 1126 | async fn assert_fixture_exited(root: &Path) { |
| 1127 | let pid = std::fs::read_to_string(root.join("pid")) |
| 1128 | .expect("fixture started") |
| 1129 | .parse::<i32>() |
| 1130 | .unwrap(); |
| 1131 | for _ in 0..100 { |
| 1132 | // Signal zero probes only this fixture PID; it never sends a signal. |
| 1133 | if unsafe { libc::kill(pid, 0) } == -1 { |
| 1134 | assert_eq!( |
| 1135 | std::io::Error::last_os_error().raw_os_error(), |
| 1136 | Some(libc::ESRCH) |
| 1137 | ); |
| 1138 | return; |
| 1139 | } |
| 1140 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 1141 | } |
| 1142 | panic!("fixture child remained alive after transport termination"); |
| 1143 | } |
| 1144 | |
| 1145 | #[cfg(unix)] |
| 1146 | #[tokio::test] |
| 1147 | async fn stdio_startup_waits_for_initialize_and_drains_stderr_pressure() { |
| 1148 | for mode in ["delayed", "stderr"] { |
| 1149 | let root = tempfile::tempdir().unwrap(); |
| 1150 | let transport = spawn_stdio_fixture(mode, root.path(), Duration::from_secs(3)) |
| 1151 | .await |
| 1152 | .unwrap(); |
| 1153 | let result = transport |
| 1154 | .request("fixture/ready", json!({}), Duration::from_secs(1)) |
| 1155 | .await |
| 1156 | .unwrap(); |
| 1157 | assert_eq!(result["ready"], true, "{mode}"); |
| 1158 | transport.shutdown().await; |
| 1159 | assert_fixture_exited(root.path()).await; |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | #[cfg(unix)] |
| 1164 | #[tokio::test] |
| 1165 | async fn stdio_startup_error_eof_and_silence_fail_and_terminate_child() { |
| 1166 | for (mode, expected, initialize_wait) in [ |
| 1167 | ( |
| 1168 | "error", |
| 1169 | "fixture rejected initialization", |
| 1170 | Duration::from_secs(10), |
| 1171 | ), |
| 1172 | ("eof", "channel closed", Duration::from_secs(10)), |
| 1173 | ("silence", "timed out", Duration::from_secs(2)), |
| 1174 | ] { |
| 1175 | let root = tempfile::tempdir().unwrap(); |
| 1176 | let error = match timeout( |
| 1177 | initialize_wait + Duration::from_secs(5), |
| 1178 | spawn_stdio_fixture(mode, root.path(), initialize_wait), |
| 1179 | ) |
| 1180 | .await |
| 1181 | .unwrap() |
| 1182 | { |
| 1183 | Ok(_) => panic!("{mode} unexpectedly initialized"), |
| 1184 | Err(error) => error, |
| 1185 | }; |
| 1186 | assert!(format!("{error:#}").contains(expected), "{mode}: {error:#}"); |
| 1187 | assert_fixture_exited(root.path()).await; |
| 1188 | } |
| 1189 | } |
| 1190 | |
| 1191 | #[cfg(unix)] |
| 1192 | #[tokio::test] |
| 1193 | async fn stdio_diagnostic_overflow_fails_pending_request_and_terminates_child() { |
| 1194 | let root = tempfile::tempdir().unwrap(); |
| 1195 | let transport = spawn_stdio_fixture("ready", root.path(), Duration::from_secs(3)) |
| 1196 | .await |
| 1197 | .unwrap(); |
| 1198 | let error = transport |
| 1199 | .request("fixture/overflow", json!({}), Duration::from_secs(2)) |
| 1200 | .await |
| 1201 | .unwrap_err(); |
| 1202 | assert!(error.to_string().contains("channel closed"), "{error:#}"); |
| 1203 | assert!(transport.pending.lock().await.is_empty()); |
| 1204 | assert_fixture_exited(root.path()).await; |
| 1205 | } |
| 1206 | |
| 1207 | #[cfg(unix)] |
| 1208 | #[tokio::test] |
| 1209 | async fn language_server_does_not_inherit_parent_secret_env() { |
| 1210 | use codewhale_runtime::test_support::{EnvVarGuard, lock_test_env}; |
| 1211 | let _env_lock = lock_test_env(); |
| 1212 | let _secret = EnvVarGuard::set("CODEWHALE_TEST_LSP_SECRET", "lsp-secret-value"); |
| 1213 | let root = tempfile::tempdir().unwrap(); |
| 1214 | let report = root.path().join("env"); |
| 1215 | // A fake server that records what it can see and exits before |
| 1216 | // answering `initialize`. |
| 1217 | let script = format!( |
| 1218 | "printf 'secret=%s\\n' \"${{CODEWHALE_TEST_LSP_SECRET-unset}}\" > '{}'; \ |
| 1219 | [ -n \"$PATH\" ] && printf 'path-ok\\n' >> '{}'", |
| 1220 | report.display(), |
| 1221 | report.display() |
| 1222 | ); |
| 1223 | let result = StdioLspTransport::spawn_with_timeout( |
| 1224 | "/bin/sh", |
| 1225 | &["-c".into(), script], |
| 1226 | "rust", |
| 1227 | root.path().to_path_buf(), |
| 1228 | Duration::from_secs(3), |
| 1229 | ) |
| 1230 | .await; |
| 1231 | assert!(result.is_err(), "fake server exits without initializing"); |
| 1232 | let seen = std::fs::read_to_string(&report).expect("fake server ran"); |
| 1233 | assert!(seen.contains("secret=unset"), "{seen}"); |
| 1234 | assert!(!seen.contains("lsp-secret-value"), "{seen}"); |
| 1235 | assert!(seen.contains("path-ok"), "{seen}"); |
| 1236 | } |
| 1237 | |
| 1238 | #[tokio::test] |
| 1239 | async fn semantic_request_holds_document_gate_until_reply_before_diagnostics() { |
| 1240 | timeout(Duration::from_secs(2), async { |
| 1241 | let (transport, mut outbound, diag) = diagnostic_fixture(); |
| 1242 | let transport = Arc::new(transport); |
| 1243 | let semantic = { |
| 1244 | let transport = transport.clone(); |
| 1245 | tokio::spawn(async move { |
| 1246 | transport |
| 1247 | .request_for_document( |
| 1248 | &fixture_path("semantic.rs"), |
| 1249 | "before", |
| 1250 | "textDocument/definition", |
| 1251 | json!({}), |
| 1252 | Duration::from_secs(1), |
| 1253 | ) |
| 1254 | .await |
| 1255 | }) |
| 1256 | }; |
| 1257 | let open = next_document(&mut outbound).await; |
| 1258 | assert_eq!(open["method"], "textDocument/didOpen"); |
| 1259 | let request = next_document(&mut outbound).await; |
| 1260 | assert_eq!(request["method"], "textDocument/definition"); |
| 1261 | let diagnostics = { |
| 1262 | let transport = transport.clone(); |
| 1263 | tokio::spawn(async move { |
| 1264 | transport |
| 1265 | .diagnostics_for( |
| 1266 | &fixture_path("semantic.rs"), |
| 1267 | "after", |
| 1268 | Duration::from_secs(1), |
| 1269 | ) |
| 1270 | .await |
| 1271 | }) |
| 1272 | }; |
| 1273 | assert!( |
| 1274 | timeout(Duration::from_millis(20), outbound.recv()) |
| 1275 | .await |
| 1276 | .is_err() |
| 1277 | ); |
| 1278 | transport |
| 1279 | .pending |
| 1280 | .lock() |
| 1281 | .await |
| 1282 | .remove(&request["id"].as_i64().unwrap()) |
| 1283 | .unwrap() |
| 1284 | .send(json!({"result":[]})) |
| 1285 | .unwrap(); |
| 1286 | assert_eq!(semantic.await.unwrap().unwrap().document_version, Some(1)); |
| 1287 | let change = next_document(&mut outbound).await; |
| 1288 | assert_eq!(change["params"]["textDocument"]["version"], 2); |
| 1289 | diag.send((fixture_path("semantic.rs"), Some(2), vec![])) |
| 1290 | .await |
| 1291 | .unwrap(); |
| 1292 | assert_eq!( |
| 1293 | diagnostics.await.unwrap().unwrap().document_version, |
| 1294 | Some(2) |
| 1295 | ); |
| 1296 | }) |
| 1297 | .await |
| 1298 | .unwrap(); |
| 1299 | } |
| 1300 | |
| 1301 | #[tokio::test] |
| 1302 | async fn semantic_deadline_includes_gate_wait_and_cleans_pending_request() { |
| 1303 | let (transport, _outbound, _diag) = diagnostic_fixture(); |
| 1304 | let gate = transport.diagnostics_gate.lock().await; |
| 1305 | let result = timeout( |
| 1306 | Duration::from_millis(250), |
| 1307 | transport.request_for_document( |
| 1308 | &fixture_path("a.rs"), |
| 1309 | "a", |
| 1310 | "textDocument/definition", |
| 1311 | json!({}), |
| 1312 | Duration::from_millis(20), |
| 1313 | ), |
| 1314 | ) |
| 1315 | .await |
| 1316 | .unwrap(); |
| 1317 | assert!(result.unwrap_err().to_string().contains("timed out")); |
| 1318 | drop(gate); |
| 1319 | assert!(transport.pending.lock().await.is_empty()); |
| 1320 | let result = transport |
| 1321 | .request_for_document( |
| 1322 | &fixture_path("a.rs"), |
| 1323 | "a", |
| 1324 | "textDocument/definition", |
| 1325 | json!({}), |
| 1326 | Duration::from_millis(20), |
| 1327 | ) |
| 1328 | .await; |
| 1329 | assert!(result.unwrap_err().to_string().contains("timed out")); |
| 1330 | assert!(transport.pending.lock().await.is_empty()); |
| 1331 | } |
| 1332 | |
| 1333 | #[test] |
| 1334 | fn semantic_file_uris_decode_spaces_and_reject_authority_and_query() { |
| 1335 | let path = &fixture_path("a b#🐋.rs"); |
| 1336 | assert_eq!( |
| 1337 | path_from_uri(&uri_from_path(path)).as_deref(), |
| 1338 | Some(path.as_path()) |
| 1339 | ); |
| 1340 | for uri in [ |
| 1341 | "https://example.test/a.rs", |
| 1342 | "file://remote/tmp/a.rs", |
| 1343 | "file:///tmp/a.rs?q=1", |
| 1344 | "file:///tmp/a.rs#fragment", |
| 1345 | ] { |
| 1346 | assert!(path_from_uri(uri).is_none(), "{uri}"); |
| 1347 | } |
| 1348 | } |
| 1349 | |
| 1350 | #[tokio::test] |
| 1351 | async fn stdio_request_deadline_includes_full_outbound_queue() { |
| 1352 | let (transport, _outbound, _diag) = diagnostic_fixture(); |
| 1353 | for _ in 0..8 { |
| 1354 | transport.tx_outbound.try_send(vec![]).unwrap(); |
| 1355 | } |
| 1356 | let error = timeout( |
| 1357 | Duration::from_millis(250), |
| 1358 | transport.request("fixture/blocked", json!({}), Duration::from_millis(20)), |
| 1359 | ) |
| 1360 | .await |
| 1361 | .unwrap() |
| 1362 | .unwrap_err(); |
| 1363 | assert!(error.to_string().contains("timed out")); |
| 1364 | assert!(transport.pending.lock().await.is_empty()); |
| 1365 | } |
| 1366 | |
| 1367 | #[tokio::test] |
| 1368 | async fn stdio_reader_bounds_and_malformed_frames_close_pending_replies() { |
| 1369 | let frames = [ |
| 1370 | vec![b'x'; MAX_LSP_HEADER_BYTES + 1], |
| 1371 | format!("Content-Length: {}\r\n\r\n", MAX_LSP_FRAME_BYTES + 1).into_bytes(), |
| 1372 | b"Content-Length: 999999999999999999999999999999999\r\n\r\n".to_vec(), |
| 1373 | b"Content-Length: 1\r\nContent-Length: 1\r\n\r\nx".to_vec(), |
| 1374 | b"Missing-Length: 1\r\n\r\nx".to_vec(), |
| 1375 | b"Content-Length: 1\r\n\r\n{".to_vec(), |
| 1376 | ]; |
| 1377 | for frame in frames { |
| 1378 | let (mut producer, reader) = tokio::io::duplex(MAX_LSP_HEADER_BYTES * 2); |
| 1379 | let (tx, rx) = mpsc::channel(8); |
| 1380 | let (diag, _diagnostics) = mpsc::channel(8); |
| 1381 | let (outbound, _outbound_rx) = mpsc::channel(8); |
| 1382 | let pending = Arc::new(AsyncMutex::new(HashMap::new())); |
| 1383 | let (reply, receiver) = oneshot::channel(); |
| 1384 | pending.lock().await.insert(1, reply); |
| 1385 | let read_task = tokio::spawn(reader_task(reader, tx)); |
| 1386 | let dispatch = tokio::spawn(dispatcher_task(rx, diag, outbound, pending.clone())); |
| 1387 | producer.write_all(&frame).await.unwrap(); |
| 1388 | assert!( |
| 1389 | timeout(Duration::from_secs(1), receiver) |
| 1390 | .await |
| 1391 | .unwrap() |
| 1392 | .is_err() |
| 1393 | ); |
| 1394 | read_task.await.unwrap(); |
| 1395 | dispatch.await.unwrap(); |
| 1396 | assert!(pending.lock().await.is_empty()); |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | #[tokio::test] |
| 1401 | async fn stdio_reader_preserves_fragmented_and_coalesced_valid_frames() { |
| 1402 | let (mut producer, reader) = tokio::io::duplex(128); |
| 1403 | let (tx, mut rx) = mpsc::channel(8); |
| 1404 | let task = tokio::spawn(reader_task(reader, tx)); |
| 1405 | producer.write_all(b"content-length: 2\r\n").await.unwrap(); |
| 1406 | producer |
| 1407 | .write_all(b"\r\n{}Content-Length: 2\r\n\r\n[]") |
| 1408 | .await |
| 1409 | .unwrap(); |
| 1410 | assert_eq!( |
| 1411 | timeout(Duration::from_secs(1), rx.recv()).await.unwrap(), |
| 1412 | Some(json!({})) |
| 1413 | ); |
| 1414 | assert_eq!( |
| 1415 | timeout(Duration::from_secs(1), rx.recv()).await.unwrap(), |
| 1416 | Some(json!([])) |
| 1417 | ); |
| 1418 | drop(producer); |
| 1419 | task.await.unwrap(); |
| 1420 | assert!(rx.recv().await.is_none()); |
| 1421 | } |
| 1422 | |
| 1423 | #[test] |
| 1424 | fn parse_publish_diagnostics_rejects_overflowing_positions() { |
| 1425 | for (line, character) in [ |
| 1426 | (u64::from(u32::MAX), 0_u64), |
| 1427 | (0_u64, u64::from(u32::MAX)), |
| 1428 | (u64::from(u32::MAX) + 1, 0_u64), |
| 1429 | (0_u64, u64::from(u32::MAX) + 1), |
| 1430 | ] { |
| 1431 | let payload = json!({ |
| 1432 | "jsonrpc": "2.0", |
| 1433 | "method": "textDocument/publishDiagnostics", |
| 1434 | "params": { |
| 1435 | "uri": uri_from_path(&fixture_path("overflow.rs")), |
| 1436 | "diagnostics": [{ |
| 1437 | "range": { |
| 1438 | "start": { "line": line, "character": character }, |
| 1439 | "end": { "line": line, "character": character } |
| 1440 | }, |
| 1441 | "severity": 1, |
| 1442 | "message": "bad position" |
| 1443 | }] |
| 1444 | } |
| 1445 | }); |
| 1446 | assert!( |
| 1447 | parse_publish_diagnostics(&payload).is_none(), |
| 1448 | "position ({line}, {character}) must not panic or wrap" |
| 1449 | ); |
| 1450 | } |
| 1451 | } |
| 1452 | |
| 1453 | #[cfg(unix)] |
| 1454 | #[tokio::test] |
| 1455 | async fn stdio_transport_shutdown_kills_grandchild_processes() { |
| 1456 | let root = tempfile::tempdir().unwrap(); |
| 1457 | let pid_file = root.path().join("grandchild.pid"); |
| 1458 | let script = [ |
| 1459 | "import json, subprocess, sys", |
| 1460 | "p = subprocess.Popen(['sleep', '60'])", |
| 1461 | &format!("open({:?}, 'w').write(str(p.pid))", pid_file.to_string_lossy()), |
| 1462 | "raw = b''", |
| 1463 | "while b'\\r\\n\\r\\n' not in raw:", |
| 1464 | " raw += sys.stdin.buffer.read(1)", |
| 1465 | "hdr, rest = raw.split(b'\\r\\n\\r\\n', 1)", |
| 1466 | "n = int([l.split(b':', 1)[1] for l in hdr.split(b'\\r\\n') if l.lower().startswith(b'content-length')][0])", |
| 1467 | "body = rest + sys.stdin.buffer.read(n - len(rest))", |
| 1468 | "req = json.loads(body)", |
| 1469 | "rep = json.dumps({'jsonrpc':'2.0','id':req['id'],'result':{'capabilities':{}}}).encode()", |
| 1470 | "sys.stdout.buffer.write(f'Content-Length: {len(rep)}\\r\\n\\r\\n'.encode() + rep)", |
| 1471 | "sys.stdout.buffer.flush()", |
| 1472 | "sys.stdin.buffer.read()", |
| 1473 | ] |
| 1474 | .join("\n"); |
| 1475 | let args = vec!["-u".to_string(), "-c".to_string(), script]; |
| 1476 | let transport = |
| 1477 | StdioLspTransport::spawn("python3", &args, "python", root.path().to_path_buf()) |
| 1478 | .await |
| 1479 | .expect("spawn fixture lsp"); |
| 1480 | let grandchild = |
| 1481 | codewhale_runtime::process_tree::read_pid_file(&pid_file, Duration::from_secs(5)); |
| 1482 | transport.shutdown().await; |
| 1483 | assert!( |
| 1484 | codewhale_runtime::process_tree::wait_for_pid_exit(grandchild, Duration::from_secs(5),), |
| 1485 | "grandchild pid {grandchild} must exit when LSP transport shuts down" |
| 1486 | ); |
| 1487 | } |
| 1488 | } |
| 1489 |