//! Reading a burst of messages before any of it is served. //! //! `lsp-server` hands messages over a rendezvous channel, one at a time; the //! forwarder here moves them onto a queue of our own so that "everything the //! client has already sent" is a question with an answer. The rest of the //! file reads a burst without handling anything in it: which requests it //! cancels, which files it opens, and — for a `didOpen` — whether the index //! scope grew, stayed, or has to be rebuilt. The loop in `mod.rs` and the //! mid-scan drain in `index.rs` both read bursts through here, which is why //! this is its own file rather than part of either. use std::collections::HashSet; use lsp_server::{Connection, Message, RequestId, Response}; use lsp_types::notification::{Cancel, DidOpenTextDocument, Notification as _}; use lsp_types::request::{Request as _, Shutdown}; use lsp_types::{CancelParams, NumberOrString}; use super::dispatch::document_uri; /// Whether this message is the `shutdown` request. `lsp-server` keeps its own /// answer to that question private, so it is asked here by method name — the /// same name `handle_shutdown` matches on. pub(super) fn is_shutdown(message: &Message) -> bool { matches!(message, Message::Request(request) if request.method == Shutdown::METHOD) } /// Move the incoming messages onto a queue of our own, and report it. /// /// Necessary because `lsp-server`'s transport hands messages over /// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding one /// message until this loop takes it, so a client's backlog never sits on /// `connection.receiver` at all: it sits in the OS pipe, invisible and one /// message deep. Forwarding onto an unbounded queue is what makes "everything /// already sent" observable without blocking, which is the whole premise of /// [`burst`] — and of the drain a scan does between two of its files. /// /// The forwarder stops at `shutdown` and never reads past it, because /// `handle_shutdown` reads the `exit` notification off the *connection* /// itself — a forwarder that kept going would steal it and strand the /// handshake for thirty seconds. It owns nothing but messages in flight and /// touches no server state — and it never parses, which is why it is the one /// thread the server spawns without `vlog_parser::PARSE_STACK_SIZE` /// (`docs/features/recursion-limit`). pub(super) fn forward( connection: &Connection, ) -> (std::sync::mpsc::Sender, std::sync::mpsc::Receiver) { let (sender, receiver) = std::sync::mpsc::channel(); let source = connection.receiver.clone(); let ours = sender.clone(); // A failed spawn would leave the server unable to receive anything at // all; there is nothing useful to do with that but let `run` end when the // queue's sender is dropped. let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || { while let Ok(message) = source.recv() { let last = is_shutdown(&message); if sender.send(message).is_err() || last { break; } } }); (ours, receiver) } /// `first` plus everything already waiting on the queue behind it — the /// client's backlog, in arrival order. Never blocks: what is not there yet /// belongs to the next burst. pub(super) fn burst(queue: &std::sync::mpsc::Receiver, first: Message) -> Vec { let mut batch = vec![first]; while let Ok(message) = queue.try_recv() { batch.push(message); } batch } /// The ids this burst cancels: every `$/cancelRequest` in it that names a /// request the burst *also* carries. /// /// A cancel naming anything else is dropped right here — it refers to a /// request answered in some earlier burst, or to one this server never /// received, and either way there is nothing left to cancel. That is what /// keeps this from becoming a set that grows for the life of the session. pub(super) fn cancelled_in(batch: &[Message]) -> HashSet { let queued: HashSet<&RequestId> = batch .iter() .filter_map(|message| match message { Message::Request(request) => Some(&request.id), _ => None, }) .collect(); batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect() } /// The request id a `$/cancelRequest` names, or `None` for any other message. /// Both id forms the protocol allows are read; a cancel whose params do not /// parse is dropped, because there is no id to act on. pub(super) fn cancelled_id(message: &Message) -> Option { let Message::Notification(notification) = message else { return None }; if notification.method != Cancel::METHOD { return None; } let params: CancelParams = serde_json::from_value(notification.params.clone()).ok()?; Some(match params.id { NumberOrString::Number(number) => RequestId::from(number), NumberOrString::String(text) => RequestId::from(text), }) } /// What a cancelled request is answered with. Every request gets exactly one /// response, cancelled or not — the protocol's own `RequestCancelled` /// (-32800), which a client reads as "the one you asked me to drop" rather /// than as a failure worth showing the user. pub(super) fn cancelled_response(id: RequestId) -> Response { Response::new_err( id, lsp_server::ErrorCode::RequestCanceled as i32, "lucisv: request cancelled by the client".to_string(), ) } /// What a `didOpen` did to the index scope, and therefore which of the three /// answers it is owed. #[derive(Debug, PartialEq, Eq)] pub(super) enum Widen { /// The scope did not move: the file is in a folder already covered, or the /// rung in force is one an open buffer cannot widen (a filelist, or the /// whole-workspace walk). Publish and index nothing. Nothing, /// Folders were added and nothing else changed — the cheap path, indexing /// only what the added folders bring in /// ([`Server::reindex_widened`](super::Server::reindex_widened)). Added(Vec), /// Anything else. The whole rescan, which is always a correct answer. Whole, } /// Which of the three [`Widen`] answers a move from `before` to `after` is. /// /// **The chooser, and it is deliberately narrow**: only a scope that grew and /// lost nothing takes the incremental path, because that is the only shape /// whose result is the whole rescan's by construction — a directory that left /// the scope can take files out of the index, and working out *which* files is /// the walk the widen exists not to do. Nothing in the server takes a directory /// out of the folder scope today (`opened_dirs` only grows, and a `didClose` /// costs no rescan at all), so the third arm is a rule kept rather than a case /// reached; a future shrink gets a correct answer instead of a subtle one. /// /// **A directory that subsumes one already in scope is an add** (2026-08-29, /// `docs/features/index-scope/README.md`). At `scopeDepth: 2` the second file a /// user opens routinely raises to a *parent* of the directory the first one /// raised to — opentitan's `hw/ip/aes` then `hw/ip`. That is still a pure add /// here, because every opened directory is raised on its own and the list keeps /// them all: the contained directory is in `after` beside the containing one, /// and nothing was lost. The overlap is not re-read either, because /// `Workspace::begin_widen`'s work list is diffed **by file against what the /// index holds** rather than by folder against the old walk. /// /// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so /// equality is set equality and `contains` is over a handful of directories. pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen { if before == after { return Widen::Nothing; } if before.iter().any(|dir| !after.contains(dir)) { return Widen::Whole; } Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect()) } /// The files a burst opened, in the order the client opened them. /// /// Read off the raw messages rather than off the workspace afterwards, /// because the workspace holds its buffers in a `HashMap` and "which file did /// the user just open" is a question about order. pub(super) fn opened_in(batch: &[Message]) -> Vec { batch .iter() .filter_map(|message| match message { Message::Notification(notification) if notification.method == DidOpenTextDocument::METHOD => { document_uri(¬ification.params) } _ => None, }) .filter_map(|uri| crate::uri::uri_to_path(&uri)) .collect() }