use std::{
fmt,
io::{self, Read, Write},
};
use incremental_lang::Grammar;
use rpc_io::{Cancellation, Config, Decoder, Endpoint, Framing, Gate, Limits};
use crate::{
context::Wire,
error::Error,
handler::Handler,
jobs::{Frontend, router},
outbox::{BufferSink, Outbox},
session::Session,
};
const DEFAULT_MESSAGE_LIMIT: usize = 256 * 1024 * 1024;
const MAX_QUEUED: usize = 4096;
pub struct Server<G, H> {
grammar: G,
handler: H,
limits: Limits,
info: Option<(String, String)>,
custom_requests: Vec<Box<str>>,
custom_notifications: Vec<Box<str>>,
}
impl<G: Grammar + Clone, H: Handler<G>> Server<G, H> {
#[must_use]
pub fn new(grammar: G, handler: H) -> Self {
Self {
grammar,
handler,
limits: limits_for(DEFAULT_MESSAGE_LIMIT),
info: None,
custom_requests: Vec::new(),
custom_notifications: Vec::new(),
}
}
#[must_use]
pub fn with_message_limit(mut self, bytes: usize) -> Self {
self.limits = limits_for(bytes);
self
}
#[must_use]
pub fn with_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
self.info = Some((name.into(), version.into()));
self
}
#[must_use]
pub fn custom_request(mut self, method: &str) -> Self {
self.custom_requests.push(method.into());
self
}
#[must_use]
pub fn custom_notification(mut self, method: &str) -> Self {
self.custom_notifications.push(method.into());
self
}
#[inline]
#[must_use]
pub fn handler(&self) -> &H {
&self.handler
}
pub fn run<R: Read, W: Write>(&mut self, mut input: R, mut output: W) -> Result<(), Error> {
let outbox = Outbox::default();
let config = Config::new()
.with_limits(self.limits)
.with_cancellation(Some(Cancellation::lsp()))
.with_gate(Some(Gate::new("initialize").allow("exit")));
let router = router(&self.custom_requests, &self.custom_notifications);
let mut endpoint =
Endpoint::new(outbox.sink(), router, Frontend::default()).with_config(config);
let wire = Wire::new(endpoint.peer(), outbox.clone());
let mut session = Session::new(
self.grammar.clone(),
&mut self.handler,
wire,
self.info.clone(),
);
let mut transport = Transport {
endpoint: &mut endpoint,
session: &mut session,
outbox: &outbox,
output: &mut output,
};
let outcome = transport.drive(&mut input, &self.limits);
endpoint.close();
let flushed = outbox.write_to(&mut output).map_err(Error::Io);
outcome.and(flushed)
}
}
pub fn serve_stdio<G, H>(grammar: G, handler: H) -> Result<(), Error>
where
G: Grammar + Clone,
H: Handler<G>,
{
Server::new(grammar, handler).run(io::stdin().lock(), io::stdout().lock())
}
fn limits_for(bytes: usize) -> Limits {
Limits::new()
.with_max_message_bytes(bytes)
.with_json(jsonx_lib::Limits::new().with_max_string_bytes(bytes))
}
struct Transport<'a, 'h, G: Grammar, H, W> {
endpoint: &'a mut Endpoint<Frontend, BufferSink>,
session: &'a mut Session<'h, G, H>,
outbox: &'a Outbox,
output: &'a mut W,
}
impl<G: Grammar + Clone, H: Handler<G>, W: Write> Transport<'_, '_, G, H, W> {
fn drive<R: Read>(&mut self, input: &mut R, limits: &Limits) -> Result<(), Error> {
let mut decoder: Decoder = Framing::ContentLength.decoder(limits);
loop {
loop {
match decoder.next_frame() {
Ok(Some(body)) => {
self.endpoint.state_mut().activity = false;
let _flow = self.endpoint.handle(body)?;
let answer = !self.endpoint.state().activity
|| body.trim_ascii_start().first() == Some(&b'[');
self.flush(answer)?;
let front = self.endpoint.state();
if front.eager || front.exit || front.jobs.len() >= MAX_QUEUED {
self.run_queue()?;
}
if let Some(end) = self.session.finished.take() {
return end;
}
}
Ok(None) => break,
Err(error) if error.is_recoverable() => {
self.outbox.refuse_oversized(error);
self.flush(false)?;
}
Err(error) => {
self.run_queue()?;
return Err(Error::Frame(error));
}
}
}
self.run_queue()?;
if let Some(end) = self.session.finished.take() {
return end;
}
let space = decoder.space();
let read = loop {
match input.read(space) {
Ok(n) => break n,
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(Error::Io(error)),
}
};
if read == 0 {
break;
}
decoder.commit(read);
}
self.run_queue()?;
match self.session.finished.take() {
Some(end) => end,
None => Err(Error::Disconnected),
}
}
fn run_queue(&mut self) -> Result<(), Error> {
while let Some(job) = self.endpoint.state_mut().jobs.pop_front() {
self.session.run(job);
self.session.poll_calls();
if let Some(failure) = self.session.wire.failure.take() {
if !matches!(failure, Error::InvalidParams(_)) {
return Err(failure);
}
}
self.flush(true)?;
if self.session.finished.is_some() {
break;
}
}
self.endpoint.state_mut().eager = false;
Ok(())
}
fn flush(&mut self, answer: bool) -> Result<(), Error> {
if answer {
self.session.poll_calls();
}
self.outbox.write_to(self.output).map_err(Error::Io)
}
}
impl<G, H> fmt::Debug for Server<G, H> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Server")
.field("message_limit", &self.limits.max_message_bytes)
.finish_non_exhaustive()
}
}