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.
This commit is contained in:
1 parent
f1a83e6cb1
commit
70d8bc2aaf
3 files changed
+373
-249
No files matched your search
+257
-155
@@ -5,11 +5,11 @@ use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::time::Duration;
|
||||
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, oneshot};
|
||||
use tokio::sync::{Mutex, Notify, mpsc, oneshot};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Diag {
|
||||
@@ -23,26 +23,29 @@ pub struct Diag {
|
||||
}
|
||||
|
||||
/// uri -> (version reported, diagnostics)
|
||||
type DiagMap = Arc<Mutex<HashMap<String, (Option<i64>, Vec<Diag>)>>>;
|
||||
type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<Result<Value, String>>>>>;
|
||||
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,
|
||||
pending: Pending,
|
||||
diags: DiagMap,
|
||||
pub diag_notify: Arc<Notify>,
|
||||
pub alive: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle
|
||||
pub busy: Arc<AtomicI64>,
|
||||
/// completed on-save checks (rust-analyzer flycheck). Diagnostics after a save are final once this advances.
|
||||
pub checks_done: Arc<AtomicI64>,
|
||||
pub checks_active: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// Incremented on every `textDocument/publishDiagnostics` notification.
|
||||
pub diag_seq: Arc<AtomicI64>,
|
||||
pub root: PathBuf,
|
||||
pub capabilities: std::sync::OnceLock<Value>,
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
pub fn uri(p: &Path) -> String {
|
||||
@@ -102,6 +105,124 @@ async fn write_msg(w: &mut ChildStdin, v: &Value) -> std::io::Result<()> {
|
||||
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(
|
||||
@@ -119,144 +240,28 @@ impl Client {
|
||||
let mut child = c.spawn()?;
|
||||
let stdin = child.stdin.take().expect("piped");
|
||||
let stdout = child.stdout.take().expect("piped");
|
||||
let pending: Pending = Default::default();
|
||||
let diags: DiagMap = Default::default();
|
||||
let notify = Arc::new(Notify::new());
|
||||
let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
let busy = Arc::new(AtomicI64::new(0));
|
||||
let checks_done = Arc::new(AtomicI64::new(0));
|
||||
let checks_active = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let diag_seq = Arc::new(AtomicI64::new(0));
|
||||
let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::unbounded_channel::<Value>();
|
||||
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 (pending, diags, notify, alive, busy, checks_done, checks_active, diag_seq) = (
|
||||
pending.clone(),
|
||||
diags.clone(),
|
||||
notify.clone(),
|
||||
alive.clone(),
|
||||
busy.clone(),
|
||||
checks_done.clone(),
|
||||
checks_active.clone(),
|
||||
diag_seq.clone(),
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
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 {
|
||||
alive.store(false, Ordering::SeqCst);
|
||||
for (_, tx) in pending.lock().await.drain() {
|
||||
let _ = tx.send(Err("server exited".into()));
|
||||
}
|
||||
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;
|
||||
};
|
||||
match (m.get("id"), m.get("method")) {
|
||||
(Some(id), None) => {
|
||||
let tx = match id.as_i64() {
|
||||
Some(i) => 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();
|
||||
diags.lock().await.insert(
|
||||
p["uri"].as_str().unwrap_or_default().to_string(),
|
||||
(p["version"].as_i64(), list),
|
||||
);
|
||||
diag_seq.fetch_add(1, Ordering::SeqCst);
|
||||
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 {
|
||||
checks_active.store(true, Ordering::SeqCst);
|
||||
}
|
||||
busy.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
Some("end") => {
|
||||
if is_flycheck {
|
||||
checks_active.store(false, Ordering::SeqCst);
|
||||
checks_done.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
busy.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
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;
|
||||
busy.fetch_add(if q { -1 } else { 1 }, Ordering::SeqCst);
|
||||
}
|
||||
notify.notify_waiters();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
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),
|
||||
pending,
|
||||
diags,
|
||||
diag_notify: notify,
|
||||
alive,
|
||||
busy,
|
||||
checks_done,
|
||||
checks_active,
|
||||
diag_seq,
|
||||
root: root.to_path_buf(),
|
||||
capabilities: Default::default(),
|
||||
shared,
|
||||
});
|
||||
// writer for replies to server requests
|
||||
{
|
||||
@@ -267,7 +272,7 @@ impl Client {
|
||||
}
|
||||
});
|
||||
}
|
||||
let init = client
|
||||
client
|
||||
.request(
|
||||
"initialize",
|
||||
json!({
|
||||
@@ -291,11 +296,15 @@ impl Client {
|
||||
)
|
||||
.await
|
||||
.map_err(std::io::Error::other)?;
|
||||
|
||||
client.notify("initialized", json!({})).await?;
|
||||
let _ = client.capabilities.set(init["capabilities"].clone());
|
||||
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,
|
||||
@@ -310,12 +319,12 @@ impl Client {
|
||||
params: Value,
|
||||
timeout: Duration,
|
||||
) -> Result<Value, String> {
|
||||
if !self.alive.load(Ordering::SeqCst) {
|
||||
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.pending.lock().await.insert(id, tx);
|
||||
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}),
|
||||
@@ -326,14 +335,107 @@ impl Client {
|
||||
Ok(Ok(r)) => r,
|
||||
Ok(Err(_)) => Err("server dropped request".into()),
|
||||
Err(_) => {
|
||||
self.pending.lock().await.remove(&id);
|
||||
self.shared.pending.lock().await.remove(&id);
|
||||
Err(format!("{method} timed out after {}s", timeout.as_secs()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn diagnostics(&self, u: &str) -> Option<(Option<i64>, Vec<Diag>)> {
|
||||
self.diags.lock().await.get(u).cloned()
|
||||
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) {
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
|
||||
@@ -265,7 +264,7 @@ impl Manager {
|
||||
}
|
||||
let slot = slots.entry(key.clone()).or_default();
|
||||
if let Some(s) = &slot.server
|
||||
&& !s.client.alive.load(Ordering::SeqCst)
|
||||
&& !s.client.is_alive()
|
||||
{
|
||||
slot.server = None;
|
||||
slot.failures += 1;
|
||||
@@ -338,104 +337,21 @@ impl Manager {
|
||||
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.
|
||||
/// 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<Result<Vec<Diag>, String>> {
|
||||
let before = self.client(file).await.map(|(c, ..)| c)?;
|
||||
let is_rust = self
|
||||
let (cl, ..) = self.client(file).await?;
|
||||
let expect_check = 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;
|
||||
}
|
||||
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).
|
||||
@@ -481,7 +397,7 @@ impl Manager {
|
||||
.iter()
|
||||
.map(|((id, root), s)| {
|
||||
let st = match &s.server {
|
||||
Some(x) if x.client.alive.load(Ordering::SeqCst) => {
|
||||
Some(x) if x.client.is_alive() => {
|
||||
format!("running, {} open", x.open.len())
|
||||
}
|
||||
Some(_) => "dead".into(),
|
||||
@@ -545,4 +461,39 @@ mod tests {
|
||||
);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Fake rust-analyzer for manager tests. Mimics the on-save flycheck protocol:
|
||||
didChange publishes empty "native" diagnostics at once; didSave starts a flycheck
|
||||
(`$/progress` begin/end), and the real diagnostics (any text containing "oops" is an error)
|
||||
are published shortly after `end`.
|
||||
"""
|
||||
import json, sys, threading, time
|
||||
|
||||
out_lock = threading.Lock()
|
||||
docs = {}
|
||||
|
||||
|
||||
def send(m):
|
||||
b = json.dumps(m).encode()
|
||||
with out_lock:
|
||||
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(b) + b)
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
|
||||
def read():
|
||||
n = None
|
||||
while True:
|
||||
line = sys.stdin.buffer.readline()
|
||||
if not line:
|
||||
return None
|
||||
line = line.strip()
|
||||
if not line:
|
||||
break
|
||||
if line.lower().startswith(b"content-length:"):
|
||||
n = int(line.split(b":")[1])
|
||||
return json.loads(sys.stdin.buffer.read(n))
|
||||
|
||||
|
||||
def publish(uri, version, diags):
|
||||
send({"jsonrpc": "2.0", "method": "textDocument/publishDiagnostics",
|
||||
"params": {"uri": uri, "version": version, "diagnostics": diags}})
|
||||
|
||||
|
||||
def progress(kind):
|
||||
send({"jsonrpc": "2.0", "method": "$/progress",
|
||||
"params": {"token": "rust-analyzer/flycheck/0", "value": {"kind": kind}}})
|
||||
|
||||
|
||||
def flycheck(uri):
|
||||
version, text = docs[uri]
|
||||
progress("begin")
|
||||
time.sleep(0.3)
|
||||
progress("end")
|
||||
time.sleep(0.1)
|
||||
bad = [{"range": {"start": {"line": 0, "character": 0}}, "severity": 1,
|
||||
"message": "bad", "source": "fake"}] if "oops" in text else []
|
||||
publish(uri, version, bad)
|
||||
|
||||
|
||||
while True:
|
||||
m = read()
|
||||
if m is None:
|
||||
break
|
||||
method, p = m.get("method"), m.get("params", {})
|
||||
if method == "initialize":
|
||||
send({"jsonrpc": "2.0", "id": m["id"], "result": {"capabilities": {}}})
|
||||
elif method == "shutdown":
|
||||
send({"jsonrpc": "2.0", "id": m["id"], "result": None})
|
||||
elif method == "exit":
|
||||
break
|
||||
elif method in ("textDocument/didOpen", "textDocument/didChange"):
|
||||
td = p["textDocument"]
|
||||
text = td["text"] if method.endswith("didOpen") else p["contentChanges"][0]["text"]
|
||||
docs[td["uri"]] = (td["version"], text)
|
||||
publish(td["uri"], td["version"], [])
|
||||
elif method == "textDocument/didSave":
|
||||
threading.Thread(target=flycheck, args=(p["textDocument"]["uri"],), daemon=True).start()
|
||||
Reference in new issue
Block a user