//! LSP manager: server table, one server per (language, root), lazy spawn, idle eviction, //! document sync, diagnostics with timeout, restart-once circuit breaker. use crate::lsp::{Client, Diag, uri}; use serde_json::{Value, json}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::Mutex; #[derive(Debug, Clone, PartialEq, serde::Deserialize)] pub struct ServerCfg { pub id: String, /// language id sent in didOpen pub language: String, pub extensions: Vec, pub command: Vec, /// files/dirs whose nearest ancestor becomes the root pub roots: Vec, #[serde(default)] pub init_options: Value, /// Install command offered when `command[0]` is missing (runs only after the user agrees). #[serde(default)] pub install: Vec, } fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) -> ServerCfg { let v = |x: &[&str]| x.iter().map(|s| s.to_string()).collect(); ServerCfg { id: id.into(), language: language.into(), extensions: v(ext), command: v(cmd), roots: v(roots), init_options: Value::Null, install: install_for(id), } } /// Built-in install recipes. The first element is the installer, which must be on PATH to offer it. fn install_for(id: &str) -> Vec { let c: &[&str] = match id { "rust-analyzer" => &["rustup", "component", "add", "rust-analyzer"], "typescript" => &[ "npm", "install", "-g", "typescript-language-server", "typescript", ], "pyright" => &["npm", "install", "-g", "pyright"], "gopls" => &["go", "install", "golang.org/x/tools/gopls@latest"], _ => &[], // clangd: system package manager, too distro-specific to guess }; c.iter().map(|s| s.to_string()).collect() } /// Why a file has no language server, and how to get one. #[derive(Debug, PartialEq)] pub enum Missing { /// no server configured for this file type Unsupported, /// server known, binary missing; `install` empty or installer not on PATH = manual install NotInstalled { id: String, bin: String, install: Vec, }, } /// Run an install command with a timeout; returns combined output tail on failure. pub async fn install(cmd: &[String]) -> Result<(), String> { let Some((bin, args)) = cmd.split_first() else { return Err("no install command".into()); }; let o = tokio::time::timeout( Duration::from_secs(600), tokio::process::Command::new(bin) .args(args) .stdin(std::process::Stdio::null()) .kill_on_drop(true) .output(), ) .await .map_err(|_| "install timed out after 600s".to_string())? .map_err(|e| e.to_string())?; if o.status.success() { return Ok(()); } let out = String::from_utf8_lossy(&o.stderr).to_string() + &String::from_utf8_lossy(&o.stdout); let lines: Vec<&str> = out.trim().lines().collect(); Err(lines[lines.len().saturating_sub(10)..].join("\n")) } pub fn default_servers() -> Vec { vec![ cfg( "rust-analyzer", "rust", &["rs"], &["rust-analyzer"], &["Cargo.toml"], ), cfg( "typescript", "typescript", &["ts", "tsx", "js", "jsx", "mjs", "cjs"], &["typescript-language-server", "--stdio"], &["tsconfig.json", "jsconfig.json", "package.json"], ), cfg( "pyright", "python", &["py", "pyi"], &["pyright-langserver", "--stdio"], &[ "pyproject.toml", "setup.py", "requirements.txt", "pyrightconfig.json", ], ), cfg("gopls", "go", &["go"], &["gopls"], &["go.mod"]), cfg( "clangd", "cpp", &["c", "h", "cc", "cpp", "hpp", "cxx"], &["clangd"], &["compile_commands.json", "CMakeLists.txt", ".clangd"], ), ] } /// JS files report language `javascript` etc. fn language_for(c: &ServerCfg, p: &Path) -> String { match ( c.id.as_str(), p.extension().and_then(|e| e.to_str()).unwrap_or_default(), ) { ("typescript", "tsx") => "typescriptreact".into(), ("typescript", "js" | "mjs" | "cjs") => "javascript".into(), ("typescript", "jsx") => "javascriptreact".into(), ("clangd", "c" | "h") => "c".into(), _ => c.language.clone(), } } pub fn find_root(file: &Path, markers: &[String], stop: &Path) -> PathBuf { let mut best = None; for d in file.ancestors().skip(1) { if markers.iter().any(|m| d.join(m).exists()) { // rust/ts workspaces: keep climbing to the outermost marker inside `stop` best = Some(d.to_path_buf()); } if d == stop { break; } } best.unwrap_or_else(|| stop.to_path_buf()) } pub fn which(bin: &str) -> bool { if bin.contains('/') { return Path::new(bin).is_file(); } std::env::var_os("PATH") .is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file())) } struct Server { client: Arc, /// uri -> version open: HashMap, last_used: Instant, } #[derive(Default)] struct Slot { server: Option, failures: u32, } pub struct Manager { pub servers: Vec, pub workspace: PathBuf, slots: Mutex>, pub idle: Duration, /// ledger of degraded behaviour (missing servers, crashes) for status output pub notes: std::sync::Mutex>, } pub const MAX_FAILURES: u32 = 2; impl Manager { pub fn new(workspace: PathBuf, servers: Vec) -> Self { Self { servers, workspace, slots: Default::default(), idle: Duration::from_secs(600), notes: Default::default(), } } fn note(&self, s: String) { let mut n = self.notes.lock().unwrap_or_else(|e| e.into_inner()); if !n.contains(&s) { n.push(s); } } pub fn server_for(&self, p: &Path) -> Option<&ServerCfg> { let ext = p.extension()?.to_str()?; self.servers .iter() .find(|s| s.extensions.iter().any(|e| e == ext)) } /// None when a server for `file` is installed; otherwise why not. pub fn missing(&self, file: &Path) -> Option { let Some(c) = self.server_for(file) else { return Some(Missing::Unsupported); }; if which(&c.command[0]) { return None; } Some(Missing::NotInstalled { id: c.id.clone(), bin: c.command[0].clone(), install: if c.install.first().is_some_and(|b| which(b)) { c.install.clone() } else { vec![] }, }) } /// Get or start the server for `file`. None = unsupported, not installed, or breaker open. async fn client(&self, file: &Path) -> Option<(Arc, (String, PathBuf), ServerCfg)> { let c = self.server_for(file)?.clone(); if !which(&c.command[0]) { self.note(format!("{}: `{}` not installed", c.id, c.command[0])); return None; } let root = find_root(file, &c.roots, &self.workspace); let key = (c.id.clone(), root.clone()); let mut slots = self.slots.lock().await; // evict idle servers let idle: Vec<_> = slots .iter() .filter(|(k, s)| { **k != key && s.server .as_ref() .is_some_and(|x| x.last_used.elapsed() > self.idle) }) .map(|(k, _)| k.clone()) .collect(); for k in idle { if let Some(s) = slots.get_mut(&k).and_then(|s| s.server.take()) { tokio::spawn(async move { s.client.shutdown().await }); } } let slot = slots.entry(key.clone()).or_default(); if let Some(s) = &slot.server && !s.client.is_alive() { slot.server = None; slot.failures += 1; self.note(format!("{} crashed in {}", c.id, root.display())); } if slot.server.is_none() { if slot.failures >= MAX_FAILURES { return None; } match Client::start(&c.command, &root, c.init_options.clone()).await { Ok(cl) => { slot.server = Some(Server { client: cl, open: HashMap::new(), last_used: Instant::now(), }) } Err(e) => { slot.failures += 1; let e = e.to_string(); // rustup proxy without the component installed exits immediately let hint = if c.id == "rust-analyzer" { " (try `rustup component add rust-analyzer`)" } else { "" }; self.note(format!( "{} failed to start: {}{hint}", c.id, e.lines().next().unwrap_or_default() )); return None; } } } let s = slot.server.as_mut()?; s.last_used = Instant::now(); Some((s.client.clone(), key, c)) } /// Open or update the document from disk. Returns the version sent. async fn sync(&self, file: &Path) -> Option<(Arc, i64)> { let (cl, key, c) = self.client(file).await?; let text = tokio::fs::read_to_string(file).await.ok()?; let u = uri(file); let mut slots = self.slots.lock().await; let s = slots.get_mut(&key)?.server.as_mut()?; let v = match s.open.get(&u) { None => { let _ = cl .notify("textDocument/didOpen", json!({"textDocument": {"uri": u, "languageId": language_for(&c, file), "version": 1, "text": text}})) .await; let _ = cl .notify("textDocument/didSave", json!({"textDocument": {"uri": u}})) .await; 1 } Some(v) => { let v = v + 1; let _ = cl .notify("textDocument/didChange", json!({"textDocument": {"uri": u, "version": v}, "contentChanges": [{"text": text}]})) .await; let _ = cl .notify("textDocument/didSave", json!({"textDocument": {"uri": u}})) .await; v } }; s.open.insert(u, v); Some((cl, v)) } /// Diagnostics for `file` after syncing from disk, once the server has settled (see /// `Client::diagnostics_after`). None = no server for this file. pub async fn diagnostics( &self, file: &Path, timeout: Duration, ) -> Option, String>> { let (cl, ..) = self.client(file).await?; let expect_check = self .server_for(file) .is_some_and(|c| c.id == "rust-analyzer"); cl.diagnostics_after(&uri(file), expect_check, timeout, async { self.sync(file).await.map(|(_, v)| v) }) .await } /// Generic request at a position (after syncing the file). pub async fn request( &self, file: &Path, method: &str, mut params: Value, ) -> Result { let (cl, _) = self .sync(file) .await .ok_or_else(|| format!("no language server for {}", file.display()))?; params["textDocument"] = json!({"uri": uri(file)}); // -32801 ContentModified / -32802 ServerCancelled: server still indexing; retry briefly for delay in [200u64, 500, 1000, 2000, 4000] { match cl .request(method, params.clone(), Duration::from_secs(30)) .await { Err(e) if e.contains("-32801") || e.contains("-32802") => { tokio::time::sleep(Duration::from_millis(delay)).await } r => return r, } } cl.request(method, params, Duration::from_secs(30)).await } /// Start servers for the given files in the background (session start). pub async fn warm(self: &Arc, files: Vec) { for f in files { let m = self.clone(); tokio::spawn(async move { let _ = m.client(&f).await; }); } } pub async fn status(&self) -> Vec { let slots = self.slots.lock().await; let mut v: Vec = slots .iter() .map(|((id, root), s)| { let st = match &s.server { Some(x) if x.client.is_alive() => { format!("running, {} open", x.open.len()) } Some(_) => "dead".into(), None if s.failures >= MAX_FAILURES => "breaker open".into(), None => "stopped".into(), }; format!("{id} @ {}: {st}", root.display()) }) .collect(); v.extend( self.notes .lock() .unwrap_or_else(|e| e.into_inner()) .iter() .cloned(), ); v.sort(); v } pub async fn shutdown(&self) { for (_, s) in self.slots.lock().await.drain() { if let Some(s) = s.server { s.client.shutdown().await; } } } } #[cfg(test)] mod tests { use super::*; #[test] fn detection_and_roots() { let d = tempfile::tempdir().unwrap(); let ws = d.path(); std::fs::create_dir_all(ws.join("crates/a/src")).unwrap(); std::fs::write(ws.join("Cargo.toml"), "").unwrap(); std::fs::write(ws.join("crates/a/Cargo.toml"), "").unwrap(); let m = Manager::new(ws.into(), default_servers()); let f = ws.join("crates/a/src/lib.rs"); let c = m.server_for(&f).unwrap(); assert_eq!(c.id, "rust-analyzer"); // outermost Cargo.toml wins (workspace root) assert_eq!(find_root(&f, &c.roots, ws), ws); assert_eq!(m.server_for(Path::new("x.tsx")).unwrap().id, "typescript"); assert_eq!( language_for( m.server_for(Path::new("x.tsx")).unwrap(), Path::new("x.tsx") ), "typescriptreact" ); assert_eq!(m.server_for(Path::new("x.py")).unwrap().id, "pyright"); assert!(m.server_for(Path::new("x.md")).is_none()); // no marker: workspace root assert_eq!( find_root(&ws.join("x/y.py"), &["pyproject.toml".into()], ws), ws ); assert!(which("sh") && !which("definitely-not-a-binary-hx")); } /// Fake rust-analyzer: the first (empty) publish after a change must not be taken as the result. #[tokio::test(flavor = "multi_thread")] async fn waits_for_flycheck() { if !which("python3") { return; } let d = tempfile::tempdir().unwrap(); let ws = d.path().to_path_buf(); std::fs::write(ws.join("Cargo.toml"), "").unwrap(); let f = ws.join("lib.rs"); let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fake_lsp.py"); let m = Manager::new( ws.clone(), vec![ServerCfg { id: "rust-analyzer".into(), language: "rust".into(), extensions: vec!["rs".into()], command: vec!["python3".into(), fake.into()], roots: vec!["Cargo.toml".into()], init_options: Value::Null, install: vec![], }], ); let t = Duration::from_secs(20); std::fs::write(&f, "let x = oops;\n").unwrap(); let r = m.diagnostics(&f, t).await.unwrap().unwrap(); assert_eq!(r.len(), 1, "{r:?}"); assert_eq!(r[0].message, "bad"); std::fs::write(&f, "let x = 1;\n").unwrap(); assert!(m.diagnostics(&f, t).await.unwrap().unwrap().is_empty()); std::fs::write(&f, "let x = oops;\n").unwrap(); assert_eq!(m.diagnostics(&f, t).await.unwrap().unwrap().len(), 1); m.shutdown().await; } }