//! The engine ↔ language server wiring (M3.3) against `lutra-lsp-fake`, //! M3.2's scripted server, which publishes every document's whole text as //! its one diagnostic. That makes the document sync visible: after any //! sequence of `buffer.edit`s the diagnostic must equal the buffer's text. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, clippy::string_slice )] use std::ffi::OsString; use std::fs; use std::path::PathBuf; use std::sync::{Mutex, mpsc}; use std::time::{Duration, Instant}; use lutra_engine::lsp::Launch; use lutra_engine::{Command, CommandSpec, Engine, EngineError, Event, Outcome, State}; use lutra_lsp::{RestartPolicy, ServerOptions}; use proptest::prelude::*; use serde_json::{Value, json}; use tempfile::TempDir; /// The fake server binary, built on demand when this test runs without /// the rest of the workspace (`cargo test -p lutra-engine`). 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 } /// Starting the fake server with `args`. fn launch(args: &[&str], options: ServerOptions) -> Launch { Launch { command: fake_server().into(), args: args.iter().map(OsString::from).collect(), options, tick: None, } } /// A temp project with `files`, opened in an engine that runs the fake /// server. fn project(files: &[(&str, &str)], launch: Launch) -> (TempDir, Engine) { let dir = tempfile::tempdir().unwrap(); for (name, text) in files { fs::write(dir.path().join(name), text).unwrap(); } let mut engine = Engine::new().unwrap(); engine.set_language_server(Some(launch)); engine .execute("project.open", json!({"path": dir.path()})) .unwrap(); (dir, engine) } /// Pumps until `done` holds for an event; returns every event seen, up to /// the end of that pump's batch. fn pump_until(engine: &mut Engine, done: impl Fn(&Value) -> bool) -> Vec { let deadline = Instant::now() + Duration::from_secs(20); let mut seen = Vec::new(); while Instant::now() < deadline { let mut hit = false; for event in engine.pump_vfs().unwrap() { let value = serde_json::to_value(&event).unwrap(); hit |= done(&value); seen.push(value); } if hit { return seen; } std::thread::sleep(Duration::from_millis(5)); } panic!("condition not met within 20 s; events: {seen:#?}"); } /// Whether `e` is `lspStatus` with `state`. fn status_is(e: &Value, state: &str) -> bool { e["kind"] == "lspStatus" && e["state"] == state } /// Pumps until the diagnostic of `path` says `text`. fn wait_for_text(engine: &mut Engine, path: &str, text: &str) { pump_until(engine, |e| { e["kind"] == "diagnosticsChanged" && e["path"] == path && e["items"][0]["message"] == text }); } /// Applies one UTF-16 edit to buffer `id`; returns the new version. fn edit(engine: &mut Engine, id: u64, base: u64, from: usize, to: usize, insert: &str) -> u64 { let out = engine .execute( "buffer.edit", json!({"id": id, "baseVersion": base, "edits": [{"from": from, "to": to, "insert": insert}]}), ) .unwrap(); out.value["version"].as_u64().unwrap() } /// The text of buffer `id`. fn text(engine: &mut Engine, id: u64) -> String { let out = engine.execute("buffer.get", json!({"id": id})).unwrap(); out.value["text"].as_str().unwrap().to_string() } #[test] fn syncs_buffers_and_reports_diagnostics() { let (_dir, mut engine) = project( &[("a.php", ">>>); impl Command for Probe { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "test.probe", label: "Probe", menu_path: None, default_shortcut: None, params: "path", } } fn run(&self, state: &mut State, params: Value) -> Result { let root = state.project.as_ref().unwrap().project.root().to_path_buf(); let path = root.join(params.as_str().unwrap()); let tx = self.0.lock().unwrap().take().unwrap(); let queued = lutra_engine::lsp::submit(state, move |server| { let _ = tx.send(server.document_text(&path)); }); assert!(queued); Ok(Outcome::default()) } } #[test] fn requests_never_overtake_edits() { let (_dir, mut engine) = project( &[("a.php", " = out .events .iter() .map(|e| serde_json::to_value(e).unwrap()) .collect(); seen.extend(pump_until(&mut engine, |e| status_is(e, "stopped"))); assert!( seen.iter() .any(|e| e["kind"] == "diagnosticsChanged" && e["items"] == json!([])), "{seen:#?}" ); let all = engine .execute("diagnostics.list", Value::Null) .unwrap() .value; assert_eq!(all, json!({"files": []})); assert_eq!( engine.execute("lsp.status", Value::Null).unwrap().value["state"], "stopped" ); } #[test] fn quit_stops_the_server_and_keeps_it_stopped() { let (_dir, mut engine) = project( &[( "a.php", " = out .events .iter() .map(|e| serde_json::to_value(e).unwrap()) .collect(); assert!( events.iter().any(|e| status_is(e, "stopped")), "{events:#?}" ); for _ in 0..10 { let events = engine.pump_vfs().unwrap(); assert!( !events.iter().any(|e| matches!(e, Event::LspStatus(_))), "{events:?}" ); } assert!(engine.state().lsp.server().is_none()); } #[test] fn restart_starts_a_fresh_server() { let (_dir, mut engine) = project( &[("a.php", " = out .events .iter() .map(|e| serde_json::to_value(e).unwrap()) .collect(); seen.extend(pump_until(&mut engine, |e| status_is(e, "ready"))); let states: Vec<&str> = seen .iter() .filter(|e| e["kind"] == "lspStatus") .map(|e| e["state"].as_str().unwrap()) .collect(); assert_eq!(states, ["stopped", "starting", "ready"], "{seen:#?}"); } #[test] fn a_missing_server_fails_with_a_notification() { let dir = tempfile::tempdir().unwrap(); let mut engine = Engine::new().unwrap(); engine.set_language_server(Some(Launch { command: dir.path().join("no-such-server").into(), args: Vec::new(), options: ServerOptions::default(), tick: None, })); engine .execute("project.open", json!({"path": dir.path()})) .unwrap(); let seen = pump_until(&mut engine, |e| status_is(e, "failed")); let failed = seen.iter().find(|e| status_is(e, "failed")).unwrap(); assert!( failed["message"] .as_str() .unwrap() .contains("no-such-server"), "{failed}" ); let note = seen.iter().find(|e| e["kind"] == "notification").unwrap(); assert_eq!(note["messageKey"], "notification.lsp.failed"); assert_eq!(note["level"], "error"); } #[test] fn a_crashing_server_restarts_then_gives_up() { let options = ServerOptions { restart: RestartPolicy { first_delay: Duration::from_millis(10), max_delay: Duration::from_millis(20), max_crashes: 2, window: Duration::from_secs(60), }, ..ServerOptions::default() }; let (_dir, mut engine) = project( &[("a.php", "(), edits in prop::collection::vec((0usize..64, 0usize..8, "[a-zé\u{1F9A6}\n\r ]{0,6}"), 1..25), ) { let args: &[&str] = if full { &["--sync-full"] } else { &[] }; let (_dir, mut engine) = project(&[("a.php", " = std::iter::once(0) .chain(current.char_indices().map(|(i, c)| current[..i].encode_utf16().count() + c.len_utf16())) .collect(); let from = units[at % units.len()]; let to = units[(at + len).min(units.len() - 1)].max(from); let result = engine.execute( "buffer.edit", json!({"id": id, "baseVersion": version, "edits": [{"from": from, "to": to, "insert": insert}]}), ); if let Ok(out) = result { version = out.value["version"].as_u64().unwrap(); } if at % 5 == 0 { engine.pump_vfs().unwrap(); } } let expected = text(&mut engine, id); wait_for_text(&mut engine, "a.php", &expected); } } /// The real Phpactor (ignored; needs PHP and a PHAR): a file with two /// errors gets its diagnostics after `file.open`, and an edit that adds a /// third gets them again. Prints the startup and diagnostics latencies. /// /// `LUTRA_PHPACTOR= [LUTRA_PHP=php] cargo test -p lutra-engine --test lsp real_phpactor -- --ignored --nocapture` #[test] #[ignore = "needs PHP and Phpactor (LUTRA_PHPACTOR)"] fn real_phpactor_reports_diagnostics() { let phar = std::env::var("LUTRA_PHPACTOR").expect("LUTRA_PHPACTOR"); let php = std::env::var("LUTRA_PHP").unwrap_or_else(|_| "php".into()); let text = "wave();\n"; let launch = lutra_engine::lsp::phpactor_launch(&php, &phar, cfg!(windows)); let (_dir, mut engine) = project(&[("Broken.php", text)], launch); let started = Instant::now(); let seen = pump_until(&mut engine, |e| { status_is(e, "ready") || status_is(e, "failed") }); println!("ready after {:?}: {:?}", started.elapsed(), seen.last()); let id = engine .execute("file.open", json!({"path": "Broken.php"})) .unwrap() .value["id"] .as_u64() .unwrap(); let opened = Instant::now(); let has = |e: &Value, word: &str| { e["kind"] == "diagnosticsChanged" && e["items"].as_array().is_some_and(|items| { items .iter() .any(|i| i["message"].as_str().unwrap_or("").contains(word)) }) }; let deadline = Instant::now() + Duration::from_secs(120); let mut found = false; while Instant::now() < deadline && !found { for event in engine.pump_vfs().unwrap() { let value = serde_json::to_value(&event).unwrap(); if value["kind"] != "notification" { println!("{:?} {value}", opened.elapsed()); } found |= has(&value, "wave"); } std::thread::sleep(Duration::from_millis(20)); } assert!(found, "no diagnostics for wave() within 120 s"); println!("first diagnostics after {:?}", opened.elapsed()); let end = text.encode_utf16().count(); edit(&mut engine, id, 1, end, end, "$g->dance();\n"); let edited = Instant::now(); let deadline = Instant::now() + Duration::from_secs(60); let mut found = false; while Instant::now() < deadline && !found { for event in engine.pump_vfs().unwrap() { found |= has(&serde_json::to_value(&event).unwrap(), "dance"); } std::thread::sleep(Duration::from_millis(20)); } assert!(found, "no diagnostics for dance() within 60 s"); println!("diagnostics after edit {:?}", edited.elapsed()); }