//! The request loop: one burst in, one response per request, on one thread. //! //! `lsp-server` runs two I/O threads of its own and hands this loop framed //! messages over a channel. Everything below is synchronous — Verilog files //! are small, every handler is milliseconds, and a worker pool would buy //! nothing yet. A request that has already started therefore runs to //! completion; the one thing `$/cancelRequest` can do here is answer a request //! still *queued* behind the one being served, which is what the burst drain //! in `run` is for. See `docs/features/lucisv-server/README.md` and //! `docs/features/cancel-request/README.md`. //! //! The server is one directory of modules, each the answer to one question; //! this file holds the `Server` itself — what the client can do, what the //! server owns, and the loop (`run`, `process_batch`, the order contract in //! `must_wait`). The rest, in the order a message meets them: //! //! * `batch` — reading a burst before any of it is served: the forwarder //! thread, the drain, the cancels a burst carries, the `didOpen`s that widen //! the scope; //! * `dispatch` — `answer_request`, the table over request methods, with the //! decoding it needs and the `Failure` it answers in; //! * `large_file` — what a buffer over the large-file threshold answers //! instead of the dispatch; //! * `formatting` — the five formatting entries and how a refusal is said; //! * `semantic_tokens` — the remembered answer a token delta is computed //! against; //! * `diagnostics` — when a buffer is analyzed (the change debounce) and how //! what it says reaches the client, pushed or pulled; //! * `notification` — `handle_notification`, the table over notification //! methods, and the settings applier both settings doors share; //! * `index` — the rescans: whole, one file, widened, and the scan that //! answers messages while it runs; //! * `progress` — the indexing bar and the per-file log a rescan runs under; //! * `client` — what goes to the client other than a response: the requests //! made of it and the answers read back, the messages, the timing lines. //! //! Methods a sibling file calls are `pub(super)`; everything else is private //! to its file. The tests are in `tests/`, one file per feature. use std::collections::{HashMap, HashSet}; use std::error::Error; use lsp_server::{Connection, Message, RequestId}; use lsp_types::notification::{Cancel, Notification as _}; use lsp_types::{SemanticToken, Uri}; use crate::settings::ClientSettings; use crate::state::Workspace; use batch::{burst, cancelled_in, cancelled_response, forward}; mod batch; mod client; mod diagnostics; mod dispatch; mod formatting; mod index; mod large_file; mod notification; mod progress; mod semantic_tokens; #[cfg(test)] mod tests; /// What the client said it can do, read once at `initialize` because that is /// the only time those capabilities are sent. #[derive(Default)] pub struct ClientAbilities { /// Whether the client can expand a completion item's tabstops. pub snippets: bool, /// Whether the client accepts a `workspace/didChangeWatchedFiles` /// registration. There is no static form of that capability, so a client /// that says nothing keeps the save-only staleness model. pub file_watching: bool, /// Whether the client applies a `workspace/applyEdit` request. A client /// that cannot gets a command's edit back as the request result instead, /// which is what every client got before this was read. pub apply_edit: bool, /// Whether the client *pulls* diagnostics (LSP 3.17). One client is never /// served both models: a pulling client is pushed nothing at all. pub pull_diagnostics: bool, /// Whether the client renders server-initiated work-done progress. The /// spec forbids creating any without it, so a client that said nothing /// sees the workspace rescan exactly as it did before — silently. pub work_done_progress: bool, /// Whether the client accepts a `workspace/codeLens/refresh`. A client /// that said nothing is never asked, and keeps the instantiation counts it /// last requested until it asks again for its own reasons. pub code_lens_refresh: bool, /// Whether the client opens a document the server asks it to /// (`window/showDocument`). This is what lets the instantiation lens /// navigate; a client without it still gets the sites back as the /// command's result. pub show_document: bool, /// Whether the client answers `workspace/configuration` — the pull model /// for settings. A client that said nothing is only ever *pushed* /// settings, which is what every client got before this was read. pub configuration: bool, /// Whether the client understands a server-cancelled semantic-tokens /// request (`textDocument.semanticTokens.serverCancelSupport`). Decides /// which error code declines `semanticTokens/full` on a large buffer — /// see `docs/features/large-file-mode/README.md`. pub token_server_cancel: bool, /// Whether the client hosts the custom lucisv hierarchy sidebar and wants /// a notification whenever the installed workspace index changes. pub hierarchy_view: bool, } /// Everything the server owns. pub struct Server { connection: Connection, workspace: Workspace, /// Documents whose `lucisv.toml` problem has already been reported. Cleared /// for a document whenever its text changes, so the warning is said once /// per file change rather than once per format-on-save. config_warnings: HashSet, abilities: ClientAbilities, /// The id of the file-watcher registration in force, if any. Kept so a /// changed `lucisv.filelist` can replace it: the watched filelist path is /// part of the registration, so a new path needs a new registration. watchers: Option, /// Numbers the file-watcher registrations, so a replacement can name the /// one it supersedes. registrations: u32, /// Numbers the requests made *of* the client. A repeated id is a protocol /// error, so this only ever counts up. request_ids: u32, /// The requests the server has made of the client whose answers it will /// act on, by the id they were sent with. Everything *not* in here is a /// request whose answer is ignorable, which is what makes `response`'s /// fall-through correct rather than lossy. pending: HashMap, /// Counts everything that can change what a pull request would answer: a /// buffer's text, and the workspace index. It is the whole of a /// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`. generation: u64, /// Revision of the completed index exposed to the custom hierarchy view. hierarchy_revision: u64, /// The last full-or-delta semantic-token answer for each open buffer — /// what a delta is computed *against*. Dropped on `didClose`, so this /// only ever holds what the editor is showing. See /// `docs/features/semantic-tokens-delta/README.md`. tokens: HashMap, /// Numbers the semantic-token answers. Per answer, not per generation: a /// client's `previousResultId` has to name the exact data it holds, and /// two buffers' answers are never comparable. token_results: u64, /// Numbers the progress tokens the index rescans run under. One rescan is /// one token, and a token is never reused: a client keys the bar it is /// showing off it. indexings: u32, /// Buffers that are text-current but analysis-stale: the newest applied /// text for each, in first-dirtied order. A `didChange` lands here instead /// of running a reparse, and every one of them is flushed — analyzed, /// republished — by the first thing that needs the analysis: the next /// request, the next non-`didChange` notification, or the quiet-period /// timer in `run`. See `docs/features/change-debounce/README.md`. dirty: Vec<(Uri, String)>, /// Everything the client has sent, forwarded off the transport's /// rendezvous channel by [`forward`]. Held here rather than made in `run` /// because a **scan** drains it too: the loop must not go quiet for the /// length of one (`docs/features/scan-interleave/README.md`). queue: std::sync::mpsc::Receiver, /// Whether a scan is running. A message answered mid-scan can ask for /// another one, and this is what turns that into the flag below rather /// than a scan inside a scan. scanning: bool, /// A rescan asked for while a scan was running. Coalesced: any number of /// requests is one more scan when this one ends, whatever asked for them. rescan_wanted: bool, /// Whether the scan now running is one a *message* asked for. The startup /// scan is not — nothing was queued ahead of it — and that is the whole /// difference between a request answered mid-scan and one that waits. See /// [`Server::must_wait`]. answering_a_rescan: bool, /// Whether the client has shut the server down. Set by a `shutdown` /// answered mid-scan, which stops the scan where it stands and keeps `run` /// from taking another message. stopped: bool, /// Messages a mid-scan drain would have answered out of order, kept in /// arrival order until the rescan they are queued behind has run. See /// [`Server::must_wait`] — this is the order contract, not a queue of its /// own. held: Vec, /// `--verbose`: whether every operation says how long it took, in the /// client's log channel. Off is the shipped state and the whole of what it /// costs is the branch that reads this field — see /// [`Server::timer`] and `docs/features/verbose-timing/README.md`. verbose: bool, } /// How long a burst of `didChange` notifications may sit unanalyzed once the /// typing has stopped, before the quiet-period timer flushes them anyway. The /// coalescing this buys — one reparse per burst instead of one per keystroke — /// is worth nothing if diagnostics never arrive until the next request does. const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150); /// How many files a scan must have to be worth answering messages in the /// middle of. /// /// **The whole trade of `docs/features/scan-interleave/README.md`, in one /// number.** A mid-scan answer reads the index as far as the scan has built /// it, so it can be *less* than the answer the same request would get a /// moment later — and that is only ever worth it when "a moment later" is a /// wait a person can feel. Below this, a scan is over in a few milliseconds /// (the 860-file corpus is 340 ms, so sixty-four files is under thirty), and /// trading a complete answer for those milliseconds would be a bad bargain; /// above it, the measured wait is hundreds of milliseconds and the trade is /// the point of the round. /// /// A count rather than a clock deliberately: a rule about elapsed time makes /// what a server answers depend on how loaded the machine was, which is /// exactly the property a test suite — and a bug report — cannot work with. /// The known limit of counting is a workspace of a *few very large* files, /// which is under this bar and can still take a second; that is written down /// as a deliberate not-done rather than papered over with a second rule. const INTERLEAVE_ABOVE: usize = 64; /// A request the server sent the client and still owes itself an answer to. /// /// One map rather than one per kind: `response` then has a single lookup and /// a single `match`, and adding a third kind is a variant the compiler makes /// you handle rather than a map somebody forgets to consult. enum Pending { /// A `workspace/applyEdit`, remembering the command that asked for it so /// a refusal can be named to the user. ApplyEdit(String), /// A `workspace/configuration` asking for the `lucisv` section. Configuration, } /// One semantic-token answer, kept so the next delta request can be answered /// against it. struct TokenAnswer { result_id: String, data: Vec, } impl Server { /// The server, with its first index built. /// /// The startup scan runs at the **default** settings — including the /// folder scope — because neither settings door can deliver anything /// before `initialized`; a client whose `lucisv.index.scope` differs pays /// one extra rescan when its settings land, exactly as `lucisv.exclude` /// has always cost one. pub fn new( connection: Connection, roots: Vec, abilities: ClientAbilities, storage: Option, verbose: bool, ) -> Server { Server::started( connection, roots, abilities, ClientSettings::default(), storage, verbose, Vec::new(), ) } /// [`Server::new`] with a client's settings already in hand — the seam the /// tests start a session from. Only a test has any settings this early: /// one whose subject is not the scope says so here rather than driving a /// `didChangeConfiguration` and then reasoning about the extra rescan it /// buys. /// /// `queued` is what the client had already sent when the server was built /// — the opening burst, put straight onto the queue the startup scan /// drains. Empty for [`Server::new`]; a test fills it because racing the /// forwarder thread for it would make the test a coin toss rather than a /// check. fn started( connection: Connection, roots: Vec, abilities: ClientAbilities, client: ClientSettings, storage: Option, verbose: bool, queued: Vec, ) -> Server { // Started before the first scan, not in `run`: the scan below answers // whatever the client has already sent, and it can only do that off a // queue that is already being filled. let (forwarded, queue) = forward(&connection); for message in queued { let _ = forwarded.send(message); } let mut server = Server { connection, workspace: Workspace::default(), config_warnings: HashSet::new(), abilities, watchers: None, registrations: 0, request_ids: 0, pending: HashMap::new(), generation: 0, hierarchy_revision: 0, tokens: HashMap::new(), token_results: 0, indexings: 0, dirty: Vec::new(), queue, scanning: false, rescan_wanted: false, answering_a_rescan: false, stopped: false, held: Vec::new(), verbose, }; // Nothing has been built yet, so there is no rebuild to owe: the // `true` this returns for a non-default `client` is the rebuild that // is about to happen anyway. let _ = server.workspace.set_client_settings(client); // Before the first build, because it is one rung of the ladder that // decides where that build reads its cache from // (`docs/features/index-persistence/README.md`). server.workspace.set_storage_path(storage); // The earliest legal moment for anything server-initiated: `main` // builds this only after `initialize_finish`, which returns once the // client's `initialized` notification has arrived — and consumes it, // so the loop below never sees one to hang these off instead. The // first index build is the slowest one of the session, so it gets the // same bar every later rescan gets. // // And it answers messages while it runs, which is what stops the first // request of a session waiting out the whole scan // (`docs/features/scan-interleave/README.md`). Everything below it is // therefore reached with the client's opening burst already handled — // and skipped altogether if that burst shut the server down. server.workspace.adopt_roots(roots); let warnings = server.scan_until_settled(false); if server.stopped { return server; } server.hierarchy_index_changed(); // A buffer can now be *opened* during the startup scan, and what was // published for it then was computed against a half-built index. This // is the same debt a rescan pays at the end of `reindex`, owed here // for the first time because before this round no buffer could exist // at this point. Nothing at all is sent when nothing is open, which is // every session whose client did not get a `didOpen` in edgeways. if !server.workspace.open_uris().is_empty() { server.refresh_code_lenses(); server.generation += 1; for uri in server.workspace.open_uris() { server.publish(&uri); } } server.report_scope(warnings); server.register_watchers(); // The pull half of the settings model. Asked here because this is the // same moment the watchers are registered — the earliest legal one — // and answered later, in the loop: the settings therefore arrive // *after* the first index build, exactly as a pushed // `didChangeConfiguration` always has (it cannot arrive before // `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist` // costs one extra rescan when it lands; nothing is stale in between, // it is simply the default scope until the client answers. server.request_configuration(); server } /// Receive until the client shuts us down or the channel closes. /// /// One blocking receive, then everything already queued behind it, then /// that whole burst in arrival order. The drain is what makes /// `$/cancelRequest` mean anything: while a handler runs, the client's /// later requests and its cancels for them pile up together, and a cancel /// found next to its request answers that request for free. /// /// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is /// flushed here rather than left waiting for a request that may never /// come — diagnostics are the one answer the client never asks for. pub fn run(&mut self) -> Result<(), Box> { use std::sync::mpsc::RecvTimeoutError; loop { // A `shutdown` the startup scan answered has already been through // `handle_shutdown`; there is nothing left to receive and nothing // left to answer. if self.stopped { return Ok(()); } // Whatever a scan set aside is answered before anything newer is // taken — the rescan those messages were queued behind has run, // and they are older than everything still on the queue. Handling // them here rather than at the end of the scan is what keeps this // a loop instead of a scan inside a scan inside a scan. if !self.held.is_empty() { let batch = std::mem::take(&mut self.held); if self.process_batch(batch)? { return Ok(()); } continue; } let message = if self.dirty.is_empty() { match self.queue.recv() { Ok(message) => message, Err(_) => return Ok(()), } } else { match self.queue.recv_timeout(CHANGE_DEBOUNCE) { Ok(message) => message, Err(RecvTimeoutError::Timeout) => { self.flush_dirty(); continue; } Err(RecvTimeoutError::Disconnected) => return Ok(()), } }; let batch = burst(&self.queue, message); if self.process_batch(batch)? { return Ok(()); } } } /// Handle one burst in arrival order, reporting whether the client shut us /// down. /// /// Order is the whole contract: a `didChange` queued ahead of a completion /// is applied before that completion is answered, exactly as it would be /// one message at a time. The only thing the burst adds is that a request /// this burst also carries a cancel for is answered `RequestCancelled` /// instead of computed — except `shutdown`, which is honoured before the /// cancelled set is ever consulted, so no cancel can talk the server out /// of shutting down. fn process_batch(&mut self, batch: Vec) -> Result> { let mut cancelled = cancelled_in(&batch); // Where this burst's own held messages have to be spliced in. A scan // this burst starts can hold messages of its *own* — ones that arrived // while it ran, and therefore after everything still in this burst — // so what is held from here goes in front of those and behind whatever // was already waiting when the burst began. let already_waiting = self.held.len(); // The `$/cancelRequest`s this burst has already carried, kept only // long enough to put them back if a request behind them has to wait. let mut consumed_cancels: Vec = Vec::new(); let mut messages = batch.into_iter(); while let Some(message) = messages.next() { // A request that must wait takes everything behind it with it, or // the burst's arrival order would not survive the wait — // `shutdown` included, because a request sent before a shutdown // is a request the client is still owed an answer to. if self.must_wait() && matches!(message, Message::Request(_)) { self.say_held(&message); // The cancels this burst carried were consumed on the way // here, and `cancelled_in` runs again over the held batch — so // they go back in front of what they cancel rather than being // lost. A cancel naming nothing in the held batch is dropped // there exactly as it was dropped here. let mut rest: Vec = std::mem::take(&mut consumed_cancels); rest.push(message); rest.extend(messages); rest.extend(self.held.split_off(already_waiting)); self.held.extend(rest); return Ok(false); } match message { Message::Request(request) => { if self.connection.handle_shutdown(&request)? { return Ok(true); } // Removed as it is used: a second cancel for the same id // then finds nothing, and the set cannot outlive the burst. let response = if cancelled.remove(&request.id) { cancelled_response(request.id) } else { self.request(request) }; self.connection.sender.send(Message::Response(response))?; } // The cancels themselves are consumed here — `notification` // has nothing to do with one, and everything it could do has // already been done above. Kept only so that a request behind // one that has to wait takes its cancel with it. Message::Notification(notification) if notification.method == Cancel::METHOD => { consumed_cancels.push(Message::Notification(notification)); } Message::Notification(notification) => self.notification(notification), Message::Response(response) => self.response(response), } } Ok(false) } /// Whether a request reaching the dispatch right now must wait instead of /// being answered. /// /// **This is the order contract, and it is the one thing interleaving a /// scan with the message loop must not cost.** The loop has always /// promised that everything queued *ahead* of a request is applied before /// that request is answered — a `didChange` before a completion, and /// equally a `didOpen` that widened the scope, a `didSave`, a changed /// setting or an added workspace folder before a go-to-definition. Those /// four ask for a rescan, and "applied" for them means the rescan has /// **run**: one message at a time, the server would have finished it /// before ever taking the request. Three clauses, one rule: /// /// * `answering_a_rescan` — this scan is one a message asked for, so /// every request that arrives while it runs arrived *after* that /// message and is owed its effect; /// * `rescan_wanted` — a message in this very burst has just asked for /// one, and the requests behind it in the burst are owed the same; /// * `held` — a request is already waiting, and answering a newer one /// ahead of it would reorder them just as badly. /// /// What is left answered mid-scan is exactly what is queued behind /// *nothing*: the opening burst of a session, whose scan is the server's /// own startup and not something a message asked for. That is the case /// the round is about, and it is the one a user feels /// (`docs/features/scan-interleave/README.md`). fn must_wait(&self) -> bool { self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty() } /// Whether the installed index covers the whole scope with no indexing /// work outstanding — what the hierarchy snapshot reports as `complete`. /// /// **Both clauses, not just `scanning`.** `!self.scanning` alone would be /// answering "is a scan running *this instant*", and a snapshot taken /// between a finished scan and a rescan already asked for would call a /// stale index complete. Today [`Server::must_wait`] makes that /// unreachable — a request arriving with `rescan_wanted` set or anything /// `held` is set aside rather than answered, so a snapshot only ever /// reaches this function when both are already clear, and `rescan_wanted` /// is in any case only ever set while `scanning` is true. Saying it here /// anyway costs nothing and means the honesty of the flag does not depend /// on a scheduling invariant two hundred lines away staying true; a /// hypothetical future exemption from `must_wait` would degrade the flag, /// not break it. Pinned by /// `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`. fn index_is_complete(&self) -> bool { !self.scanning && !self.must_wait() } }