use std::io::{self, BufRead, Write};
use std::panic::{self, AssertUnwindSafe};
use std::sync::Mutex;
use std::thread;
use serde_json::Value;
use super::session::{Asked, Session, Setup};
use super::tool::{Answer, Blocking, Card, Tool};
use crate::sync::lock;
use crate::{CancellationToken, Error, Result};
#[derive(Debug)]
#[must_use = "a server answers with serve()"]
pub struct Server {
setup: Setup,
tools: Vec<Tool>,
}
impl Server {
pub(super) fn new(name: &str, version: &str) -> Server {
Server { setup: Setup::new(name, version), tools: Vec::new() }
}
pub fn instructions(mut self, text: &str) -> Server {
self.setup.instructions = Some(text.to_owned());
self
}
pub fn tool(mut self, tool: Tool) -> Server {
self.tools.push(tool);
self
}
pub fn tools(mut self, tools: impl IntoIterator<Item = Tool>) -> Server {
self.tools.extend(tools);
self
}
pub fn allow<'a>(mut self, given: impl Into<Option<&'a str>>) -> Server {
self.setup.allowed = given.into().map(str::to_owned);
self
}
pub fn serve(self) -> Result<()> {
self.serve_on(io::stdin().lock(), io::stdout())
}
#[doc(hidden)]
pub fn serve_on(self, input: impl BufRead, output: impl Write + Send) -> Result<()> {
let (cards, handlers): (Vec<Card>, Vec<Blocking>) =
self.tools.into_iter().map(|tool| (tool.card, tool.handler)).unzip();
let session = Session::of(self.setup, cards)?;
let answers = Lines::to(output);
let (session, handlers, lines) = (&session, &handlers, &answers);
let read = thread::scope(|calls| {
for line in input.lines() {
let line = line.map_err(|error| Error::io("mcp: stdin", error))?;
match session.received(&line) {
Asked::Answer(answer) => answer.iter().for_each(|answer| lines.write(answer)),
Asked::Call(call) => {
calls.spawn(move || {
let ran = ran(&handlers[call.tool], &call.arguments, &call.token);
session.finished(call, ran).iter().for_each(|answer| lines.write(answer));
});
}
}
if lines.stopped() {
break;
}
}
if lines.stopped() {
session.cancel_all();
}
Ok(())
});
read.and(answers.ended())
}
}
pub(crate) fn ran(handler: &Blocking, arguments: &Value, token: &CancellationToken) -> thread::Result<Answer> {
panic::catch_unwind(AssertUnwindSafe(|| token.run(|| handler(arguments, token))))
}
pub(crate) struct Lines<W> {
output: Mutex<Output<W>>,
}
struct Output<W> {
to: W,
failed: Option<io::Error>,
}
impl<W: Write> Lines<W> {
pub(crate) fn to(output: W) -> Lines<W> {
Lines { output: Mutex::new(Output { to: output, failed: None }) }
}
pub(crate) fn write(&self, answer: &Value) {
let mut output = lock(&self.output);
if output.failed.is_some() {
return;
}
let line = format!("{answer}\n");
let to = &mut output.to;
if let Err(error) = to.write_all(line.as_bytes()).and_then(|()| to.flush()) {
output.failed = Some(error);
}
}
pub(crate) fn stopped(&self) -> bool {
lock(&self.output).failed.is_some()
}
pub(crate) fn ended(&self) -> Result<()> {
match lock(&self.output).failed.take() {
Some(error) if error.kind() != io::ErrorKind::BrokenPipe => Err(Error::io("mcp: stdout", error)),
_ => Ok(()),
}
}
}
#[cfg(test)]
#[path = "server_tests.rs"]
mod tests;