1use std::collections::{BTreeMap, BTreeSet};
28use std::fmt;
29use std::str::FromStr;
30
31use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
32use serde::{Deserialize, Deserializer, Serialize, Serializer};
33
34use crate::catalog::Catalog;
35use crate::ops::Margin;
36use crate::params::{ParamValue, check_params};
37use crate::types::Type;
38
39pub const PIPELINE_VERSION: u32 = 1;
41
42#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub struct Endpoint {
45 pub node: String,
47 pub port: Option<String>,
49}
50
51impl Endpoint {
52 pub fn port(node: impl Into<String>, port: impl Into<String>) -> Self {
54 Self { node: node.into(), port: Some(port.into()) }
55 }
56
57 pub fn source(name: impl Into<String>) -> Self {
59 Self { node: name.into(), port: None }
60 }
61}
62
63impl fmt::Display for Endpoint {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match &self.port {
66 Some(p) => write!(f, "{}.{p}", self.node),
67 None => f.write_str(&self.node),
68 }
69 }
70}
71
72impl FromStr for Endpoint {
73 type Err = String;
74 fn from_str(s: &str) -> Result<Self, String> {
75 let s = s.trim();
76 let ok = |t: &str| !t.is_empty() && t.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-');
77 match s.split_once('.') {
78 Some((n, p)) if ok(n) && ok(p) => Ok(Endpoint::port(n, p)),
79 None if ok(s) => Ok(Endpoint::source(s)),
80 _ => Err(format!("{s:?} is not `node.port` or a source's name")),
81 }
82 }
83}
84
85impl Serialize for Endpoint {
86 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
87 s.collect_str(self)
88 }
89}
90
91impl<'de> Deserialize<'de> for Endpoint {
92 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
93 String::deserialize(d)?.parse().map_err(serde::de::Error::custom)
94 }
95}
96
97impl JsonSchema for Endpoint {
98 fn schema_name() -> std::borrow::Cow<'static, str> {
99 "Endpoint".into()
100 }
101
102 fn json_schema(_: &mut SchemaGenerator) -> Schema {
103 json_schema!({
104 "type": "string",
105 "description": "`node.port`, or a source's name.",
106 "pattern": "^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)?$"
107 })
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
113pub struct Edge(pub Endpoint, pub Endpoint);
114
115fn yes() -> bool {
116 true
117}
118
119#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
121#[serde(deny_unknown_fields)]
122pub struct Node {
123 pub op: String,
125 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
127 pub params: BTreeMap<String, ParamValue>,
128 #[serde(default = "yes", skip_serializing_if = "Clone::clone")]
130 pub enabled: bool,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub label: Option<String>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub at: Option<[f32; 2]>,
137}
138
139impl Node {
140 pub fn new(op: impl Into<String>) -> Self {
142 Self { op: op.into(), params: BTreeMap::new(), enabled: true, label: None, at: None }
143 }
144
145 pub fn with(mut self, name: impl Into<String>, value: ParamValue) -> Self {
147 self.params.insert(name.into(), value);
148 self
149 }
150}
151
152fn version() -> u32 {
153 PIPELINE_VERSION
154}
155
156#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
158#[serde(deny_unknown_fields)]
159pub struct Pipeline {
160 #[serde(default = "version", alias = "kitchen_pipeline")]
162 pub version: u32,
163 #[serde(default, skip_serializing_if = "String::is_empty")]
165 pub app: String,
166 pub sources: BTreeMap<String, Type>,
168 #[serde(default)]
170 pub nodes: BTreeMap<String, Node>,
171 #[serde(default)]
173 pub edges: Vec<Edge>,
174 pub outputs: BTreeMap<String, Endpoint>,
176}
177
178#[derive(Clone, Debug, PartialEq, Eq)]
180pub struct Problem {
181 pub node: Option<String>,
183 pub message: String,
185}
186
187impl Problem {
188 fn at(node: &str, message: impl Into<String>) -> Self {
189 Problem { node: Some(node.to_string()), message: message.into() }
190 }
191
192 fn graph(message: impl Into<String>) -> Self {
193 Problem { node: None, message: message.into() }
194 }
195}
196
197impl fmt::Display for Problem {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 match &self.node {
200 Some(n) => write!(f, "{n}: {}", self.message),
201 None => f.write_str(&self.message),
202 }
203 }
204}
205
206#[derive(Clone, Debug, PartialEq)]
208pub struct Plan {
209 pub order: Vec<String>,
211 pub ops: BTreeMap<String, String>,
213 pub inputs: BTreeMap<String, BTreeMap<String, Endpoint>>,
215 pub params: BTreeMap<String, BTreeMap<String, ParamValue>>,
217 pub forwards: BTreeMap<String, BTreeMap<String, Endpoint>>,
219 pub sources: BTreeSet<String>,
221 pub outputs: BTreeMap<String, Endpoint>,
223 pub margin: Margin,
226 pub readers: BTreeMap<Endpoint, usize>,
229}
230
231impl Pipeline {
232 pub fn new(app: impl Into<String>) -> Self {
234 Self {
235 version: PIPELINE_VERSION,
236 app: app.into(),
237 sources: BTreeMap::new(),
238 nodes: BTreeMap::new(),
239 edges: Vec::new(),
240 outputs: BTreeMap::new(),
241 }
242 }
243
244 pub fn from_json(text: &str) -> Result<Pipeline, String> {
246 let g: Pipeline = serde_json::from_str(text).map_err(|e| e.to_string())?;
247 if g.version > PIPELINE_VERSION {
248 return Err(format!(
249 "format {} is newer than this app reads ({PIPELINE_VERSION}): update the app",
250 g.version
251 ));
252 }
253 Ok(g)
254 }
255
256 pub fn to_json(&self) -> String {
258 serde_json::to_string_pretty(self).unwrap_or_default()
259 }
260
261 pub fn connect(&mut self, from: Endpoint, to: Endpoint) {
263 self.edges.retain(|e| e.1 != to);
264 self.edges.push(Edge(from, to));
265 }
266
267 pub fn check(&self, catalog: &Catalog) -> Result<Plan, Vec<Problem>> {
269 let mut problems = Vec::new();
270 if self.version > PIPELINE_VERSION {
271 problems.push(Problem::graph(format!("format {} is newer than this app reads", self.version)));
272 }
273 for (name, ty) in &self.sources {
274 if self.nodes.contains_key(name) {
275 problems.push(Problem::graph(format!("{name} is both a source and a node")));
276 }
277 if !catalog.knows(ty) {
278 problems.push(Problem::graph(format!("source {name}: type {ty} is not one of the app's")));
279 }
280 }
281 if self.outputs.is_empty() {
282 problems.push(Problem::graph("nothing is written: add an output"));
283 }
284
285 let mut params = BTreeMap::new();
287 let mut ops = BTreeMap::new();
288 for (id, node) in &self.nodes {
289 let Some(spec) = catalog.get(&node.op) else {
290 problems.push(Problem::at(
291 id,
292 format!(
293 "no operation {:?} in this app (another app's op runs in a chain, on the orchestrator)",
294 node.op
295 ),
296 ));
297 continue;
298 };
299 ops.insert(id.clone(), node.op.clone());
300 match check_params(&spec.params, &node.params) {
301 Ok(p) => {
302 params.insert(id.clone(), p);
303 }
304 Err(es) => problems.extend(es.into_iter().map(|e| Problem::at(id, e))),
305 }
306 }
307
308 let type_of = |e: &Endpoint| -> Option<Type> {
310 match &e.port {
311 None => self.sources.get(&e.node).cloned(),
312 Some(p) => catalog.get(&self.nodes.get(&e.node)?.op)?.output_port(p).map(|p| p.ty.clone()),
313 }
314 };
315
316 let mut inputs: BTreeMap<String, BTreeMap<String, Endpoint>> = BTreeMap::new();
318 for Edge(from, to) in &self.edges {
319 let Some(from_ty) = type_of(from) else {
320 problems.push(Problem::graph(format!("{from} → {to}: {from} is not a source or an output")));
321 continue;
322 };
323 let Some(port) = &to.port else {
324 problems.push(Problem::graph(format!("{from} → {to}: a source cannot be fed")));
325 continue;
326 };
327 let Some(spec) = self.nodes.get(&to.node).and_then(|n| catalog.get(&n.op)) else {
328 if !self.nodes.contains_key(&to.node) {
329 problems.push(Problem::graph(format!("{from} → {to}: no node {}", to.node)));
330 }
331 continue;
332 };
333 let Some(input) = spec.input_port(port) else {
334 problems.push(Problem::at(&to.node, format!("{} has no input {port}", spec.title)));
335 continue;
336 };
337 if !from_ty.feeds(&input.ty) {
338 problems.push(Problem::at(&to.node, format!("{port} takes {}, but {from} gives {from_ty}", input.ty)));
339 }
340 if inputs.entry(to.node.clone()).or_default().insert(port.clone(), from.clone()).is_some() {
341 problems.push(Problem::at(&to.node, format!("{port} is fed twice")));
342 }
343 }
344 for (id, node) in &self.nodes {
345 let Some(spec) = catalog.get(&node.op) else { continue };
346 for p in spec.inputs.iter().filter(|p| !p.optional) {
347 if !inputs.get(id).is_some_and(|i| i.contains_key(&p.name)) {
348 problems.push(Problem::at(id, format!("{} is not connected", p.name)));
349 }
350 }
351 }
352
353 let mut forwards = BTreeMap::new();
355 for (id, node) in self.nodes.iter().filter(|(_, n)| !n.enabled) {
356 let Some(spec) = catalog.get(&node.op) else { continue };
357 let mut map = BTreeMap::new();
358 for out in &spec.outputs {
359 let feed = spec
360 .inputs
361 .iter()
362 .filter_map(|p| inputs.get(id).and_then(|i| i.get(&p.name)).filter(|_| p.ty == out.ty))
363 .next();
364 match feed {
365 Some(f) => {
366 map.insert(out.name.clone(), f.clone());
367 }
368 None => problems.push(Problem::at(
369 id,
370 format!("cannot be turned off: no input gives {} for {}", out.ty, out.name),
371 )),
372 }
373 }
374 forwards.insert(id.clone(), map);
375 }
376
377 for (name, e) in &self.outputs {
379 if type_of(e).is_none() {
380 problems.push(Problem::graph(format!("output {name}: {e} is not a source or a node's output")));
381 }
382 }
383
384 let mut order = Vec::new();
386 let mut state: BTreeMap<String, u8> = BTreeMap::new();
387 fn visit(
388 id: &str,
389 inputs: &BTreeMap<String, BTreeMap<String, Endpoint>>,
390 nodes: &BTreeMap<String, Node>,
391 state: &mut BTreeMap<String, u8>,
392 order: &mut Vec<String>,
393 problems: &mut Vec<Problem>,
394 ) {
395 if !nodes.contains_key(id) {
396 return;
397 }
398 match state.get(id) {
399 Some(1) => {
400 problems.push(Problem::at(id, "the graph loops back through it"));
401 return;
402 }
403 Some(_) => return,
404 None => {}
405 }
406 state.insert(id.to_string(), 1);
407 if let Some(feeds) = inputs.get(id) {
408 for f in feeds.values() {
409 visit(&f.node, inputs, nodes, state, order, problems);
410 }
411 }
412 state.insert(id.to_string(), 2);
413 order.push(id.to_string());
414 }
415 for e in self.outputs.values() {
416 visit(&e.node, &inputs, &self.nodes, &mut state, &mut order, &mut problems);
417 }
418 if !problems.is_empty() {
419 problems.dedup();
420 return Err(problems);
421 }
422
423 let mut readers: BTreeMap<Endpoint, usize> = BTreeMap::new();
425 let mut sources = BTreeSet::new();
426 let read = |e: &Endpoint, readers: &mut BTreeMap<Endpoint, usize>, sources: &mut BTreeSet<String>| {
427 *readers.entry(e.clone()).or_default() += 1;
428 if e.port.is_none() {
429 sources.insert(e.node.clone());
430 }
431 };
432 for id in &order {
433 let feeds: Vec<&Endpoint> = match forwards.get(id) {
434 Some(f) => f.values().collect(),
435 None => inputs.get(id).map(|i| i.values().collect()).unwrap_or_default(),
436 };
437 for e in feeds {
438 read(e, &mut readers, &mut sources);
439 }
440 }
441 for e in self.outputs.values() {
442 read(e, &mut readers, &mut sources);
443 }
444
445 let mut need_out: BTreeMap<String, Margin> = BTreeMap::new();
447 let mut at_sources = Margin::NONE;
448 for id in order.iter().rev() {
449 let own = if forwards.contains_key(id) {
450 Margin::NONE
451 } else {
452 catalog.get(&self.nodes[id].op).map(|s| s.margin).unwrap_or_default()
453 };
454 let need_in = own.then(need_out.get(id).copied().unwrap_or_default());
455 let feeds: Vec<&Endpoint> = match forwards.get(id) {
456 Some(f) => f.values().collect(),
457 None => inputs.get(id).map(|i| i.values().collect()).unwrap_or_default(),
458 };
459 for f in feeds {
460 if f.port.is_none() {
461 at_sources = at_sources.max(need_in);
462 } else {
463 let e = need_out.entry(f.node.clone()).or_default();
464 *e = e.max(need_in);
465 }
466 }
467 }
468
469 let inputs = order.iter().map(|id| (id.clone(), inputs.remove(id).unwrap_or_default())).collect();
470 let params = order.iter().filter_map(|id| params.remove(id).map(|p| (id.clone(), p))).collect();
471 let ops = order.iter().filter_map(|id| ops.remove(id).map(|o| (id.clone(), o))).collect();
472 Ok(Plan {
473 order,
474 ops,
475 inputs,
476 params,
477 forwards,
478 sources,
479 outputs: self.outputs.clone(),
480 margin: at_sources,
481 readers,
482 })
483 }
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489 use crate::ops::{OpSpec, PortSpec};
490 use crate::params::ParamSpec;
491
492 fn catalog() -> Catalog {
493 let mut c = Catalog::new(["image", "mask", "table"].map(Type::new));
494 c.add(
495 OpSpec::new("blur", "Blur")
496 .input(PortSpec::new("image", "image"))
497 .output(PortSpec::new("image", "image"))
498 .param(ParamSpec::number("sigma", 2.0).range(0.2, 20.0))
499 .margin(Margin::around(6, 2)),
500 )
501 .unwrap();
502 c.add(
503 OpSpec::new("otsu", "Otsu")
504 .input(PortSpec::new("image", "image"))
505 .output(PortSpec::new("mask", "mask"))
506 .margin(Margin::around(1, 2)),
507 )
508 .unwrap();
509 c.add(
510 OpSpec::new("and", "And")
511 .input(PortSpec::new("a", "mask"))
512 .input(PortSpec::new("b", "mask").optional())
513 .output(PortSpec::new("mask", "mask")),
514 )
515 .unwrap();
516 c.add(
517 OpSpec::new("count", "Count").input(PortSpec::new("mask", "mask")).output(PortSpec::new("counts", "table")),
518 )
519 .unwrap();
520 c
521 }
522
523 fn e(s: &str) -> Endpoint {
524 s.parse().unwrap()
525 }
526
527 fn graph() -> Pipeline {
529 let mut g = Pipeline::new("test");
530 g.sources.insert("nuclei".into(), Type::new("image"));
531 g.nodes.insert("blur".into(), Node::new("blur").with("sigma", ParamValue::Integer(3)));
532 g.nodes.insert("otsu".into(), Node::new("otsu"));
533 g.nodes.insert("and".into(), Node::new("and"));
534 g.nodes.insert("count".into(), Node::new("count"));
535 g.nodes.insert("blur2".into(), Node::new("blur"));
536 for (a, b) in [
537 ("nuclei", "blur.image"),
538 ("blur.image", "otsu.image"),
539 ("otsu.mask", "and.a"),
540 ("and.mask", "count.mask"),
541 ("nuclei", "blur2.image"),
542 ] {
543 g.connect(e(a), e(b));
544 }
545 g.outputs.insert("counts".into(), e("count.counts"));
546 g.outputs.insert("mask".into(), e("otsu.mask"));
547 g
548 }
549
550 #[test]
551 fn a_good_pipeline_plans_in_order_with_its_margin() {
552 let plan = graph().check(&catalog()).unwrap();
553 assert_eq!(plan.order, ["blur", "otsu", "and", "count"], "blur2 leads nowhere");
554 assert_eq!(plan.params["blur"]["sigma"], ParamValue::Number(3.0));
555 assert_eq!(plan.margin, Margin::around(7, 2), "blur 6 then otsu 1");
556 assert_eq!(plan.readers[&e("otsu.mask")], 2, "and, and the mask output");
557 assert_eq!(plan.sources, BTreeSet::from(["nuclei".to_string()]));
558 assert!(!plan.inputs["and"].contains_key("b"), "an optional input may stay open");
559 }
560
561 #[test]
562 fn every_problem_is_reported_at_once() {
563 let mut g = graph();
564 g.nodes.insert("ghost".into(), Node::new("nope"));
565 g.nodes.get_mut("blur").unwrap().params.insert("sigma".into(), ParamValue::Number(99.0));
566 g.connect(e("nuclei"), e("count.mask")); g.edges.retain(|x| x.1 != e("and.a")); let problems = g.check(&catalog()).unwrap_err();
569 let text: Vec<String> = problems.iter().map(|p| p.to_string()).collect();
570 for want in [
571 "ghost: no operation",
572 "blur: sigma is at most 20",
573 "count: mask takes mask, but nuclei gives image",
574 "and: a is not connected",
575 ] {
576 assert!(text.iter().any(|t| t.starts_with(want)), "{want:?} in {text:?}");
577 }
578 }
579
580 #[test]
581 fn loops_are_found() {
582 let mut g = graph();
583 g.connect(e("and.mask"), e("and.b"));
584 let problems = g.check(&catalog()).unwrap_err();
585 assert!(problems.iter().any(|p| p.message.contains("loops")), "{problems:?}");
586 }
587
588 #[test]
589 fn a_disabled_node_passes_its_input_on() {
590 let mut g = graph();
591 g.nodes.get_mut("blur").unwrap().enabled = false;
592 let plan = g.check(&catalog()).unwrap();
593 assert_eq!(plan.forwards["blur"]["image"], e("nuclei"));
594 assert_eq!(plan.margin, Margin::around(1, 2), "blur's margin no longer counts");
595 g.nodes.get_mut("otsu").unwrap().enabled = false;
597 assert!(g.check(&catalog()).unwrap_err().iter().any(|p| p.message.contains("cannot be turned off")));
598 }
599
600 #[test]
601 fn reads_and_writes_json() {
602 let g = graph();
603 let back = Pipeline::from_json(&g.to_json()).unwrap();
604 assert_eq!(back, g);
605 let text = r#"{"sources":{"a":"image"},"nodes":{"b":{"op":"blur"}},"edges":[["a","b.image"]],"outputs":{"o":"b.image"}}"#;
606 let g = Pipeline::from_json(text).unwrap();
607 assert_eq!(g.version, PIPELINE_VERSION);
608 assert!(g.check(&catalog()).is_ok());
609 assert!(Pipeline::from_json(r#"{"version":9,"sources":{},"outputs":{}}"#).is_err());
610 assert!(Pipeline::from_json(r#"{"kitchen_pipeline":1,"sources":{},"outputs":{}}"#).is_ok());
612 assert!("a.b.c".parse::<Endpoint>().is_err());
613 }
614}