1use crate::plugin::PluginProcess;
5use serde_json::Value;
6
7use crate::tool::{Operation, RunInput, RunReport, RunRequest, ToolDescription, ToolRequest, Validation};
8
9pub struct ToolClient {
11 process: PluginProcess,
12 description: ToolDescription,
13}
14
15impl ToolClient {
16 pub fn start(program: &str, args: &[&str]) -> Result<Self, String> {
19 let mut process = PluginProcess::start_command(program, args)?;
20 let answer = process.request(&ToolRequest::Describe, &mut |_, _| {})?;
21 let description: ToolDescription =
22 serde_json::from_value(answer).map_err(|e| format!("{program}: not a tool description: {e}"))?;
23 description.compatible()?;
24 description.check()?;
25 Ok(Self { process, description })
26 }
27
28 pub fn description(&self) -> &ToolDescription {
29 &self.description
30 }
31
32 pub fn validate(&mut self, operation: &str, recipe: &Value) -> Result<Validation, String> {
34 self.operation(operation)?;
35 let request = ToolRequest::Validate { operation: operation.to_string(), recipe: recipe.clone() };
36 let answer = self.process.request(&request, &mut |_, _| {})?;
37 serde_json::from_value(answer).map_err(|e| format!("{}: not a validation: {e}", self.description.name))
38 }
39
40 pub fn run(
43 &mut self,
44 request: &RunRequest,
45 progress: &mut dyn FnMut(&str, Option<f32>),
46 ) -> Result<RunReport, String> {
47 let operation = self.operation(&request.operation)?.clone();
48 check_inputs(&operation, &request.inputs)?;
49 let answer = self.process.request(&ToolRequest::Run(request.clone()), progress)?;
50 let report: RunReport =
51 serde_json::from_value(answer).map_err(|e| format!("{}: not a run report: {e}", self.description.name))?;
52 report.check(&operation, &request.output_dir)?;
53 Ok(report)
54 }
55
56 pub fn alive(&mut self) -> bool {
58 self.process.alive()
59 }
60
61 fn operation(&self, name: &str) -> Result<&Operation, String> {
62 self.description.operation(name).ok_or_else(|| format!("{} has no operation {name}", self.description.name))
63 }
64}
65
66pub fn check_inputs(operation: &Operation, inputs: &[RunInput]) -> Result<(), String> {
69 for input in inputs {
70 let port = operation
71 .inputs
72 .iter()
73 .find(|p| p.name == input.name)
74 .ok_or_else(|| format!("{}: no input port {}", operation.name, input.name))?;
75 if !port.accepts(&input.ty, &input.format) {
76 return Err(format!(
77 "{}.{}: takes {}, not {} in {}",
78 operation.name,
79 port.name,
80 port.takes(),
81 input.ty,
82 input.format
83 ));
84 }
85 }
86 for port in &operation.inputs {
87 let given = inputs.iter().filter(|i| i.name == port.name).count();
88 if given == 0 && !port.optional {
89 return Err(format!("{}.{}: no input given", operation.name, port.name));
90 }
91 if given > 1 && !port.many {
92 return Err(format!("{}.{}: takes one input, {given} given", operation.name, port.name));
93 }
94 }
95 Ok(())
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101 use crate::tool::{InputPort, OutputPort};
102 use kitchen_contract::{ContentId, Format, Type};
103
104 fn input(name: &str, ty: &str, format: &str) -> RunInput {
105 RunInput {
106 name: name.into(),
107 ty: Type::new(ty),
108 format: Format::parse(format).unwrap(),
109 path: "/data/x".into(),
110 id: ContentId::parse(&format!("sha256:{}", "a".repeat(64))).unwrap(),
111 }
112 }
113
114 #[test]
115 fn inputs_are_checked_against_the_ports() {
116 let op = Operation {
117 name: "sort".into(),
118 summary: String::new(),
119 inputs: vec![
120 InputPort {
121 name: "recording".into(),
122 ty: Type::new("signal"),
123 formats: vec![Format::parse("nwb-zarr").unwrap()],
124 many: false,
125 optional: false,
126 },
127 InputPort { name: "probe".into(), ty: Type::new("file"), formats: vec![], many: false, optional: true },
128 ],
129 outputs: vec![OutputPort {
130 name: "sorting".into(),
131 ty: Type::new("dspk:sorting"),
132 format: Format::parse("zarr").unwrap(),
133 }],
134 recipe_schema: Value::Null,
135 resources: Default::default(),
136 };
137 assert!(check_inputs(&op, &[input("recording", "signal", "nwb-zarr")]).is_ok());
138 assert!(check_inputs(&op, &[]).is_err(), "a required port is missing");
139 let wrong = check_inputs(&op, &[input("recording", "image", "ome-zarr")]).unwrap_err();
140 assert!(wrong.contains("takes signal in nwb-zarr, not image in ome-zarr"), "{wrong}");
141 assert!(check_inputs(&op, &[input("recording", "signal", "raw")]).is_err(), "the wrong format");
142 assert!(
143 check_inputs(&op, &[input("recording", "signal", "nwb-zarr"), input("recording", "signal", "nwb-zarr")])
144 .is_err(),
145 "one only"
146 );
147 assert!(
148 check_inputs(&op, &[input("recording", "signal", "nwb-zarr"), input("probe", "file", "json")]).is_ok(),
149 "any format"
150 );
151 }
152}