Files
hx/crates/hx-lens/src/lsp.rs
T
johannes 70d8bc2aaf
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s
Move flycheck wait into lsp::Client
Client::diagnostics_after now owns the rust-analyzer on-save check protocol
(flycheck begin/end, publish after end, busy, settle). The counters are
private, and Manager::diagnostics only picks the server and passes the sync
step. Reader state is one Arc<Shared> instead of eight cloned Arcs.

Adds a fake LSP server and a manager test that fails if the first empty
publish after a change is taken as the result.
2026-10-01 23:32:14 +02:00

462 lines
17 KiB
Rust

//! Minimal LSP JSON-RPC client over stdio.
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::{Mutex, Notify, mpsc, oneshot};
#[derive(Debug, Clone, PartialEq)]
pub struct Diag {
pub line: u32,
pub col: u32,
/// 1 error, 2 warning, 3 info, 4 hint
pub severity: u8,
pub message: String,
pub source: String,
pub code: String,
}
/// uri -> (version reported, diagnostics)
type DiagMap = HashMap<String, (Option<i64>, Vec<Diag>)>;
/// State the reader task updates and `Client` reads.
struct Shared {
pending: Mutex<HashMap<i64, oneshot::Sender<Result<Value, String>>>>,
diags: Mutex<DiagMap>,
/// woken on every diagnostics publish, progress event, status change and server exit
notify: Notify,
alive: AtomicBool,
/// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle
busy: AtomicI64,
/// completed on-save checks (rust-analyzer flycheck)
checks_done: AtomicI64,
checks_active: AtomicBool,
/// incremented on every `textDocument/publishDiagnostics`
diag_seq: AtomicI64,
}
pub struct Client {
stdin: Mutex<ChildStdin>,
child: Mutex<Child>,
next: AtomicI64,
shared: Arc<Shared>,
}
pub fn uri(p: &Path) -> String {
let s = p.to_string_lossy();
let enc: String = s
.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'-' | b'_' | b'.' | b'~' => {
(b as char).to_string()
}
_ => format!("%{b:02X}"),
})
.collect();
format!("file://{enc}")
}
pub fn path_of(uri: &str) -> PathBuf {
let s = uri.strip_prefix("file://").unwrap_or(uri);
let b = s.as_bytes();
let mut out = vec![];
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& i + 2 < b.len()
&& let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16)
{
out.push(v);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
PathBuf::from(String::from_utf8_lossy(&out).into_owned())
}
fn parse_diag(d: &Value) -> Diag {
Diag {
line: d["range"]["start"]["line"].as_u64().unwrap_or(0) as u32,
col: d["range"]["start"]["character"].as_u64().unwrap_or(0) as u32,
severity: d["severity"].as_u64().unwrap_or(1) as u8,
message: d["message"].as_str().unwrap_or_default().to_string(),
source: d["source"].as_str().unwrap_or_default().to_string(),
code: match &d["code"] {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
_ => String::new(),
},
}
}
async fn write_msg(w: &mut ChildStdin, v: &Value) -> std::io::Result<()> {
let body = serde_json::to_vec(v)?;
w.write_all(format!("Content-Length: {}\r\n\r\n", body.len()).as_bytes())
.await?;
w.write_all(&body).await?;
w.flush().await
}
impl Shared {
async fn read_loop(
&self,
stdout: tokio::process::ChildStdout,
stdin_tx: mpsc::UnboundedSender<Value>,
) {
let mut r = BufReader::new(stdout);
let mut quiescent_busy = false;
loop {
let mut len = None;
loop {
let mut h = String::new();
if r.read_line(&mut h).await.unwrap_or(0) == 0 {
self.alive.store(false, Ordering::SeqCst);
for (_, tx) in self.pending.lock().await.drain() {
let _ = tx.send(Err("server exited".into()));
}
self.notify.notify_waiters();
return;
}
let h = h.trim();
if h.is_empty() {
break;
}
if let Some(v) = h.strip_prefix("Content-Length:") {
len = v.trim().parse::<usize>().ok();
}
}
let Some(len) = len else { continue };
let mut buf = vec![0; len];
if r.read_exact(&mut buf).await.is_err() {
continue;
}
let Ok(m) = serde_json::from_slice::<Value>(&buf) else {
continue;
};
self.handle(m, &mut quiescent_busy, &stdin_tx).await;
}
}
async fn handle(
&self,
m: Value,
quiescent_busy: &mut bool,
stdin_tx: &mpsc::UnboundedSender<Value>,
) {
match (m.get("id"), m.get("method")) {
(Some(id), None) => {
let tx = match id.as_i64() {
Some(i) => self.pending.lock().await.remove(&i),
None => None,
};
if let Some(tx) = tx {
let _ = tx.send(match m.get("error") {
Some(e) => Err(e.to_string()),
None => Ok(m["result"].clone()),
});
}
}
(Some(id), Some(method)) => {
// server request: workspace/configuration wants an array; others get null
let result = if method == "workspace/configuration" {
let n = m["params"]["items"].as_array().map_or(0, |a| a.len());
Value::Array(vec![Value::Null; n])
} else {
Value::Null
};
let _ = stdin_tx.send(json!({"jsonrpc":"2.0","id":id,"result":result}));
}
(None, Some(method)) if method == "textDocument/publishDiagnostics" => {
let p = &m["params"];
let list: Vec<Diag> = p["diagnostics"]
.as_array()
.map(|a| a.iter().map(parse_diag).collect())
.unwrap_or_default();
self.diags.lock().await.insert(
p["uri"].as_str().unwrap_or_default().to_string(),
(p["version"].as_i64(), list),
);
self.diag_seq.fetch_add(1, Ordering::SeqCst);
self.notify.notify_waiters();
}
(None, Some(method)) if method == "$/progress" => {
let is_flycheck = m["params"]["token"]
.as_str()
.is_some_and(|t| t.contains("flycheck"));
match m["params"]["value"]["kind"].as_str() {
Some("begin") => {
if is_flycheck {
self.checks_active.store(true, Ordering::SeqCst);
}
self.busy.fetch_add(1, Ordering::SeqCst);
}
Some("end") => {
if is_flycheck {
self.checks_active.store(false, Ordering::SeqCst);
self.checks_done.fetch_add(1, Ordering::SeqCst);
}
self.busy.fetch_sub(1, Ordering::SeqCst);
}
_ => {}
};
self.notify.notify_waiters();
}
(None, Some(method)) if method == "experimental/serverStatus" => {
let q = m["params"]["quiescent"].as_bool().unwrap_or(true);
if q == *quiescent_busy {
*quiescent_busy = !q;
self.busy
.fetch_add(if q { -1 } else { 1 }, Ordering::SeqCst);
}
self.notify.notify_waiters();
}
_ => {}
}
}
}
impl Client {
/// Spawn the server and run `initialize`.
pub async fn start(
cmd: &[String],
root: &Path,
init_options: Value,
) -> std::io::Result<Arc<Self>> {
let mut c = Command::new(&cmd[0]);
c.args(&cmd[1..])
.current_dir(root)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true);
let mut child = c.spawn()?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let shared = Arc::new(Shared {
pending: Default::default(),
diags: Default::default(),
notify: Notify::new(),
alive: AtomicBool::new(true),
busy: AtomicI64::new(0),
checks_done: AtomicI64::new(0),
checks_active: AtomicBool::new(false),
diag_seq: AtomicI64::new(0),
});
let (stdin_tx, mut stdin_rx) = mpsc::unbounded_channel::<Value>();
// reader: responses, diagnostics, and server->client requests (answered via stdin_tx)
{
let shared = shared.clone();
tokio::spawn(async move { shared.read_loop(stdout, stdin_tx).await });
}
let client = Arc::new(Self {
stdin: Mutex::new(stdin),
child: Mutex::new(child),
next: AtomicI64::new(1),
shared,
});
// writer for replies to server requests
{
let c = client.clone();
tokio::spawn(async move {
while let Some(v) = stdin_rx.recv().await {
let _ = write_msg(&mut *c.stdin.lock().await, &v).await;
}
});
}
client
.request(
"initialize",
json!({
"processId": std::process::id(),
"rootUri": uri(root),
"workspaceFolders": [{"uri": uri(root), "name": root.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()}],
"initializationOptions": init_options,
"capabilities": {
"textDocument": {
"synchronization": {"didSave": true},
"publishDiagnostics": {"versionSupport": true},
"hover": {"contentFormat": ["plaintext", "markdown"]},
"definition": {}, "references": {}, "documentSymbol": {"hierarchicalDocumentSymbolSupport": true}
},
"workspace": {"configuration": true, "workspaceFolders": true, "symbol": {}},
"window": {"workDoneProgress": true},
"experimental": {"serverStatusNotification": true}
}
}),
Duration::from_secs(60),
)
.await
.map_err(std::io::Error::other)?;
client.notify("initialized", json!({})).await?;
Ok(client)
}
pub fn is_alive(&self) -> bool {
self.shared.alive.load(Ordering::SeqCst)
}
pub async fn notify(&self, method: &str, params: Value) -> std::io::Result<()> {
write_msg(
&mut *self.stdin.lock().await,
&json!({"jsonrpc":"2.0","method":method,"params":params}),
)
.await
}
pub async fn request(
&self,
method: &str,
params: Value,
timeout: Duration,
) -> Result<Value, String> {
if !self.is_alive() {
return Err("server not running".into());
}
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = oneshot::channel();
self.shared.pending.lock().await.insert(id, tx);
write_msg(
&mut *self.stdin.lock().await,
&json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}),
)
.await
.map_err(|e| e.to_string())?;
match tokio::time::timeout(timeout, rx).await {
Ok(Ok(r)) => r,
Ok(Err(_)) => Err("server dropped request".into()),
Err(_) => {
self.shared.pending.lock().await.remove(&id);
Err(format!("{method} timed out after {}s", timeout.as_secs()))
}
}
}
async fn published(&self, u: &str) -> Option<(Option<i64>, Vec<Diag>)> {
self.shared.diags.lock().await.get(u).cloned()
}
/// Final diagnostics for `u` after `sync` has sent the file's current text (didOpen/didChange +
/// didSave) and returned the document version. Waits up to `timeout` for a publish at that version
/// (or any changed publish when the server sends no versions), until the server is idle, then a
/// short settle period. With `expect_check` (rust-analyzer) the result also waits for the on-save
/// flycheck to end and publish. None = `sync` failed.
pub async fn diagnostics_after(
&self,
u: &str,
expect_check: bool,
timeout: Duration,
sync: impl Future<Output = Option<i64>>,
) -> Option<Result<Vec<Diag>, String>> {
let sh = &*self.shared;
let deadline = Instant::now() + timeout;
// a check still running from an earlier turn/startup must finish first
if expect_check {
while sh.checks_active.load(Ordering::SeqCst) {
if Instant::now() >= deadline
|| tokio::time::timeout(Duration::from_millis(500), sh.notify.notified())
.await
.is_err()
{
break;
}
}
}
let stale = self.published(u).await;
let v = sync.await?;
// count checks from after our save: a check still ending from an earlier save carries stale results
let checks_before = sh.checks_done.load(Ordering::SeqCst)
+ i64::from(sh.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 10s) 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 = sh.notify.notified();
let cur = self.published(u).await;
let check_finished = sh.checks_done.load(Ordering::SeqCst) > checks_before
&& !sh.checks_active.load(Ordering::SeqCst);
let check_never_started = sh.checks_done.load(Ordering::SeqCst) == checks_before
&& !sh.checks_active.load(Ordering::SeqCst)
&& Instant::now() >= check_wait_deadline;
if check_finished && after_end.is_none() {
after_end = Some((sh.diag_seq.load(Ordering::SeqCst), Instant::now()));
}
let published = after_end.is_some_and(|(seq, t)| {
sh.diag_seq.load(Ordering::SeqCst) > seq || t.elapsed() >= Duration::from_secs(10)
});
let checked = !expect_check || (check_finished && published) || check_never_started;
if fresh(&cur) && checked && sh.busy.load(Ordering::SeqCst) <= 0 {
loop {
let settle = sh.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 sh.busy.load(Ordering::SeqCst) <= 0 {
return Some(Ok(self.published(u).await.map(|x| x.1).unwrap_or_default()));
}
}
if !self.is_alive() {
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;
}
}
pub async fn shutdown(&self) {
let _ = self
.request("shutdown", Value::Null, Duration::from_secs(2))
.await;
let _ = self.notify("exit", Value::Null).await;
let _ = tokio::time::timeout(Duration::from_secs(2), self.child.lock().await.wait()).await;
let _ = self.child.lock().await.kill().await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uri_round_trip() {
let p = Path::new("/tmp/a b/ü.rs");
assert_eq!(uri(p), "file:///tmp/a%20b/%C3%BC.rs");
assert_eq!(path_of(&uri(p)), p);
}
}