Skip to main content

flow_toolkit/
server.rs

1//! The Tool process protocol, served (`abi.md`, *The Tool process
2//! protocol*): JSON-RPC 2.0, one message per line.
3//!
4//! `describe` is answered from the declarations the code was generated
5//! from; each `call` runs on a thread of its own and is answered by one
6//! `reply`, written whole; a `cancel` sets the call's flag. When the input
7//! ends, the calls still running finish and are answered, and the server
8//! returns.
9
10use std::collections::HashMap;
11use std::io::{self, BufRead, Write};
12use std::panic::{AssertUnwindSafe, catch_unwind};
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex};
15
16use flow_abi::{Json, Limits, TypeSpec, ValidatedTypes};
17
18use crate::data::{ContextCodec, Data, DecodeError, variant, within};
19
20/// Why a call did not produce its success value.
21#[derive(Clone, PartialEq, Eq, Debug)]
22pub enum Problem<E> {
23    /// The declared error: the call happened and failed.
24    Failed(E),
25    /// The call definitely did not happen, with why.
26    NotRun(String),
27    /// The call may or may not have happened, with why.
28    Unknown(String),
29}
30
31/// What a method knows about the call it answers.
32#[derive(Clone, Debug)]
33pub struct Context {
34    run: String,
35    call: String,
36    schema: Option<Json>,
37    cancelled: Arc<AtomicBool>,
38    types: Option<Arc<ValidatedTypes>>,
39}
40
41impl Context {
42    /// Validates the complete call views before making an author context.
43    #[allow(clippy::needless_pass_by_value)] // The public constructor takes ownership of both wire views.
44    pub fn try_new(
45        run: &str,
46        call: &str,
47        spec: &TypeSpec,
48        schema: Option<Json>,
49        types: Option<Json>,
50        cancelled: Arc<AtomicBool>,
51    ) -> Result<Context, DecodeError> {
52        let types = spec
53            .validate_call(schema.as_ref(), types.as_ref())?
54            .map(Arc::new);
55        Ok(Context {
56            run: run.to_owned(),
57            call: call.to_owned(),
58            schema,
59            cancelled,
60            types,
61        })
62    }
63
64    /// The admitted concrete type description, if this Tool is generic.
65    pub fn types(&self) -> Option<&ValidatedTypes> {
66        self.types.as_deref()
67    }
68
69    fn graph(&self) -> Result<Arc<ValidatedTypes>, DecodeError> {
70        self.types
71            .clone()
72            .ok_or_else(|| crate::data::refused("nongeneric context has no dynamic codecs"))
73    }
74
75    /// A generic binding's owned codec, when that binding crosses the boundary.
76    pub fn codec(&self, name: &str) -> Result<ContextCodec, DecodeError> {
77        let graph = self.graph()?;
78        let ty = graph
79            .binding(name)
80            .cloned()
81            .ok_or_else(|| crate::data::refused(format!("unknown binding {name}")))?;
82        ContextCodec::new(graph, ty, flow_abi::Mode::Reply)
83    }
84    /// An argument's owned concrete codec.
85    pub fn argument_codec(&self, name: &str) -> Result<ContextCodec, DecodeError> {
86        let graph = self.graph()?;
87        let ty = graph
88            .argument(name)
89            .cloned()
90            .ok_or_else(|| crate::data::refused(format!("unknown argument {name}")))?;
91        ContextCodec::new(graph, ty, flow_abi::Mode::Rebuild)
92    }
93    /// The owned success codec.
94    pub fn success_codec(&self) -> Result<ContextCodec, DecodeError> {
95        let graph = self.graph()?;
96        ContextCodec::new(graph.clone(), graph.ok().clone(), flow_abi::Mode::Reply)
97    }
98    /// The owned failure codec.
99    pub fn failure_codec(&self) -> Result<ContextCodec, DecodeError> {
100        let graph = self.graph()?;
101        ContextCodec::new(graph.clone(), graph.err().clone(), flow_abi::Mode::Reply)
102    }
103
104    /// The run's id.
105    pub fn run(&self) -> &str {
106        &self.run
107    }
108
109    /// The call's id, which a call sent again after a crash keeps.
110    pub fn call(&self) -> &str {
111        &self.call
112    }
113
114    /// For a generic Tool, the schema of the success type the caller
115    /// expects.
116    pub fn schema(&self) -> Option<&Json> {
117        self.schema.as_ref()
118    }
119
120    /// Writes one call-correlated operational log record outside protocol stdout.
121    pub fn log(&self, level: &str, message: &str) -> io::Result<()> {
122        if !matches!(level, "trace" | "debug" | "info" | "warn" | "error") {
123            return Err(io::Error::new(
124                io::ErrorKind::InvalidInput,
125                "log level must be trace, debug, info, warn or error",
126            ));
127        }
128        let record = Json::Object(vec![
129            ("run".into(), Json::String(self.run.clone())),
130            ("call".into(), Json::String(self.call.clone())),
131            ("level".into(), Json::String(level.into())),
132            ("message".into(), Json::String(message.into())),
133        ]);
134        let line = format!("\nFLOW_LOG {}\n", record.canonical());
135        io::stderr().lock().write_all(line.as_bytes())
136    }
137
138    /// Whether the host asked to stop work on this call. It proves nothing
139    /// either way.
140    pub fn cancelled(&self) -> bool {
141        self.cancelled.load(Ordering::SeqCst)
142    }
143
144    /// Asks to stop work on this call, as a `cancel` does.
145    pub fn cancel(&self) {
146        self.cancelled.store(true, Ordering::SeqCst);
147    }
148}
149
150/// A call's arguments, by parameter key.
151#[derive(Debug)]
152pub struct Args<'j>(&'j Json);
153
154impl Args<'_> {
155    /// A named raw argument for a generated contextual factory.
156    pub fn json(&self, name: &str) -> Result<&Json, DecodeError> {
157        self.0
158            .get(name)
159            .ok_or_else(|| crate::data::inside(crate::data::refused("is missing"), name))
160    }
161    /// The argument `name`, decoded.
162    pub fn take<T: Data>(&self, name: &str) -> Result<T, DecodeError> {
163        match self.0.get(name) {
164            Some(value) => within(value, name, T::decode),
165            None => Err(crate::data::inside(
166                crate::data::refused("is missing"),
167                name,
168            )),
169        }
170    }
171}
172
173type Handler = Box<dyn Fn(&Context, &Args<'_>) -> Json + Send + Sync>;
174
175/// One declaration an implementation serves: what `describe` lists for it,
176/// and the method answering its calls.
177pub(crate) struct Declaration {
178    entry: Json,
179    spec: TypeSpec,
180    handler: Handler,
181}
182
183impl std::fmt::Debug for Declaration {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        f.debug_struct("Declaration")
186            .field("entry", &self.entry)
187            .finish_non_exhaustive()
188    }
189}
190
191impl Declaration {
192    /// The declaration `describe` lists as `entry` — the JSON text of
193    /// `{"tool", "fingerprint", "signature"}` — answered by `method`, which
194    /// reads the arguments and calls the author's code.
195    ///
196    /// # Panics
197    ///
198    /// When `entry` is not JSON, which generated code never gives.
199    pub(crate) fn new<T, E, F>(entry: &str, spec: TypeSpec, method: F) -> Declaration
200    where
201        T: Data,
202        E: Data,
203        F: Fn(&Context, &Args<'_>) -> Result<Result<T, Problem<E>>, DecodeError>
204            + Send
205            + Sync
206            + 'static,
207    {
208        let entry = flow_abi::parse(entry, &Limits::default()).expect("a declaration's entry");
209        Declaration {
210            entry,
211            spec,
212            handler: Box::new(move |context, args| outcome(method(context, args))),
213        }
214    }
215
216    /// A declaration whose generated contextual factories produce JSON after author invocation.
217    pub(crate) fn contextual<F>(entry: &str, spec: TypeSpec, method: F) -> Declaration
218    where
219        F: Fn(&Context, &Args<'_>) -> Result<Result<Json, Problem<Json>>, DecodeError>
220            + Send
221            + Sync
222            + 'static,
223    {
224        let entry = flow_abi::parse(entry, &Limits::default()).expect("a declaration's entry");
225        Declaration {
226            entry,
227            spec,
228            handler: Box::new(move |context, args| outcome(method(context, args))),
229        }
230    }
231
232    fn serves(&self, tool: &Json) -> bool {
233        let named = |key: &str| self.entry.get("tool").and_then(|own| own.get(key));
234        let origin = if let Some(package) = named("package") {
235            named("repository").is_none()
236                && tool.get("repository").is_none()
237                && tool.get("package") == Some(package)
238        } else {
239            tool.get("package").is_none()
240                && named("repository").is_some()
241                && named("repository") == tool.get("repository")
242        };
243        origin
244            && ["file", "name"]
245                .into_iter()
246                .all(|key| named(key) == tool.get(key) && named(key).is_some())
247    }
248}
249
250/// The reply's `outcome` for what a method returned.
251fn outcome<T: Data, E: Data>(answer: Result<Result<T, Problem<E>>, DecodeError>) -> Json {
252    match answer {
253        Ok(Ok(value)) => variant("Ok", value.encode()),
254        Ok(Err(Problem::Failed(error))) => variant("Failed", error.encode()),
255        Ok(Err(Problem::NotRun(reason))) => variant("NotRun", Json::String(reason)),
256        Ok(Err(Problem::Unknown(reason))) => variant("Unknown", Json::String(reason)),
257        Err(error) => variant(
258            "NotRun",
259            Json::String(format!("the arguments do not decode: {error}")),
260        ),
261    }
262}
263
264#[cfg(test)]
265mod origin_tests {
266    use super::*;
267
268    fn json(value: &str) -> Json {
269        flow_abi::parse(value, &Limits::default()).unwrap()
270    }
271
272    #[test]
273    fn package_calls_do_not_alias_other_packages_or_repository_origins() {
274        for (origin, matched) in [
275            (r#""package":"flow/example""#, true),
276            (r#""package":"other/example""#, false),
277            (r#""repository":"flow/example""#, false),
278            (r#""package":"flow/example","repository":null"#, false),
279        ] {
280            let declaration = Declaration::new::<String, String, _>(
281                r#"{"tool":{"package":"flow/example","version":"v1","file":"","name":"act"},"fingerprint":"sha256:x","signature":{}}"#,
282                TypeSpec::read(&json(
283                    r#"{"generic":[],"params":[],"ok":"Text","err":"Text","declarations":{}}"#,
284                ))
285                .unwrap(),
286                |_, _| Ok(Ok("called".into())),
287            );
288            let server = Server::new("0.1", vec![declaration]);
289            let input = format!(
290                "{{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{{\"run\":\"r\",\"call\":\"c\",\"tool\":{{{origin},\"version\":\"v9\",\"file\":\"\",\"name\":\"act\"}},\"args\":{{}}}}}}\n"
291            );
292            let mut output = Vec::new();
293            server
294                .run(std::io::Cursor::new(input), &mut output)
295                .unwrap();
296            let reply = json(std::str::from_utf8(&output).unwrap().trim());
297            let outcome = reply.get("params").unwrap().get("outcome").unwrap();
298            if matched {
299                assert_eq!(outcome, &json(r#"{"Ok":"called"}"#));
300            } else {
301                assert!(outcome.get("NotRun").is_some());
302            }
303        }
304    }
305}
306
307/// An implementation's declarations, served over the Tool process
308/// protocol.
309#[derive(Debug)]
310pub(crate) struct Server {
311    data: String,
312    declarations: Vec<Declaration>,
313}
314
315impl Server {
316    /// A server for `declarations`, answering `describe` with the data
317    /// version `data`.
318    pub(crate) fn new(data: &str, declarations: Vec<Declaration>) -> Server {
319        Server {
320            data: data.to_owned(),
321            declarations,
322        }
323    }
324
325    /// Serves the messages read from `input`, writing each answer to
326    /// `output`, until the input ends and every call is answered.
327    pub(crate) fn run(&self, input: impl BufRead, output: impl Write + Send) -> io::Result<()> {
328        let output = Mutex::new(output);
329        let open: Mutex<HashMap<(String, String), Arc<AtomicBool>>> = Mutex::new(HashMap::new());
330        std::thread::scope(|scope| {
331            for line in input.lines() {
332                let line = line?;
333                let Ok(message) = flow_abi::parse(&line, &crate::data::LIMITS) else {
334                    continue;
335                };
336                let params = message.get("params");
337                let text = |key: &str| match params.and_then(|params| params.get(key)) {
338                    Some(Json::String(text)) => Some(text.clone()),
339                    _ => None,
340                };
341                match message.get("method") {
342                    Some(Json::String(method)) if method == "describe" => {
343                        let id = message.get("id").cloned().unwrap_or(Json::Null);
344                        write(&output, &self.described(id))?;
345                    }
346                    Some(Json::String(method)) if method == "call" => {
347                        let (Some(run), Some(call)) = (text("run"), text("call")) else {
348                            continue;
349                        };
350                        let params = params.cloned().unwrap_or(Json::Null);
351                        let cancelled = Arc::new(AtomicBool::new(false));
352                        lock(&open).insert((run.clone(), call.clone()), cancelled.clone());
353                        let (output, open) = (&output, &open);
354                        scope.spawn(move || {
355                            let outcome = self.answer(&run, &call, cancelled, &params);
356                            lock(open).remove(&(run.clone(), call.clone()));
357                            let reply = reply(&run, &call, outcome);
358                            let _ = write(output, &reply);
359                        });
360                    }
361                    Some(Json::String(method)) if method == "cancel" => {
362                        if let (Some(run), Some(call)) = (text("run"), text("call"))
363                            && let Some(context) = lock(&open).get(&(run, call))
364                        {
365                            context.store(true, Ordering::SeqCst);
366                        }
367                    }
368                    _ => {}
369                }
370            }
371            Ok(())
372        })
373    }
374
375    fn described(&self, id: Json) -> Json {
376        let tools = self
377            .declarations
378            .iter()
379            .map(|declaration| declaration.entry.clone())
380            .collect();
381        Json::Object(vec![
382            ("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
383            ("id".to_owned(), id),
384            (
385                "result".to_owned(),
386                Json::Object(vec![
387                    ("data".to_owned(), Json::String(self.data.clone())),
388                    ("tools".to_owned(), Json::Array(tools)),
389                ]),
390            ),
391        ])
392    }
393
394    /// The outcome of the call `params` describes.
395    fn answer(&self, run: &str, call: &str, cancelled: Arc<AtomicBool>, params: &Json) -> Json {
396        let tool = params.get("tool").cloned().unwrap_or(Json::Null);
397        let Some(declaration) = self.declarations.iter().find(|d| d.serves(&tool)) else {
398            return variant(
399                "NotRun",
400                Json::String(format!(
401                    "this implementation serves no declaration {}",
402                    tool.canonical()
403                )),
404            );
405        };
406        let context = match Context::try_new(
407            run,
408            call,
409            &declaration.spec,
410            params.get("schema").cloned(),
411            params.get("types").cloned(),
412            cancelled,
413        ) {
414            Ok(context) => context,
415            Err(error) => {
416                return variant(
417                    "NotRun",
418                    Json::String(format!("invalid call types: {error}")),
419                );
420            }
421        };
422        let args = params.get("args").cloned().unwrap_or(Json::Null);
423        let answered = catch_unwind(AssertUnwindSafe(|| {
424            (declaration.handler)(&context, &Args(&args))
425        }));
426        answered.unwrap_or_else(|panic| {
427            let why = panic
428                .downcast_ref::<&str>()
429                .map(|text| (*text).to_owned())
430                .or_else(|| panic.downcast_ref::<String>().cloned())
431                .unwrap_or_else(|| "it panicked".to_owned());
432            variant(
433                "Unknown",
434                Json::String(format!("the implementation stopped: {why}")),
435            )
436        })
437    }
438}
439
440fn reply(run: &str, call: &str, outcome: Json) -> Json {
441    Json::Object(vec![
442        ("jsonrpc".to_owned(), Json::String("2.0".to_owned())),
443        ("method".to_owned(), Json::String("reply".to_owned())),
444        (
445            "params".to_owned(),
446            Json::Object(vec![
447                ("run".to_owned(), Json::String(run.to_owned())),
448                ("call".to_owned(), Json::String(call.to_owned())),
449                ("outcome".to_owned(), outcome),
450            ]),
451        ),
452    ])
453}
454
455fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
456    mutex
457        .lock()
458        .unwrap_or_else(std::sync::PoisonError::into_inner)
459}
460
461/// Writes `message` as one line, whole, and flushes it.
462fn write(output: &Mutex<impl Write>, message: &Json) -> io::Result<()> {
463    let mut line = message.canonical();
464    line.push('\n');
465    let mut output = lock(output);
466    output.write_all(line.as_bytes())?;
467    output.flush()
468}