Skip to main content

kitchen_tools/tool/
description.rs

1//! What a tool offers: its operations, what each reads and writes, how its recipe looks.
2
3use kitchen_contract::{Format, Type};
4use serde::{Deserialize, Serialize};
5
6use crate::tool::TOOL_PROTOCOL;
7use crate::tool::protocol::ToolRef;
8
9/// A tool's answer to `describe`.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub struct ToolDescription {
12    pub name: String,
13    pub version: String,
14    /// The tool protocol version it speaks ([`TOOL_PROTOCOL`]).
15    pub tool_protocol: u32,
16    pub operations: Vec<Operation>,
17}
18
19impl ToolDescription {
20    /// The handshake: whether the orchestrator can drive it (the same tool protocol version).
21    pub fn compatible(&self) -> Result<(), String> {
22        match self.tool_protocol {
23            TOOL_PROTOCOL => Ok(()),
24            p if p > TOOL_PROTOCOL => Err(format!(
25                "{} speaks tool protocol {p}; this orchestrator speaks {TOOL_PROTOCOL}: update the orchestrator",
26                self.name
27            )),
28            p => Err(format!(
29                "{} speaks tool protocol {p}; this orchestrator speaks {TOOL_PROTOCOL}: update the tool",
30                self.name
31            )),
32        }
33    }
34
35    pub fn operation(&self, name: &str) -> Option<&Operation> {
36        self.operations.iter().find(|o| o.name == name)
37    }
38
39    /// The tool as provenance names it (the image is the runner's to add).
40    pub fn tool_ref(&self) -> ToolRef {
41        ToolRef { name: self.name.clone(), version: self.version.clone(), image: None }
42    }
43
44    /// Every operation's ports and names well formed: unique operation names, unique port names
45    /// within an operation, at least one output.
46    pub fn check(&self) -> Result<(), String> {
47        let mut seen = std::collections::BTreeSet::new();
48        for op in &self.operations {
49            if !seen.insert(op.name.as_str()) {
50                return Err(format!("{}: operation {} twice", self.name, op.name));
51            }
52            let mut ports = std::collections::BTreeSet::new();
53            for name in op.inputs.iter().map(|p| &p.name).chain(op.outputs.iter().map(|p| &p.name)) {
54                if !ports.insert(name.as_str()) {
55                    return Err(format!("{}.{}: port {name} twice", self.name, op.name));
56                }
57            }
58            if op.outputs.is_empty() {
59                return Err(format!("{}.{}: no outputs", self.name, op.name));
60            }
61        }
62        Ok(())
63    }
64}
65
66/// One thing a tool does (`convert`, `sort`, `segment`, `extract`).
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub struct Operation {
69    pub name: String,
70    /// One line, for people choosing it.
71    pub summary: String,
72    pub inputs: Vec<InputPort>,
73    pub outputs: Vec<OutputPort>,
74    /// The JSON Schema of the operation's recipe (the tool's session or pipeline spec): the
75    /// orchestrator checks a recipe against it before anything runs.
76    #[serde(default)]
77    pub recipe_schema: serde_json::Value,
78    #[serde(default)]
79    pub resources: Resources,
80}
81
82impl Operation {
83    /// The input port that accepts a result of type `ty` in `format`, if one does.
84    pub fn input_for(&self, ty: &Type, format: &Format) -> Option<&InputPort> {
85        self.inputs.iter().find(|p| p.accepts(ty, format))
86    }
87}
88
89/// What an operation reads: a result of the contract's type `ty`, in one of `formats` (any format
90/// when empty).
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92pub struct InputPort {
93    pub name: String,
94    #[serde(rename = "type")]
95    pub ty: Type,
96    #[serde(default, skip_serializing_if = "Vec::is_empty")]
97    pub formats: Vec<Format>,
98    /// Takes several artifacts (a folder of recordings), not one.
99    #[serde(default)]
100    pub many: bool,
101    #[serde(default)]
102    pub optional: bool,
103}
104
105impl InputPort {
106    /// Whether it takes a result of type `ty` in `format`.
107    pub fn accepts(&self, ty: &Type, format: &Format) -> bool {
108        ty.feeds(&self.ty) && (self.formats.is_empty() || self.formats.contains(format))
109    }
110
111    /// What it takes, for messages (`signal in nwb-zarr or raw`).
112    pub fn takes(&self) -> String {
113        if self.formats.is_empty() {
114            self.ty.to_string()
115        } else {
116            format!("{} in {}", self.ty, self.formats.iter().map(Format::as_str).collect::<Vec<_>>().join(" or "))
117        }
118    }
119}
120
121/// What an operation writes: a result of the contract's type `ty` in `format`.
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123pub struct OutputPort {
124    pub name: String,
125    #[serde(rename = "type")]
126    pub ty: Type,
127    pub format: Format,
128}
129
130/// What an operation needs to run, so the orchestrator sends it where it can.
131#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
132pub struct Resources {
133    /// Needs a GPU (it still runs on the CPU runtime, slower, when none is there).
134    #[serde(default)]
135    pub gpu: bool,
136    /// Memory it needs, about (GiB).
137    #[serde(default)]
138    pub memory_gib: Option<f32>,
139}