use std::collections::HashMap;
use std::io::{self, BufRead, Write};
use std::path::PathBuf;
use std::sync::mpsc::{self, RecvTimeoutError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::capabilities::{self, Session};
use crate::catalog::{self, Catalog};
use crate::document::Documents;
use crate::framing;
use crate::intel::{ParsedCache, World};
use crate::lifecycle::{Event, Phase, Reply, Request, request_allowed, transition};
use crate::navigation::{self, Lines};
use crate::position::Position;
use crate::project::{self, UserConfig};
use crate::semantic;
use crate::trust::{self, Trust};
use crate::workspace::Workspace;
mod diagnostics;
mod refactoring;
#[derive(Clone, Debug, Default)]
pub struct Options {
pub emacs: Option<PathBuf>,
}
enum Loader<T> {
Idle,
Running(JoinHandle<(T, Vec<String>)>),
Ready(T),
}
impl<T> Loader<T> {
fn finish(&mut self, log: &mut dyn Write) {
if let Loader::Running(_) = self {
let Loader::Running(handle) = std::mem::replace(self, Loader::Idle) else {
unreachable!("the loader is running");
};
match handle.join() {
Ok((value, messages)) => {
for message in messages {
let _ = writeln!(log, "{message}");
}
*self = Loader::Ready(value);
}
Err(_) => {
let _ = writeln!(log, "A background loader panicked");
}
}
}
}
fn get(&self) -> Option<&T> {
match self {
Loader::Ready(value) => Some(value),
_ => None,
}
}
fn get_mut(&mut self) -> Option<&mut T> {
match self {
Loader::Ready(value) => Some(value),
_ => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq)]
#[serde(untagged)]
enum Id {
Number(i32),
String(String),
}
struct Server<'a> {
phase: Phase,
session: Option<Session>,
documents: Documents,
pending: HashMap<Id, Request>,
workspaces: Vec<PathBuf>,
config_dir: Option<PathBuf>,
trust: Trust,
log: &'a mut dyn Write,
options: Options,
client: Value,
cache_dir: Option<PathBuf>,
catalog: Loader<Option<Catalog>>,
workspace: Loader<Workspace>,
pending_changes: Vec<PathBuf>,
parsed: ParsedCache,
semantic: HashMap<String, (String, Vec<u32>)>,
result_ids: u64,
diagnostics: diagnostics::Diagnostics,
outbox: Vec<Value>,
reload_environment: bool,
}
impl<'a> Server<'a> {
fn new(log: &'a mut dyn Write, options: Options) -> Self {
let config_dir = match trust::config_dir() {
Ok(dir) => Some(dir),
Err(err) => {
let _ = writeln!(log, "Could not locate the trusted roots: {err}");
None
}
};
Self {
phase: Phase::Fresh,
session: None,
documents: Documents::default(),
pending: HashMap::new(),
workspaces: Vec::new(),
config_dir,
trust: Trust::default(),
log,
options,
client: Value::Null,
cache_dir: catalog::cache_dir().ok(),
catalog: Loader::Idle,
workspace: Loader::Idle,
pending_changes: Vec::new(),
parsed: ParsedCache::default(),
semantic: HashMap::new(),
result_ids: 0,
diagnostics: diagnostics::Diagnostics::default(),
outbox: Vec::new(),
reload_environment: false,
}
}
fn start_loaders(&mut self) {
let user = match self.config_dir.as_deref().map(UserConfig::load) {
Some(Ok(config)) => config,
Some(Err(err)) => {
let _ = writeln!(self.log, "Could not read the user configuration: {err}");
UserConfig::default()
}
None => UserConfig::default(),
};
let explicit = self.options.emacs.clone();
let configured = user.emacs_path.clone();
let roots = self.workspaces.clone();
let cache = self.cache_dir.clone();
self.catalog = Loader::Running(std::thread::spawn(move || {
let mut messages = Vec::new();
let emacs =
match catalog::locate_emacs(explicit.as_deref(), configured.as_deref(), &roots) {
Ok(emacs) => emacs,
Err(err) => {
messages.push(format!("No Emacs catalog: {err}"));
return (None, messages);
}
};
let Some(cache) = cache else {
messages.push("No Emacs catalog: no cache directory".to_owned());
return (None, messages);
};
match Catalog::load_or_build(&emacs, &cache, false) {
Ok(built) => {
messages.push(format!(
"Emacs catalog for {} ({}) {} in {} ms",
emacs.display(),
built.catalog.data.version,
if built.cached { "loaded" } else { "built" },
built.duration.as_millis()
));
(Some(built.catalog), messages)
}
Err(err) => {
messages.push(format!("No Emacs catalog: {err}"));
(None, messages)
}
}
}));
let environments: Vec<_> = self
.workspaces
.iter()
.map(|root| {
let inputs = project::Inputs {
user: &user,
emacs_version: None,
trusted: self.trust.permits(root, &[]),
emacs_load_path: std::env::var_os("EMACSLOADPATH"),
};
project::resolve(root, &inputs)
})
.collect();
self.workspace = Loader::Running(std::thread::spawn(move || {
let workspace = Workspace::build(environments, true);
let mut messages = Vec::new();
for env in &workspace.environments {
for note in &env.notes {
messages.push(format!("{}: {note}", env.root.display()));
}
}
messages.push(format!(
"Indexed {} files in {} workspace roots",
workspace.len(),
workspace.environments.len()
));
(workspace, messages)
}));
}
fn loaders_ready(&self) -> bool {
self.catalog.get().is_some() && self.workspace.get().is_some()
}
fn ensure_loaded(&mut self) {
let ready = self.loaders_ready();
self.catalog.finish(self.log);
self.workspace.finish(self.log);
if let Some(workspace) = self.workspace.get_mut() {
for path in self.pending_changes.drain(..) {
workspace.mark_changed(path);
}
let updated = workspace.refresh();
if updated > 0 {
self.dependencies_changed();
return;
}
}
if !ready && self.loaders_ready() {
self.update_static_diagnostics();
}
}
fn tick(&mut self) {
if !request_allowed(self.phase) {
return;
}
self.check_trust(false);
self.refresh_loaded();
self.poll_oracle();
}
fn refresh_loaded(&mut self) {
if let Loader::Running(handle) = &self.catalog
&& handle.is_finished()
{
self.catalog.finish(self.log);
self.update_static_diagnostics();
}
if let Loader::Running(handle) = &self.workspace
&& handle.is_finished()
{
self.workspace.finish(self.log);
self.update_static_diagnostics();
}
if self.loaders_ready() {
if std::mem::take(&mut self.reload_environment) {
self.start_loaders();
self.update_static_diagnostics();
} else {
self.ensure_loaded();
}
}
}
fn mark_changed(&mut self, uri: &str) {
if let Some(path) = url::Url::parse(uri)
.ok()
.and_then(|url| url.to_file_path().ok())
{
match self.workspace.get_mut() {
Some(workspace) => workspace.mark_changed(path),
None => self.pending_changes.push(path),
}
}
}
fn world(&self) -> Option<World<'_>> {
let session = self.session.as_ref()?;
Some(World {
documents: &self.documents,
workspace: self.workspace.get(),
catalog: self.catalog.get().and_then(Option::as_ref),
cache: self.cache_dir.as_deref(),
parsed: &self.parsed,
encoding: capabilities::position_encoding(session),
client: &self.client,
})
}
fn enter(&mut self, event: Event) -> bool {
let Some(next) = transition(self.phase, event) else {
return false;
};
self.phase = next;
true
}
fn refresh_trust(&mut self) {
if let Err(err) = self.trust.refresh(self.config_dir.as_deref()) {
let _ = writeln!(self.log, "Could not read the trusted roots: {err}");
}
let trusted = self
.workspaces
.iter()
.filter(|workspace| self.trust.permits(workspace, &[]))
.count();
let _ = writeln!(
self.log,
"Trust epoch {}, {trusted}/{} file workspace roots trusted",
self.trust.epoch(),
self.workspaces.len()
);
}
fn initialize(&mut self, params: Value) -> Result<Value, (i32, &'static str)> {
let capabilities = params
.get("capabilities")
.filter(|value| value.is_object())
.ok_or((-32602, "Invalid initialize parameters"))?;
if !self.enter(Event::Initialize) {
return Err((-32600, "Initialize has already been received"));
}
self.workspaces = workspace_roots(¶ms);
self.refresh_trust();
self.client = capabilities.clone();
let session = capabilities::negotiate(capabilities);
let mut result = json!({
"capabilities": {
"positionEncoding": session.encoding,
"textDocumentSync": {
"openClose": true,
"change": 2,
"save": {"includeText": false}
},
"documentSymbolProvider": true,
"definitionProvider": true,
"declarationProvider": true,
"referencesProvider": true,
"documentHighlightProvider": true,
"foldingRangeProvider": true,
"selectionRangeProvider": true,
"renameProvider": if capabilities.pointer("/textDocument/rename/prepareSupport")
.and_then(Value::as_bool) == Some(true) {
json!({"prepareProvider": true})
} else {
json!(true)
},
"documentFormattingProvider": true,
"documentRangeFormattingProvider": true,
"documentOnTypeFormattingProvider": {
"firstTriggerCharacter": "\n", "moreTriggerCharacter": [")", "]"]
},
"callHierarchyProvider": true,
"hoverProvider": true,
"completionProvider": {
"resolveProvider": true,
"triggerCharacters": ["(", "'", ":"]
},
"signatureHelpProvider": {
"triggerCharacters": ["(", " "],
"retriggerCharacters": [" "]
},
"semanticTokensProvider": {
"legend": {
"tokenTypes": semantic::TOKEN_TYPES,
"tokenModifiers": semantic::TOKEN_MODIFIERS
},
"range": true,
"full": {"delta": true}
},
"inlayHintProvider": {"resolveProvider": true},
"workspaceSymbolProvider": true,
"executeCommandProvider": {"commands": ["elsmith.expandMacro"]}
},
"serverInfo": {"name": "elsmith", "version": env!("CARGO_PKG_VERSION")}
});
if self.pull_diagnostics() {
result["capabilities"]["diagnosticProvider"] = json!({
"identifier": "elsmith", "interFileDependencies": true, "workspaceDiagnostics": true
});
}
if self
.client
.pointer("/textDocument/codeAction/codeActionLiteralSupport")
.is_some_and(Value::is_object)
{
result["capabilities"]["codeActionProvider"] = json!({
"codeActionKinds": ["quickfix", "refactor.rewrite"], "resolveProvider": true
});
}
self.session = Some(session);
self.start_loaders();
Ok(result)
}
fn request(&mut self, method: &str, params: Value) -> Result<Value, (i32, &'static str)> {
if matches!(self.phase, Phase::Stopped | Phase::Exited) {
return Err((-32600, "The server has shut down"));
}
if method == "initialize" {
return self.initialize(params);
}
if !request_allowed(self.phase) {
return Err((-32002, "The server is not initialized"));
}
match method {
"shutdown" if empty_params(¶ms) && self.enter(Event::Shutdown) => {
self.stop_oracle((-32800, "The server has shut down"));
Ok(Value::Null)
}
"shutdown" => Err((-32602, "Invalid shutdown parameters")),
"textDocument/diagnostic" => {
self.check_trust(false);
self.refresh_loaded();
self.diagnostic_request(¶ms)
}
"workspace/diagnostic" => {
self.check_trust(false);
self.refresh_loaded();
self.workspace_diagnostics(¶ms)
}
"textDocument/codeAction" => {
self.refresh_loaded();
self.code_actions(¶ms)
}
"codeAction/resolve" => self.resolve_code_action(params),
"textDocument/prepareRename"
| "textDocument/rename"
| "textDocument/formatting"
| "textDocument/rangeFormatting"
| "textDocument/onTypeFormatting"
| "textDocument/prepareCallHierarchy"
| "callHierarchy/incomingCalls"
| "callHierarchy/outgoingCalls" => self.refactor(method, ¶ms),
"textDocument/documentSymbol"
| "textDocument/documentHighlight"
| "textDocument/foldingRange"
| "textDocument/selectionRange" => self.navigate(method, ¶ms),
"textDocument/definition"
| "textDocument/declaration"
| "textDocument/references"
| "textDocument/hover"
| "textDocument/completion"
| "completionItem/resolve"
| "textDocument/signatureHelp"
| "textDocument/semanticTokens/full"
| "textDocument/semanticTokens/full/delta"
| "textDocument/semanticTokens/range"
| "textDocument/inlayHint"
| "inlayHint/resolve"
| "workspace/symbol" => {
self.ensure_loaded();
self.intelligence(method, params)
}
_ => Err((-32601, "Method not found")),
}
}
fn navigate(&self, method: &str, params: &Value) -> Result<Value, (i32, &'static str)> {
const INVALID: (i32, &str) = (-32602, "Invalid parameters");
let uri = params
.pointer("/textDocument/uri")
.and_then(Value::as_str)
.ok_or(INVALID)?;
let position = || {
params
.get("position")
.and_then(|value| serde_json::from_value::<Position>(value.clone()).ok())
.ok_or(INVALID)
};
let Some(document) = self.documents.get(uri) else {
return Ok(match method {
"textDocument/definition" | "textDocument/declaration" => Value::Null,
_ => json!([]),
});
};
let session = self.session.as_ref().ok_or(INVALID)?;
let lines = Lines::new(&document.text, capabilities::position_encoding(session));
let analysis = || document.analysis();
Ok(match method {
"textDocument/documentSymbol" => {
navigation::document_symbols(&document.text, &lines, analysis())
}
"textDocument/definition" => {
navigation::definition(uri, &lines, analysis(), position()?, false)
}
"textDocument/declaration" => {
navigation::definition(uri, &lines, analysis(), position()?, true)
}
"textDocument/references" => {
let include = params
.pointer("/context/includeDeclaration")
.and_then(Value::as_bool)
.unwrap_or(false);
navigation::references(uri, &lines, analysis(), position()?, include)
}
"textDocument/documentHighlight" => {
navigation::highlight(&lines, analysis(), position()?)
}
"textDocument/foldingRange" => {
navigation::folding_ranges(&document.text, &document.tree, &lines)
}
_ => {
let positions: Vec<Position> = params
.get("positions")
.and_then(|value| serde_json::from_value(value.clone()).ok())
.ok_or(INVALID)?;
navigation::selection_ranges(&document.tree, &lines, &positions)
.unwrap_or(Value::Null)
}
})
}
fn intelligence(&mut self, method: &str, params: Value) -> Result<Value, (i32, &'static str)> {
const INVALID: (i32, &str) = (-32602, "Invalid parameters");
let uri = params
.pointer("/textDocument/uri")
.and_then(Value::as_str)
.map(str::to_owned);
let position = || {
params
.get("position")
.and_then(|value| serde_json::from_value::<Position>(value.clone()).ok())
.ok_or(INVALID)
};
let additional = self
.session
.as_ref()
.is_some_and(|session| session.additional_text_edits);
let world = self.world().ok_or(INVALID)?;
let range = |uri: &str| -> Option<(usize, usize)> {
let text = &self.documents.get(uri)?.text;
let lines = Lines::new(text, world.encoding);
let read = |key: &str| {
params
.pointer(&format!("/range/{key}"))
.and_then(|value| serde_json::from_value::<Position>(value.clone()).ok())
.and_then(|position| lines.offset(position))
};
Some((read("start")?, read("end").unwrap_or(text.len())))
};
match method {
"completionItem/resolve" => {
return Ok(world.resolve_completion(params.clone(), additional));
}
"inlayHint/resolve" => return Ok(world.resolve_inlay_hint(params.clone())),
"workspace/symbol" => {
let query = params.get("query").and_then(Value::as_str).ok_or(INVALID)?;
return Ok(world.workspace_symbols(query));
}
_ => {}
}
let uri = uri.ok_or(INVALID)?;
Ok(match method {
"textDocument/definition" => world.definition(&uri, position()?, false),
"textDocument/declaration" => world.definition(&uri, position()?, true),
"textDocument/references" => {
let include = params
.pointer("/context/includeDeclaration")
.and_then(Value::as_bool)
.unwrap_or(false);
world.references(&uri, position()?, include)
}
"textDocument/hover" => world.hover(&uri, position()?),
"textDocument/completion" => world.completion(&uri, position()?),
"textDocument/signatureHelp" => world.signature_help(&uri, position()?),
"textDocument/inlayHint" => {
let Some(range) = range(&uri) else {
return Ok(json!([]));
};
world.inlay_hints(&uri, range)
}
"textDocument/semanticTokens/range" => {
let Some(range) = range(&uri) else {
return Ok(json!({"data": []}));
};
json!({"data": world.semantic_tokens(&uri, Some(range)).unwrap_or_default()})
}
_ => {
let Some(data) = world.semantic_tokens(&uri, None) else {
return Ok(json!({"data": []}));
};
let previous = params
.get("previousResultId")
.and_then(Value::as_str)
.map(str::to_owned);
self.result_ids += 1;
let id = self.result_ids.to_string();
let delta = match (method, previous, self.semantic.get(&uri)) {
(
"textDocument/semanticTokens/full/delta",
Some(previous),
Some((last, old)),
) if *last == previous => {
let prefix = old.iter().zip(&data).take_while(|(a, b)| a == b).count();
let suffix = old[prefix..]
.iter()
.rev()
.zip(data[prefix..].iter().rev())
.take_while(|(a, b)| a == b)
.count();
let edits = if old == &data {
json!([])
} else {
json!([{
"start": prefix,
"deleteCount": old.len() - prefix - suffix,
"data": data[prefix..data.len() - suffix],
}])
};
Some(json!({"resultId": id, "edits": edits}))
}
_ => None,
};
let result = delta.unwrap_or_else(|| json!({"resultId": id, "data": data}));
self.semantic.insert(uri, (id, data));
result
}
})
}
fn notify(&mut self, method: &str, params: Value) -> Option<Value> {
if method == "initialized" && empty_params(¶ms) {
self.enter(Event::Initialized);
return None;
}
if !request_allowed(self.phase) {
return None;
}
match method {
"textDocument/didOpen"
| "textDocument/didChange"
| "textDocument/didSave"
| "textDocument/didClose" => {
let uri = params
.pointer("/textDocument/uri")
.and_then(Value::as_str)
.map(str::to_owned);
let applied = match method {
"textDocument/didOpen" => self.documents.open(params),
"textDocument/didChange" => {
let encoding = capabilities::position_encoding(self.session.as_ref()?);
self.documents.change(params, encoding)
}
"textDocument/didSave" => self.documents.save(params),
"textDocument/didClose" => self.documents.close(params),
_ => unreachable!(),
};
if let (Some(uri), Some(())) = (uri, applied) {
match method {
"textDocument/didOpen" => self.diagnostic_open(&uri),
"textDocument/didChange" => self.diagnostic_change(&uri),
"textDocument/didSave" => {
self.mark_changed(&uri);
self.diagnostic_save(&uri);
}
"textDocument/didClose" => {
self.semantic.remove(&uri);
self.mark_changed(&uri);
self.diagnostic_close(&uri);
}
_ => unreachable!(),
}
} else {
let _ = writeln!(self.log, "Ignored invalid {method} notification");
}
}
"workspace/didChangeWatchedFiles" => {
if let Some(changes) = params.get("changes").and_then(Value::as_array) {
for uri in changes
.iter()
.filter_map(|change| change.get("uri").and_then(Value::as_str))
{
self.mark_changed(uri);
}
self.dependencies_changed();
}
}
"workspace/didChangeConfiguration" => self.diagnostic_config_changed(),
"window/workDoneProgress/cancel" => {
if let Some(token) = params.get("token").and_then(Value::as_str) {
self.cancel_oracle(None, Some(token));
}
}
"$/cancelRequest" => {
let value = params.get("id")?;
let id = serde_json::from_value(value.clone()).ok()?;
if self.cancel_oracle(Some(&id), None) {
return None;
}
if matches!(
self.pending.remove(&id)?.claim(true),
Some(Reply::Cancelled)
) {
return Some(error(value, -32800, "Request cancelled"));
}
}
"$/setTrace" => {
if let Some(level @ ("off" | "messages" | "verbose")) =
params.get("value").and_then(Value::as_str)
{
let _ = writeln!(self.log, "Client trace setting: {level}");
}
}
_ => {}
}
None
}
fn dispatch(&mut self, message: Value) -> Dispatch {
let raw_id = message.get("id");
let id = raw_id.and_then(|value| serde_json::from_value::<Id>(value.clone()).ok());
let valid_id = id.as_ref().and(raw_id).unwrap_or(&Value::Null);
let method = message.get("method").and_then(Value::as_str);
if method.is_none()
&& message.get("jsonrpc").and_then(Value::as_str) == Some("2.0")
&& (message.get("result").is_some() ^ message.get("error").is_some())
&& let Some(Id::String(id)) = &id
&& self.diagnostic_response(id, message.get("result").is_some_and(Value::is_null))
{
return Dispatch::Continue;
}
if message.get("jsonrpc").and_then(Value::as_str) != Some("2.0")
|| method.is_none()
|| (raw_id.is_some() && id.is_none())
|| message.get("result").is_some()
|| message.get("error").is_some()
{
return Dispatch::Reply(error(valid_id, -32600, "Invalid Request"));
}
let method = method.expect("a method was checked");
let params = message.get("params").cloned().unwrap_or(Value::Null);
if let Some(id) = id {
self.pending.insert(id.clone(), Request::default());
let result = if method == "workspace/executeCommand"
&& params.get("command").and_then(Value::as_str) == Some("elsmith.expandMacro")
&& request_allowed(self.phase)
{
match self.expand_macro(¶ms, id.clone(), valid_id.clone()) {
Ok(None) => return Dispatch::Continue,
Ok(Some(result)) => Ok(result),
Err(err) => Err(err),
}
} else {
self.request(method, params)
};
let response = match result {
Ok(result) => json!({"jsonrpc": "2.0", "id": valid_id, "result": result}),
Err((code, message)) => error(valid_id, code, message),
};
if let Some(request) = self.pending.remove(&id)
&& matches!(request.claim(false), Some(Reply::Finished))
{
return Dispatch::Reply(response);
}
return Dispatch::Continue;
}
if method == "exit" && empty_params(¶ms) {
let code = i32::from(!matches!(self.phase, Phase::Stopped));
self.enter(Event::Exit);
return Dispatch::Exit(code);
}
self.notify(method, params)
.map_or(Dispatch::Continue, Dispatch::Reply)
}
}
enum Dispatch {
Continue,
Reply(Value),
Exit(i32),
}
fn empty_params(params: &Value) -> bool {
params.is_null() || params.as_object().is_some_and(|object| object.is_empty())
}
fn error(id: &Value, code: i32, message: &str) -> Value {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
}
fn workspace_roots(params: &Value) -> Vec<PathBuf> {
let to_path = |value: &Value| {
let uri = url::Url::parse(value.as_str()?).ok()?;
uri.to_file_path().ok()
};
if let Some(folders) = params.get("workspaceFolders").and_then(Value::as_array) {
folders
.iter()
.filter_map(|folder| folder.get("uri").and_then(to_path))
.collect()
} else if let Some(path) = params.get("rootUri").and_then(to_path) {
vec![path]
} else {
params
.get("rootPath")
.and_then(Value::as_str)
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.into_iter()
.collect()
}
}
pub fn check_source(text: &str, catalog: Option<&Catalog>) -> Vec<Value> {
let tree = crate::syntax::Tree::parse_str(text);
let analysis = crate::analysis::analyze(text, &tree);
let view = crate::intel::View {
uri: "untitled:check-file",
text,
tree: &tree,
analysis: &analysis,
};
let world = World {
documents: &Documents::default(),
workspace: None,
catalog,
cache: None,
parsed: &ParsedCache::default(),
encoding: crate::position::Encoding::Utf16,
client: &Value::Null,
};
crate::diagnostics::collect(&world, view)
.0
.into_iter()
.map(|diagnostic| {
let item = diagnostic.value;
json!({
"Severity": if item["severity"] == 1 { "error" } else { "warning" },
"Source": item["source"],
"Code": item["code"],
"Line": item["range"]["start"]["line"],
"Character": item["range"]["start"]["character"],
"Message": item["message"]
})
})
.collect()
}
pub fn run(
mut input: impl BufRead + Send + 'static,
mut output: impl Write,
log: &mut dyn Write,
options: Options,
) -> io::Result<i32> {
let (sender, receiver) = mpsc::sync_channel(16);
std::thread::spawn(move || {
loop {
let frame = framing::read(&mut input);
let done = !matches!(frame, Ok(Some(_)));
if sender.send(frame).is_err() || done {
break;
}
}
});
let mut server = Server::new(log, options);
let idle_interval = Duration::from_millis(50);
let oracle_interval = Duration::from_millis(10);
let mut next_tick = Instant::now() + idle_interval;
loop {
match receiver.recv_timeout(next_tick.saturating_duration_since(Instant::now())) {
Ok(frame) => {
let Some(frame) = frame? else {
break;
};
match serde_json::from_slice::<Value>(&frame) {
Ok(message) => match server.dispatch(message) {
Dispatch::Continue => {}
Dispatch::Reply(response) => framing::write(&mut output, &response)?,
Dispatch::Exit(code) => return Ok(code),
},
Err(_) => {
framing::write(&mut output, &error(&Value::Null, -32700, "Parse error"))?
}
}
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => break,
}
if Instant::now() >= next_tick {
server.tick();
let interval = if server.oracle_pending() {
oracle_interval
} else {
idle_interval
};
next_tick = Instant::now() + interval;
}
for message in server.outbox.drain(..) {
framing::write(&mut output, &message)?;
}
}
Ok(1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pending_cancellation_emits_one_error_and_suppresses_a_later_completion() {
let mut log = io::sink();
let mut server = Server::new(&mut log, Options::default());
server.enter(Event::Initialize);
server.enter(Event::Initialized);
let id = Id::Number(3);
server.pending.insert(id.clone(), Request::default());
let cancel = json!({"jsonrpc": "2.0", "method": "$/cancelRequest", "params": {"id": 3}});
let Dispatch::Reply(response) = server.dispatch(cancel.clone()) else {
panic!("the pending request should be cancelled");
};
assert_eq!(response, error(&json!(3), -32800, "Request cancelled"));
assert!(server.pending.remove(&id).is_none());
assert!(matches!(server.dispatch(cancel), Dispatch::Continue));
}
}