Skip to main content

kitchen_tools/tool/
protocol.rs

1//! The requests a tool answers beside the plugin protocol's own (`info`, `install`, `remove`,
2//! `quit`). Each is one JSON line with a `"request"` tag; the answer is the plugin protocol's
3//! `progress` events, then one `done` (its `result` as below) or `error`.
4
5use std::path::PathBuf;
6
7use kitchen_contract::{ContentId, Format, RunKey, Type};
8use serde::{Deserialize, Serialize};
9
10/// The tool protocol version this crate speaks: in [`crate::tool::ToolDescription::tool_protocol`],
11/// checked by the orchestrator. The plugin protocol under it has its own version. Version 2 names
12/// ports and results by the contract's type and format (version 1: artifact kinds).
13pub const TOOL_PROTOCOL: u32 = 2;
14
15/// A request to a tool.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[serde(tag = "request", rename_all = "snake_case")]
18pub enum ToolRequest {
19    /// Answered with a [`crate::tool::ToolDescription`].
20    Describe,
21    /// Answered with a [`Validation`].
22    Validate { operation: String, recipe: serde_json::Value },
23    /// Answered with a [`crate::tool::RunReport`].
24    Run(RunRequest),
25}
26
27/// The answer to `validate`.
28#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
29pub struct Validation {
30    /// What is wrong with the recipe, in words a person can act on; empty when it can run.
31    pub problems: Vec<String>,
32}
33
34impl Validation {
35    pub fn ok(&self) -> bool {
36        self.problems.is_empty()
37    }
38}
39
40/// Run an operation on input artifacts, writing its outputs into `output_dir` (which exists and
41/// is empty; the tool writes nothing elsewhere).
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct RunRequest {
44    pub operation: String,
45    pub recipe: serde_json::Value,
46    pub inputs: Vec<RunInput>,
47    pub output_dir: PathBuf,
48    /// The run's own parameters beside the recipe (a channel range, a region).
49    #[serde(default)]
50    pub params: serde_json::Value,
51}
52
53impl RunRequest {
54    /// This run's key: what decides its result, so a finished one is reused. The fields are the
55    /// same as before the contract (tool, version, image, operation, recipe, named inputs,
56    /// parameters), so earlier keys still match.
57    pub fn run_key(&self, tool: &ToolRef) -> RunKey {
58        let mut named: Vec<(&str, &str)> = self.inputs.iter().map(|i| (i.name.as_str(), i.id.as_str())).collect();
59        named.sort();
60        RunKey::from_fields(&serde_json::json!({
61            "key": "kitchen-run-v1",
62            "tool": tool.name,
63            "version": tool.version,
64            "image": tool.image,
65            "operation": self.operation,
66            "recipe": ContentId::of_json(&self.recipe).as_str(),
67            "inputs": named,
68            "params": self.params,
69        }))
70    }
71}
72
73/// An input result, on a path the tool can read.
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75pub struct RunInput {
76    /// The input port it is for.
77    pub name: String,
78    #[serde(rename = "type")]
79    pub ty: Type,
80    pub format: Format,
81    pub path: PathBuf,
82    pub id: ContentId,
83}
84
85/// The tool that ran: its name and version, and the container image when it ran in one.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct ToolRef {
88    pub name: String,
89    pub version: String,
90    /// The image by digest (`ghcr.io/neuro-kitchen/dspk@sha256:…`), never by a moving tag.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub image: Option<String>,
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn requests_are_tagged_json_lines() {
101        assert_eq!(serde_json::to_string(&ToolRequest::Describe).unwrap(), r#"{"request":"describe"}"#);
102        let run = ToolRequest::Run(RunRequest {
103            operation: "sort".into(),
104            recipe: serde_json::json!({"sorter": "ks4"}),
105            inputs: vec![],
106            output_dir: "/out".into(),
107            params: serde_json::Value::Null,
108        });
109        let line = serde_json::to_string(&run).unwrap();
110        assert!(line.starts_with(r#"{"request":"run","operation":"sort""#), "{line}");
111        assert_eq!(serde_json::from_str::<ToolRequest>(&line).unwrap(), run);
112    }
113
114    #[test]
115    fn the_same_run_has_the_same_key() {
116        let tool = ToolRef { name: "dspk".into(), version: "0.0.13".into(), image: None };
117        let input = |name: &str, c: char| RunInput {
118            name: name.into(),
119            ty: Type::new("signal"),
120            format: Format::parse("nwb-zarr").unwrap(),
121            path: "/data/x".into(),
122            id: ContentId::parse(&format!("sha256:{}", c.to_string().repeat(64))).unwrap(),
123        };
124        let reordered: serde_json::Value = serde_json::from_str(r#"{"threshold": 6, "sorter": "ks4"}"#).unwrap();
125        let run = |inputs: Vec<RunInput>, recipe: serde_json::Value| RunRequest {
126            operation: "sort".into(),
127            recipe,
128            inputs,
129            output_dir: "/out".into(),
130            params: serde_json::Value::Null,
131        };
132        let key = run(
133            vec![input("recording", 'a'), input("probe", 'b')],
134            serde_json::json!({"sorter": "ks4", "threshold": 6}),
135        )
136        .run_key(&tool);
137        assert_eq!(
138            key,
139            run(vec![input("probe", 'b'), input("recording", 'a')], reordered.clone()).run_key(&tool),
140            "order does not count"
141        );
142        assert_ne!(key, run(vec![input("recording", 'a'), input("probe", 'c')], reordered.clone()).run_key(&tool));
143        let newer = ToolRef { version: "0.0.14".into(), ..tool.clone() };
144        assert_ne!(key, run(vec![input("recording", 'a'), input("probe", 'b')], reordered).run_key(&newer));
145    }
146}