Files
hx/crates/hx-lens/src/manager.rs
T
hermes 99dc90fd3b
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
M6: native MCP client, lazy index, mcp-serve (closes #42-#51)
2026-09-30 15:51:25 +00:00

471 lines
17 KiB
Rust

//! 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::sync::atomic::Ordering;
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<String>,
pub command: Vec<String>,
/// files/dirs whose nearest ancestor becomes the root
pub roots: Vec<String>,
#[serde(default)]
pub init_options: Value,
}
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,
}
}
pub fn default_servers() -> Vec<ServerCfg> {
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<Client>,
/// uri -> version
open: HashMap<String, i64>,
last_used: Instant,
}
#[derive(Default)]
struct Slot {
server: Option<Server>,
failures: u32,
}
pub struct Manager {
pub servers: Vec<ServerCfg>,
pub workspace: PathBuf,
slots: Mutex<HashMap<(String, PathBuf), Slot>>,
pub idle: Duration,
/// ledger of degraded behaviour (missing servers, crashes) for status output
pub notes: std::sync::Mutex<Vec<String>>,
}
pub const MAX_FAILURES: u32 = 2;
impl Manager {
pub fn new(workspace: PathBuf, servers: Vec<ServerCfg>) -> 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))
}
/// Get or start the server for `file`. None = unsupported, not installed, or breaker open.
async fn client(&self, file: &Path) -> Option<(Arc<Client>, (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.alive.load(Ordering::SeqCst)
{
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<Client>, 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. Waits up to `timeout` for a report matching this version
/// (or any fresh report when the server doesn't send versions), then a short settle period.
/// None = no server for this file.
pub async fn diagnostics(
&self,
file: &Path,
timeout: Duration,
) -> Option<Result<Vec<Diag>, String>> {
let before = self.client(file).await.map(|(c, ..)| c)?;
let is_rust = self
.server_for(file)
.is_some_and(|c| c.id == "rust-analyzer");
let deadline = Instant::now() + timeout;
// If a check is already running from an earlier turn/startup, wait for it to finish first:
if is_rust {
while before.checks_active.load(Ordering::SeqCst) {
if Instant::now() >= deadline
|| tokio::time::timeout(
Duration::from_millis(500),
before.diag_notify.notified(),
)
.await
.is_err()
{
break;
}
}
}
let u = uri(file);
let stale = before.diagnostics(&u).await;
let (cl, v) = self.sync(file).await?;
// count checks from after our save: a check still ending from an earlier save carries stale results
let checks_before = cl.checks_done.load(Ordering::SeqCst)
+ i64::from(cl.checks_active.load(Ordering::SeqCst));
let fresh = |d: &Option<(Option<i64>, Vec<Diag>)>| match d {
Some((Some(rv), _)) => *rv >= v,
Some((None, _)) => d != &stale || v == 1,
None => false,
};
// For rust-analyzer, didSave triggers a flycheck. Wait until either:
// - A flycheck completes (checks_done > checks_before and !checks_active), OR
// - 15s passes without flycheck ever starting (checkOnSave disabled; queued checks start later under load).
let settle_for = Duration::from_millis(300);
// rust-analyzer publishes flycheck results after progress `end`: once the check ends,
// wait (max 3s) for a publish that arrives after it.
let mut after_end: Option<(i64, Instant)> = None;
let check_wait_deadline = Instant::now() + Duration::from_secs(15);
loop {
let n = cl.diag_notify.notified();
let cur = cl.diagnostics(&u).await;
let check_finished = cl.checks_done.load(Ordering::SeqCst) > checks_before
&& !cl.checks_active.load(Ordering::SeqCst);
let check_never_started = cl.checks_done.load(Ordering::SeqCst) == checks_before
&& !cl.checks_active.load(Ordering::SeqCst)
&& Instant::now() >= check_wait_deadline;
if check_finished && after_end.is_none() {
after_end = Some((cl.diag_seq.load(Ordering::SeqCst), Instant::now()));
}
let published = after_end.is_some_and(|(seq, t)| {
cl.diag_seq.load(Ordering::SeqCst) > seq || t.elapsed() >= Duration::from_secs(10)
});
let checked = !is_rust || (check_finished && published) || check_never_started;
if fresh(&cur) && checked && cl.busy.load(Ordering::SeqCst) <= 0 {
loop {
let settle = cl.diag_notify.notified();
let left = deadline.saturating_duration_since(Instant::now());
if tokio::time::timeout(settle_for.min(left), settle)
.await
.is_err()
{
break;
}
if Instant::now() >= deadline {
break;
}
}
if cl.busy.load(Ordering::SeqCst) <= 0 {
return Some(Ok(cl
.diagnostics(&u)
.await
.map(|x| x.1)
.unwrap_or_default()));
}
}
if !cl.alive.load(Ordering::SeqCst) {
return Some(Err("language server exited".into()));
}
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
// best effort: return whatever we have
return Some(match cur {
Some((_, d)) if fresh(&Some((None, d.clone()))) || !d.is_empty() => Ok(d),
_ => Err(format!("no diagnostics within {}s", timeout.as_secs())),
});
}
let _ = tokio::time::timeout(left.min(Duration::from_millis(500)), n).await;
}
}
/// Generic request at a position (after syncing the file).
pub async fn request(
&self,
file: &Path,
method: &str,
mut params: Value,
) -> Result<Value, String> {
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<Self>, files: Vec<PathBuf>) {
for f in files {
let m = self.clone();
tokio::spawn(async move {
let _ = m.client(&f).await;
});
}
}
pub async fn status(&self) -> Vec<String> {
let slots = self.slots.lock().await;
let mut v: Vec<String> = slots
.iter()
.map(|((id, root), s)| {
let st = match &s.server {
Some(x) if x.client.alive.load(Ordering::SeqCst) => {
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"));
}
}