Lutra/crates/engine/tests/pending.rs
danny 20d1d28c32 M3.5: pending outcomes for commands that wait for the language server
Step 1 of M3.5: the shared mechanism. M3.4 and M3.5 build on it.

- Engine: `Outcome.pending: Option<Pending>`. `Pending::new(rx, timeout,
  finish)`; `Pending::wait()` is called without the engine lock and
  returns at the answer, a dropped sender or the deadline (timeout + 1 s).
  `Engine::resolve(answered)` then runs `finish(state, reply)` inside the
  guard, under the lock. `run_waiting(lock, cmd, params, publish)` does
  all three steps for hosts.
- Hosts: `Host::run`, `testkit::EngineBackend` and the control test
  backend use `run_waiting`.
- New IPC `engine_execute_waiting` (`#[tauri::command(async)]`, off the
  main thread) with `runWaiting()` in `ui/src/ipc.ts`. Only `lsp.*`
  requests use it.

Ordering guarantee:
- `engine_execute` stays synchronous on the main thread, so ordinary
  commands (`buffer.edit`) still run in call order.
- The order towards the server is fixed under the engine lock:
  `buffer.edit` queues its didChange on the session's FIFO queue before
  it returns, and `lsp::submit` queues the request on the same queue.
  A request therefore sees every edit whose `buffer.edit` returned
  first, and the UI awaits the sync's `idle()` before sending one.

Failures:
- A stall is caught by the request timeout, with the deadline as
  backstop.
- On restart, close, quit or crash the request is dropped or resolved
  as stopped, so the waiter gets an error, never a hang.

Tests: `crates/engine/tests/pending.rs` (answer, lock free while
waiting, dropped sender, deadline, resolve, lsp.restart while a
request is pending) and Vitest for `runWaiting`. Gate: 13 steps,
321 s, Vitest 443 + 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 06:36:20 +02:00

348 lines
11 KiB
Rust

//! Pending outcomes: a command that waits for an answer from outside the
//! engine (a language server request) returns [`Pending`]; hosts wait for
//! it without the engine lock ([`run_waiting`]) and finish it under the
//! lock ([`Engine::resolve`]). Covers the answer, a dropped sender, the
//! deadline, the lock staying free while waiting, events of both steps,
//! and a language server restart while a request is pending.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use lutra_engine::lsp::Launch;
use lutra_engine::{
Command, CommandSpec, Engine, EngineError, Event, Outcome, Pending, Reply, State, run_waiting,
};
use lutra_lsp::{LspError, ServerOptions};
use serde_json::{Value, json};
/// How a [`Waits`] command's answer arrives.
#[derive(Clone, Copy)]
enum Answer {
/// From another thread after 100 ms.
Later,
/// Never: the sender is dropped at once.
Dropped,
/// Never: the sender is kept beyond the deadline (200 ms).
Stalls,
/// By the test: the sender is put into [`HANDED`].
Handed,
}
/// The sender of the last `Answer::Handed` command.
static HANDED: Mutex<Option<mpsc::Sender<Result<Value, LspError>>>> = Mutex::new(None);
/// `test.wait`: returns a pending outcome answered as `Answer` says; its
/// first step and its finish each queue one notification.
struct Waits(Answer, CommandSpec);
impl Waits {
/// A `Waits` command with id `id`.
fn new(answer: Answer, id: &'static str) -> Self {
Self(
answer,
CommandSpec {
id,
label: "Wait",
menu_path: None,
default_shortcut: None,
params: "none",
},
)
}
}
impl Command for Waits {
fn spec(&self) -> &CommandSpec {
&self.1
}
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
let (tx, rx) = mpsc::channel();
match self.0 {
Answer::Later => {
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
let _ = tx.send(Ok(json!(42)));
});
}
Answer::Dropped => drop(tx),
Answer::Handed => *HANDED.lock().unwrap() = Some(tx),
Answer::Stalls => {
std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(3));
drop(tx);
});
}
}
state.notify(
lutra_engine::NotificationLevel::Info,
None,
Some("asked".into()),
None,
);
Ok(Outcome::pending(Pending::new(
rx,
if matches!(self.0, Answer::Handed) {
Duration::from_secs(10)
} else {
Duration::from_millis(200)
},
|state: &mut State, reply: Reply| {
state.notify(
lutra_engine::NotificationLevel::Info,
None,
Some("answered".into()),
None,
);
match reply {
Some(Ok(value)) => Ok(json!({ "answer": value })),
Some(Err(e)) => Err(EngineError::Failed(e.to_string())),
None => Err(EngineError::Failed("no answer".into())),
}
},
)))
}
}
/// An engine with the three test commands, behind a lock like in a host.
fn engine() -> Arc<Mutex<Engine>> {
let mut engine = Engine::new().unwrap();
engine
.register(Box::new(Waits::new(Answer::Later, "test.later")))
.unwrap();
engine
.register(Box::new(Waits::new(Answer::Dropped, "test.dropped")))
.unwrap();
engine
.register(Box::new(Waits::new(Answer::Stalls, "test.stalls")))
.unwrap();
engine
.register(Box::new(Waits::new(Answer::Handed, "test.handed")))
.unwrap();
Arc::new(Mutex::new(engine))
}
/// The messages of the notifications among `events`.
fn messages(events: &[Event]) -> Vec<String> {
events
.iter()
.filter_map(|e| match e {
Event::Notification { message, .. } => message.clone(),
_ => None,
})
.collect()
}
#[test]
fn the_answer_becomes_the_value_and_both_steps_publish() {
let engine = engine();
let mut published = Vec::new();
let out = run_waiting(
|| engine.lock().unwrap(),
"test.later",
Value::Null,
|events| published.extend_from_slice(events),
)
.unwrap();
assert_eq!(out.value, json!({"answer": 42}));
assert!(out.pending.is_none());
assert_eq!(messages(&published), ["asked", "answered"]);
}
#[test]
fn the_lock_is_free_while_waiting() {
let engine = engine();
let waiter = {
let engine = Arc::clone(&engine);
std::thread::spawn(move || {
run_waiting(
|| engine.lock().unwrap(),
"test.handed",
Value::Null,
|_| {},
)
})
};
let deadline = Instant::now() + Duration::from_secs(10);
let answer = loop {
if let Some(tx) = HANDED.lock().unwrap().take() {
break tx;
}
assert!(Instant::now() < deadline, "the command never ran");
std::thread::sleep(Duration::from_millis(1));
};
let about = loop {
if let Ok(mut engine) = engine.try_lock() {
break engine.execute("app.about", Value::Null).unwrap();
}
assert!(
Instant::now() < deadline,
"the engine stayed locked while the command waited"
);
std::thread::sleep(Duration::from_millis(1));
};
assert_eq!(about.value["name"], "Lutra");
assert!(!waiter.is_finished(), "still waiting for its answer");
answer.send(Ok(json!(42))).unwrap();
assert_eq!(waiter.join().unwrap().unwrap().value["answer"], 42);
}
#[test]
fn a_dropped_sender_ends_at_once_with_the_finish_error() {
let engine = engine();
let started = Instant::now();
let err = run_waiting(
|| engine.lock().unwrap(),
"test.dropped",
Value::Null,
|_| {},
)
.unwrap_err();
assert_eq!(err, EngineError::Failed("no answer".into()));
assert!(started.elapsed() < Duration::from_millis(500));
}
#[test]
fn a_stalled_answer_ends_at_the_deadline() {
let engine = engine();
let started = Instant::now();
let err = run_waiting(
|| engine.lock().unwrap(),
"test.stalls",
Value::Null,
|_| {},
)
.unwrap_err();
assert_eq!(err, EngineError::Failed("no answer".into()));
let took = started.elapsed();
assert!(
took >= Duration::from_millis(200) && took < Duration::from_millis(2_500),
"deadline plus one second of grace, took {took:?}"
);
}
#[test]
fn engine_resolve_runs_the_finish_with_the_lock() {
let engine = engine();
let mut engine = engine.lock().unwrap();
let mut out = engine.execute("test.later", Value::Null).unwrap();
assert_eq!(
out.value,
Value::Null,
"the value comes from the pending answer"
);
assert_eq!(messages(&out.events), ["asked"]);
let answered = out.pending.take().unwrap().wait();
let resolved = engine.resolve(answered).unwrap();
assert_eq!(resolved.value, json!({"answer": 42}));
assert_eq!(messages(&resolved.events), ["answered"]);
}
/// The fake language server binary (see `tests/lsp.rs`).
fn fake_server() -> PathBuf {
let exe = format!("lutra-lsp-fake{}", std::env::consts::EXE_SUFFIX);
let deps = std::env::current_exe().unwrap();
let path = deps.parent().unwrap().parent().unwrap().join(exe);
if !path.exists() {
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let status = std::process::Command::new(cargo)
.args(["build", "-p", "lutra-lsp", "--bin", "lutra-lsp-fake"])
.status()
.unwrap();
assert!(status.success(), "building lutra-lsp-fake failed");
}
path
}
/// `test.sleep`: sends the fake server's `fake/sleep`, which is never
/// answered, through [`lutra_engine::lsp::submit`].
struct Sleeps;
impl Command for Sleeps {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "test.sleep",
label: "Sleep",
menu_path: None,
default_shortcut: None,
params: "none",
}
}
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
let (tx, rx) = mpsc::channel::<Result<Value, LspError>>();
let queued = lutra_engine::lsp::submit(state, move |server| {
let reply = tx.clone();
let sent = server.request_with(
"fake/sleep",
json!({}),
Duration::from_secs(30),
Box::new(move |result| {
let _ = reply.send(result);
}),
);
if let Err(e) = sent {
let _ = tx.send(Err(e));
}
});
assert!(queued, "a session runs");
Ok(Outcome::pending(Pending::new(
rx,
Duration::from_secs(30),
|_state, reply| match reply {
Some(Ok(value)) => Ok(value),
Some(Err(e)) => Err(EngineError::Failed(e.to_string())),
None => Err(EngineError::Failed("the server stopped".into())),
},
)))
}
}
#[test]
fn a_language_server_restart_ends_a_pending_request_with_an_error() {
let dir = tempfile::tempdir().unwrap();
let mut engine = Engine::new().unwrap();
engine.register(Box::new(Sleeps)).unwrap();
engine.set_language_server(Some(Launch {
command: fake_server().into(),
args: Vec::<OsString>::new(),
options: ServerOptions::default(),
tick: None,
}));
engine
.execute("project.open", json!({"path": dir.path()}))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
while engine.state().lsp.status().state != lutra_engine::lsp::LspState::Ready {
assert!(Instant::now() < deadline, "the fake server never got ready");
engine.pump_vfs().unwrap();
std::thread::sleep(Duration::from_millis(5));
}
let engine = Arc::new(Mutex::new(engine));
let waiter = {
let engine = Arc::clone(&engine);
std::thread::spawn(move || {
let started = Instant::now();
let result = run_waiting(|| engine.lock().unwrap(), "test.sleep", Value::Null, |_| {});
(result, started.elapsed())
})
};
std::thread::sleep(Duration::from_millis(300));
{
let mut engine = engine.lock().unwrap();
engine.execute("lsp.restart", Value::Null).unwrap();
engine.pump_vfs().unwrap();
}
let (result, took) = waiter.join().unwrap();
let err = result.unwrap_err();
assert_eq!(err.code(), "failed", "{err}");
assert!(took < Duration::from_secs(10), "took {took:?}");
}