//! One language server session: the thread that owns the //! [`lutra_lsp::Server`] of the open project. //! //! The engine lock only ever enqueues [`Job`]s. The session thread starts //! the server (spawning a process can take tens of milliseconds on Windows //! with a virus scanner), turns buffer snapshots into text, sends document //! sync and runs the closures of [`super::submit`], strictly in the order //! they were queued. A request queued after an edit therefore reaches the //! server after that edit's `didChange`. What the thread learns goes back //! to the next pump as a [`Report`]. use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError}; use std::time::{Duration, Instant}; use lutra_lsp::{LspError, Server, ServerEvent, ServerOptions, Status}; use lutra_text::{Buffer, Edit}; use serde_json::{Map, Value}; /// How a session starts its server. #[derive(Debug, Clone, PartialEq)] pub struct Launch { /// The executable (PHP for Phpactor). pub command: OsString, /// Its arguments (the PHAR and `language-server` for Phpactor). pub args: Vec, /// Client options (timeouts, restart policy, `initializationOptions`). pub options: ServerOptions, /// Send the no-op notification [`super::TICK_METHOD`] at this interval /// while the session is busy (see [`super::TICK_WINDOW`]), and at /// [`super::FAST_TICK_INTERVAL`] while the server indexes or the /// session is young (see [`super::tick_interval`]); `None` for servers /// that need no nudge. Phpactor on Windows needs it, see /// [`super::phpactor_launch`]. pub tick: Option, } /// Work for the session thread, run in queue order. pub enum Job { /// Open a document with the text of a buffer snapshot. Open { /// Absolute path. path: PathBuf, /// The buffer at the version the engine recorded. text: Buffer, }, /// Apply the edits `buffer.edit` applied (byte ranges into the previous /// text). Change { /// Absolute path. path: PathBuf, /// The edit batch. edits: Vec, }, /// Replace the whole text (a reload from disk, a restore, a resync). Full { /// Absolute path. path: PathBuf, /// The buffer snapshot. text: Buffer, }, /// The buffer was saved. Save { /// Absolute path. path: PathBuf, }, /// The buffer was closed. Close { /// Absolute path. path: PathBuf, }, /// A closure from [`super::submit`]: requests of M3.4/M3.5. Run(Box), } /// What the session thread reports to the pump. pub enum Report { /// The server process started; its events arrive on `events`. Started { /// The server, shared so the engine can read its status. server: Arc, /// Its event channel. events: Receiver, }, /// The server could not be started. SpawnFailed(String), /// A `didChange` did not fit the client's copy of the document; the /// pump resends the whole text. Desync(PathBuf), } /// The engine's handle on a running session thread. pub struct Session { /// Jobs to the thread. Dropping it ends the thread, which shuts the /// server down. jobs: Sender, /// Reports from the thread. pub reports: Receiver, /// The thread, joined by [`Session::join`]. thread: Option>, } impl Session { /// Starts the session thread, which starts `launch` in `root`. /// /// # Parameters /// - `indexing`: set by the pump while the server reports work-done /// progress; the thread ticks fast while it is set. /// /// # Errors /// The thread could not be started. pub fn start(launch: Launch, root: PathBuf, indexing: Arc) -> Result { let (jobs, queue) = mpsc::channel::(); let (reporter, reports) = mpsc::channel::(); let thread = std::thread::Builder::new() .name("lsp-session".into()) .spawn(move || run(launch, &root, &indexing, &queue, &reporter)) .map_err(|e| format!("cannot start the language server thread: {e}"))?; Ok(Self { jobs, reports, thread: Some(thread), }) } /// Queues a job. /// /// # Returns /// `false` when the thread is gone. pub fn send(&self, job: Job) -> bool { self.jobs.send(job).is_ok() } /// Ends the queue and waits until the thread has shut the server down /// (`shutdown`, `exit`, kill if needed: at most about 3 s). For a host /// that is about to exit, where a background shutdown would be cut /// short and leave the server process running. The caller must have /// dropped its own handles on the server first, or the thread cannot /// take sole ownership and the server is only stopped in the /// background. A thread that panicked is ignored: there is nothing /// left to stop. pub fn join(self) { let Self { jobs, reports, thread, } = self; drop(jobs); drop(reports); if let Some(thread) = thread { let _ = thread.join(); } } } /// The session thread: starts the server, works off the queue until the /// engine drops its sender, then shuts the server down (`shutdown`, `exit`, /// kill), here and never under the engine lock. Reports that cannot be /// delivered are dropped because the engine has stopped listening. fn run( launch: Launch, root: &Path, indexing: &AtomicBool, queue: &Receiver, reporter: &Sender, ) { let Launch { command, args, options, tick, } = launch; let server = match Server::spawn(&command, &args, root, options) { Ok((server, events)) => { let server = Arc::new(server); let _ = reporter.send(Report::Started { server: Arc::clone(&server), events, }); server } Err(error) => { let _ = reporter.send(Report::SpawnFailed(error.to_string())); while queue.recv().is_ok() {} return; } }; work(&server, tick, indexing, queue, reporter); match Arc::try_unwrap(server) { Ok(server) => server.shutdown(), Err(shared) => drop(shared), } } /// Works off the queue until the engine drops its sender. With a tick /// interval, also sends [`super::TICK_METHOD`] whenever one is due /// ([`super::tick_due`]): the thread wakes at least once per interval, so /// ticks do not depend on how often the host pumps. /// /// The interval comes from [`super::tick_interval`]. A fast one (below /// [`COARSE_WAIT`]) is kept with [`std::thread::sleep`] between polls of /// the queue, because a channel wait with a timeout wakes at most about /// 64 times a second on Windows (its timer resolution of 15.6 ms; /// measured: 63–67 wakes/s for 1, 2 and 5 ms timeouts), while a sleep /// uses a high-resolution timer. A job then waits at most one interval. fn work( server: &Server, tick: Option, indexing: &AtomicBool, queue: &Receiver, reporter: &Sender, ) { let started = Instant::now(); let mut last_job = started; let mut last_tick = None; loop { let fast = indexing.load(Ordering::Relaxed); let interval = super::tick_interval(tick, fast, started.elapsed()); let next = match interval { Some(interval) if interval < COARSE_WAIT => match queue.try_recv() { Ok(job) => Ok(job), Err(TryRecvError::Empty) => { std::thread::sleep(interval); Err(RecvTimeoutError::Timeout) } Err(TryRecvError::Disconnected) => Err(RecvTimeoutError::Disconnected), }, Some(interval) => queue.recv_timeout(interval), None => queue.recv().map_err(|_| RecvTimeoutError::Disconnected), }; match next { Ok(job) => { last_job = Instant::now(); handle(server, job, reporter); } Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => return, } let now = Instant::now(); let ready = server.status() == Status::Ready; let activity = if interval == tick { last_job } else { now }; if super::tick_due(interval, ready, Some(activity), last_tick, now) { last_tick = Some(now); server.notify(super::TICK_METHOD, Value::Object(Map::new())); } } } /// Intervals below this are waited for with a sleep instead of a channel /// timeout (see [`work`]). const COARSE_WAIT: Duration = Duration::from_millis(16); /// Runs one job against the server. Sync failures are expected races /// (a buffer closed twice, a document already open after a restart of the /// session) and change nothing, except a `didChange` that no longer fits, /// which asks the pump for a full resync. fn handle(server: &Server, job: Job, reporter: &Sender) { match job { Job::Open { path, text } => { let text = text.text(); if let Err(LspError::AlreadyOpen { .. }) = server.did_open(&path, "php", &text) { let _ = server.did_change_full(&path, &text); } } Job::Change { path, edits } => { if let Err(LspError::Text(_) | LspError::NotOpen { .. }) = server.did_change(&path, &edits) { let _ = reporter.send(Report::Desync(path)); } } Job::Full { path, text } => { let text = text.text(); if let Err(LspError::NotOpen { .. }) = server.did_change_full(&path, &text) { let _ = server.did_open(&path, "php", &text); } } Job::Save { path } => { let _ = server.did_save(&path); } Job::Close { path } => { let _ = server.did_close(&path); } Job::Run(f) => f(server), } }