Skip to main content

docattest_rust/protocol/
server.rs

1//! The loop that serves requests: one JSON value per line in, one per line out.
2
3use super::Hello;
4use serde::de::DeserializeOwned;
5use serde_json::{Value, json};
6use std::io::{BufRead, Write};
7use std::panic::{AssertUnwindSafe, catch_unwind};
8use std::sync::{Arc, Mutex};
9use std::thread::JoinHandle;
10
11/// Why a request has no result.
12#[derive(Debug)]
13pub enum Error {
14    /// A mistake in the project; the core prints the message as it is.
15    User(String),
16    /// A bug in the adapter, or a mistake by the core.
17    Internal(String),
18}
19
20impl Error {
21    /// An internal error from anything that says what went wrong.
22    pub fn internal(why: impl std::fmt::Display) -> Self {
23        Error::Internal(why.to_string())
24    }
25}
26
27/// The answer to one request.
28pub type Answer = Result<Value, Error>;
29
30/// Reads a method's params; params of the wrong shape are the core's mistake.
31pub fn decode<T: DeserializeOwned>(params: Value) -> Result<T, Error> {
32    serde_json::from_value(params).map_err(|err| Error::Internal(format!("params of the wrong shape: {err}")))
33}
34
35/// The one project `open` creates.
36pub trait Session: Send + Sync {
37    /// Answers a method of the session; `None` for a method it does not have.
38    fn call(&self, method: &str, params: Value) -> Option<Answer>;
39    /// Releases what the session holds.
40    fn close(&self);
41}
42
43/// What a language gives the server to serve.
44pub struct Adapter {
45    /// The greeting, the same in every process.
46    pub hello: Hello,
47    /// Answers a question about text, which needs no session; `None` for any other method.
48    pub language: fn(method: &str, params: Value) -> Option<Answer>,
49    /// Creates the session.
50    pub open: fn(params: Value) -> Result<Arc<dyn Session>, Error>,
51}
52
53/// Where a process is in the life of its one session.
54#[derive(Clone)]
55enum Life {
56    NotOpen,
57    Open(Arc<dyn Session>),
58    Closed,
59}
60
61struct Server<W: Write + Send + 'static> {
62    adapter: Adapter,
63    out: Arc<Mutex<W>>,
64    greeted: bool,
65    life: Life,
66    pending: Vec<JoinHandle<()>>,
67}
68
69/// Answers the requests on `input` until it ends; it then writes the answers still in
70/// flight and closes the session.
71pub fn serve<W: Write + Send + 'static>(input: impl BufRead, out: W, adapter: Adapter) {
72    let out = Arc::new(Mutex::new(out));
73    let mut server = Server { adapter, out, greeted: false, life: Life::NotOpen, pending: Vec::new() };
74    for line in input.lines() {
75        let Ok(line) = line else { break };
76        if !line.trim().is_empty() {
77            server.receive(&line);
78        }
79    }
80    server.settle();
81    server.close_session();
82}
83
84impl<W: Write + Send + 'static> Server<W> {
85    /// Reads one line as a request and routes it; a line that is no request, or has no
86    /// usable id, is answered with a null id.
87    fn receive(&mut self, line: &str) {
88        let Ok(request) = serde_json::from_str::<Value>(line) else {
89            return write(&self.out, &Value::Null, Err(Error::internal("a line that is not a request")));
90        };
91        let id = request.get("id").cloned().unwrap_or(Value::Null);
92        if !id.as_u64().is_some_and(|n| n > 0) {
93            return write(
94                &self.out,
95                &Value::Null,
96                Err(Error::internal("a request without a positive integer id")),
97            );
98        }
99        let method = request.get("method").and_then(Value::as_str).unwrap_or("").to_string();
100        let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
101        self.route(id, &method, params);
102    }
103
104    fn route(&mut self, id: Value, method: &str, params: Value) {
105        let answer = match method {
106            "hello" => self.hello(&params),
107            _ if !self.greeted => {
108                Err(Error::Internal(format!("\"{method}\" before hello: hello comes first")))
109            }
110            "open" => self.open(params),
111            "close" => self.close(),
112            _ => return self.later(id, method.to_string(), params),
113        };
114        write(&self.out, &id, answer);
115    }
116
117    /// Answers a request on its own thread, so that a slow one holds up no other.
118    fn later(&mut self, id: Value, method: String, params: Value) {
119        let (language, life) = (self.adapter.language, self.life.clone());
120        let out = Arc::clone(&self.out);
121        self.pending.push(std::thread::spawn(move || {
122            let answer = catch_unwind(AssertUnwindSafe(|| {
123                language(&method, params.clone()).unwrap_or_else(|| answer_in(&life, &method, params))
124            }));
125            let answer = answer.unwrap_or_else(|_| Err(Error::internal("the adapter panicked")));
126            write(&out, &id, answer);
127        }));
128    }
129
130    fn hello(&mut self, params: &Value) -> Answer {
131        let asked = params.get("protocol").and_then(Value::as_f64);
132        if asked != Some(super::VERSION as f64) {
133            let name = &self.adapter.hello.adapter.name;
134            let shown = params.get("protocol").map(Value::to_string).unwrap_or_default();
135            let message =
136                "docattest: the {name} adapter speaks protocol {version}, and the core asked for {shown}";
137            let message = message
138                .replace("{name}", name)
139                .replace("{version}", &super::VERSION.to_string())
140                .replace("{shown}", &shown);
141            return Err(Error::User(message));
142        }
143        self.greeted = true;
144        serde_json::to_value(&self.adapter.hello).map_err(Error::internal)
145    }
146
147    fn open(&mut self, params: Value) -> Answer {
148        if !matches!(self.life, Life::NotOpen) {
149            return Err(Error::internal("a second open: one process serves one session"));
150        }
151        self.life = Life::Open((self.adapter.open)(params)?);
152        Ok(json!({}))
153    }
154
155    /// Waits for every request sent before it, then releases the session.
156    fn close(&mut self) -> Answer {
157        if !matches!(self.life, Life::Open(_)) {
158            return Err(Error::internal("close needs a session, and none is open"));
159        }
160        self.settle();
161        self.close_session();
162        Ok(json!({}))
163    }
164
165    fn settle(&mut self) {
166        for handle in self.pending.drain(..) {
167            let _ = handle.join();
168        }
169    }
170
171    fn close_session(&mut self) {
172        if let Life::Open(session) = &self.life {
173            session.close();
174            self.life = Life::Closed;
175        }
176    }
177}
178
179/// Answers a method of the session, or says why there is no answer.
180fn answer_in(life: &Life, method: &str, params: Value) -> Answer {
181    let unanswered = match life {
182        Life::Open(session) => match session.call(method, params) {
183            Some(answer) => return answer,
184            None => format!("unknown method \"{method}\""),
185        },
186        Life::Closed => format!("\"{method}\" after close: the session is closed"),
187        Life::NotOpen => format!("\"{method}\" needs a session, and none is open"),
188    };
189    Err(Error::Internal(unanswered))
190}
191
192fn write<W: Write>(out: &Mutex<W>, id: &Value, answer: Answer) {
193    let response = match answer {
194        Ok(result) => json!({ "id": id, "result": result }),
195        Err(Error::User(message)) => json!({ "id": id, "error": { "kind": "user", "message": message } }),
196        Err(Error::Internal(message)) => {
197            json!({ "id": id, "error": { "kind": "internal", "message": message } })
198        }
199    };
200    let mut out = out.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
201    let _ = writeln!(out, "{response}");
202    let _ = out.flush();
203}