Files
hx/crates/hx-lens/src/manager.rs
T
johannesandClaude Sonnet 5.5 a94632ea3d chore: delete code comments, add ratchet lint and ADRs
Classify every comment as tautology, stale, excuse or decision record.
Tautology/stale/excuse comments are deleted (excuses filed as issues
#196-#236), decisions moved to docs/adr/0001-0034.

- scripts/lint-comments.sh + .comment-baseline: per-file comment count
  may only go down; wired into tests/all.sh
- .claude/skills/delete-comment: repeatable audit workflow
- cargo fmt applied to touched crates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:37:32 +01:00

472 lines
15 KiB
Rust

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,
pub language: String,
pub extensions: Vec<String>,
pub command: Vec<String>,
pub roots: Vec<String>,
#[serde(default)]
pub init_options: Value,
#[serde(default)]
pub install: Vec<String>,
}
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),
}
}
fn install_for(id: &str) -> Vec<String> {
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"],
_ => &[],
};
c.iter().map(|s| s.to_string()).collect()
}
#[derive(Debug, PartialEq)]
pub enum Missing {
Unsupported,
NotInstalled {
id: String,
bin: String,
install: Vec<String>,
},
}
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<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"],
),
]
}
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()) {
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>,
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,
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))
}
pub fn missing(&self, file: &Path) -> Option<Missing> {
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![]
},
})
}
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;
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();
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))
}
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))
}
pub async fn diagnostics(
&self,
file: &Path,
timeout: Duration,
) -> Option<Result<Vec<Diag>, 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
}
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)});
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
}
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.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");
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());
assert_eq!(
find_root(&ws.join("x/y.py"), &["pyproject.toml".into()], ws),
ws
);
assert!(which("sh") && !which("definitely-not-a-binary-hx"));
}
#[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;
}
}