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 #[serde(default, skip_serializing_if = "Layout::is_empty")]
179 pub layout: Layout,
180}
181
182#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
184#[serde(deny_unknown_fields)]
185pub struct Layout {
186 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
188 pub sources: BTreeMap<String, [f32; 2]>,
189 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
191 pub outputs: BTreeMap<String, [f32; 2]>,
192}
193
194impl Layout {
195 pub fn is_empty(&self) -> bool {
197 self.sources.is_empty() && self.outputs.is_empty()
198 }
199}
200
201#[derive(Clone, Debug, PartialEq, Eq)]
203pub struct Problem {
204 pub node: Option<String>,
206 pub message: String,
208}
209
210impl Problem {
211 fn at(node: &str, message: impl Into<String>) -> Self {
212 Problem { node: Some(node.to_string()), message: message.into() }
213 }
214
215 fn graph(message: impl Into<String>) -> Self {
216 Problem { node: None, message: message.into() }
217 }
218}
219
220impl fmt::Display for Problem {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 match &self.node {
223 Some(n) => write!(f, "{n}: {}", self.message),
224 None => f.write_str(&self.message),
225 }
226 }
227}
228
229#[derive(Clone, Debug, PartialEq)]
231pub struct Plan {
232 pub order: Vec<String>,
234 pub ops: BTreeMap<String, String>,
236 pub inputs: BTreeMap<String, BTreeMap<String, Endpoint>>,
238 pub params: BTreeMap<String, BTreeMap<String, ParamValue>>,
240 pub forwards: BTreeMap<String, BTreeMap<String, Endpoint>>,
242 pub sources: BTreeSet<String>,
244 pub outputs: BTreeMap<String, Endpoint>,
246 pub margin: Margin,
249 pub readers: BTreeMap<Endpoint, usize>,
252}
253
254impl Plan {
255 pub fn margin_with(&self, own: impl Fn(&str, &str, &BTreeMap<String, ParamValue>) -> Margin) -> Margin {
260 let none = BTreeMap::new();
261 let mut need_out: BTreeMap<String, Margin> = BTreeMap::new();
262 let mut at_sources = Margin::NONE;
263 for id in self.order.iter().rev() {
264 let mine = match self.forwards.contains_key(id) {
265 true => Margin::NONE,
266 false => own(id, &self.ops[id], self.params.get(id).unwrap_or(&none)),
267 };
268 let need_in = mine.then(need_out.get(id).copied().unwrap_or_default());
269 let feeds: Vec<&Endpoint> = match self.forwards.get(id) {
270 Some(f) => f.values().collect(),
271 None => self.inputs.get(id).map(|i| i.values().collect()).unwrap_or_default(),
272 };
273 for f in feeds {
274 if f.port.is_none() {
275 at_sources = at_sources.max(need_in);
276 } else {
277 let e = need_out.entry(f.node.clone()).or_default();
278 *e = e.max(need_in);
279 }
280 }
281 }
282 at_sources
283 }
284}
285
286impl Pipeline {
287 pub fn new(app: impl Into<String>) -> Self {
289 Self {
290 version: PIPELINE_VERSION,
291 app: app.into(),
292 sources: BTreeMap::new(),
293 nodes: BTreeMap::new(),
294 edges: Vec::new(),
295 outputs: BTreeMap::new(),
296 layout: Layout::default(),
297 }
298 }
299
300 pub fn from_json(text: &str) -> Result<Pipeline, String> {
302 let g: Pipeline = serde_json::from_str(text).map_err(|e| e.to_string())?;
303 if g.version > PIPELINE_VERSION {
304 return Err(format!(
305 "format {} is newer than this app reads ({PIPELINE_VERSION}): update the app",
306 g.version
307 ));
308 }
309 Ok(g)
310 }
311
312 pub fn to_json(&self) -> String {
314 serde_json::to_string_pretty(self).unwrap_or_default()
315 }
316
317 pub fn connect(&mut self, from: Endpoint, to: Endpoint) {
319 self.edges.retain(|e| e.1 != to);
320 self.edges.push(Edge(from, to));
321 }
322
323 pub fn check(&self, catalog: &Catalog) -> Result<Plan, Vec<Problem>> {
325 let mut problems = Vec::new();
326 if self.version > PIPELINE_VERSION {
327 problems.push(Problem::graph(format!("format {} is newer than this app reads", self.version)));
328 }
329 for (name, ty) in &self.sources {
330 if self.nodes.contains_key(name) {
331 problems.push(Problem::graph(format!("{name} is both a source and a node")));
332 }
333 if !catalog.knows(ty) {
334 problems.push(Problem::graph(format!("source {name}: type {ty} is not one of the app's")));
335 }
336 }
337 if self.outputs.is_empty() {
338 problems.push(Problem::graph("nothing is written: add an output"));
339 }
340
341 let mut params = BTreeMap::new();
343 let mut ops = BTreeMap::new();
344 for (id, node) in &self.nodes {
345 let Some(spec) = catalog.get(&node.op) else {
346 problems.push(Problem::at(
347 id,
348 format!(
349 "no operation {:?} in this app (another app's op runs in a chain, on the orchestrator)",
350 node.op
351 ),
352 ));
353 continue;
354 };
355 ops.insert(id.clone(), node.op.clone());
356 match check_params(&spec.params, &node.params) {
357 Ok(p) => {
358 params.insert(id.clone(), p);
359 }
360 Err(es) => problems.extend(es.into_iter().map(|e| Problem::at(id, e))),
361 }
362 }
363
364 let type_of = |e: &Endpoint| -> Option<Type> {
366 match &e.port {
367 None => self.sources.get(&e.node).cloned(),
368 Some(p) => catalog.get(&self.nodes.get(&e.node)?.op)?.output_port(p).map(|p| p.ty.clone()),
369 }
370 };
371
372 let mut inputs: BTreeMap<String, BTreeMap<String, Endpoint>> = BTreeMap::new();
374 for Edge(from, to) in &self.edges {
375 let Some(from_ty) = type_of(from) else {
376 problems.push(Problem::graph(format!("{from} → {to}: {from} is not a source or an output")));
377 continue;
378 };
379 let Some(port) = &to.port else {
380 problems.push(Problem::graph(format!("{from} → {to}: a source cannot be fed")));
381 continue;
382 };
383 let Some(spec) = self.nodes.get(&to.node).and_then(|n| catalog.get(&n.op)) else {
384 if !self.nodes.contains_key(&to.node) {
385 problems.push(Problem::graph(format!("{from} → {to}: no node {}", to.node)));
386 }
387 continue;
388 };
389 let Some(input) = spec.input_port(port) else {
390 problems.push(Problem::at(&to.node, format!("{} has no input {port}", spec.title)));
391 continue;
392 };
393 if !from_ty.feeds(&input.ty) {
394 problems.push(Problem::at(&to.node, format!("{port} takes {}, but {from} gives {from_ty}", input.ty)));
395 }
396 if inputs.entry(to.node.clone()).or_default().insert(port.clone(), from.clone()).is_some() {
397 problems.push(Problem::at(&to.node, format!("{port} is fed twice")));
398 }
399 }
400 for (id, node) in &self.nodes {
401 let Some(spec) = catalog.get(&node.op) else { continue };
402 for p in spec.inputs.iter().filter(|p| !p.optional) {
403 if !inputs.get(id).is_some_and(|i| i.contains_key(&p.name)) {
404 problems.push(Problem::at(id, format!("{} is not connected", p.name)));
405 }
406 }
407 }
408
409 let mut forwards = BTreeMap::new();
411 for (id, node) in self.nodes.iter().filter(|(_, n)| !n.enabled) {
412 let Some(spec) = catalog.get(&node.op) else { continue };
413 let mut map = BTreeMap::new();
414 for out in &spec.outputs {
415 let feed = spec
416 .inputs
417 .iter()
418 .filter_map(|p| inputs.get(id).and_then(|i| i.get(&p.name)).filter(|_| p.ty == out.ty))
419 .next();
420 match feed {
421 Some(f) => {
422 map.insert(out.name.clone(), f.clone());
423 }
424 None => problems.push(Problem::at(
425 id,
426 format!("cannot be turned off: no input gives {} for {}", out.ty, out.name),
427 )),
428 }
429 }
430 forwards.insert(id.clone(), map);
431 }
432
433 for (name, e) in &self.outputs {
435 if type_of(e).is_none() {
436 problems.push(Problem::graph(format!("output {name}: {e} is not a source or a node's output")));
437 }
438 }
439
440 let mut order = Vec::new();
442 let mut state: BTreeMap<String, u8> = BTreeMap::new();
443 fn visit(
444 id: &str,
445 inputs: &BTreeMap<String, BTreeMap<String, Endpoint>>,
446 nodes: &BTreeMap<String, Node>,
447 state: &mut BTreeMap<String, u8>,
448 order: &mut Vec<String>,
449 problems: &mut Vec<Problem>,
450 ) {
451 if !nodes.contains_key(id) {
452 return;
453 }
454 match state.get(id) {
455 Some(1) => {
456 problems.push(Problem::at(id, "the graph loops back through it"));
457 return;
458 }
459 Some(_) => return,
460 None => {}
461 }
462 state.insert(id.to_string(), 1);
463 if let Some(feeds) = inputs.get(id) {
464 for f in feeds.values() {
465 visit(&f.node, inputs, nodes, state, order, problems);
466 }
467 }
468 state.insert(id.to_string(), 2);
469 order.push(id.to_string());
470 }
471 for e in self.outputs.values() {
472 visit(&e.node, &inputs, &self.nodes, &mut state, &mut order, &mut problems);
473 }
474 if !problems.is_empty() {
475 problems.dedup();
476 return Err(problems);
477 }
478
479 let mut readers: BTreeMap<Endpoint, usize> = BTreeMap::new();
481 let mut sources = BTreeSet::new();
482 let read = |e: &Endpoint, readers: &mut BTreeMap<Endpoint, usize>, sources: &mut BTreeSet<String>| {
483 *readers.entry(e.clone()).or_default() += 1;
484 if e.port.is_none() {
485 sources.insert(e.node.clone());
486 }
487 };
488 for id in &order {
489 let feeds: Vec<&Endpoint> = match forwards.get(id) {
490 Some(f) => f.values().collect(),
491 None => inputs.get(id).map(|i| i.values().collect()).unwrap_or_default(),
492 };
493 for e in feeds {
494 read(e, &mut readers, &mut sources);
495 }
496 }
497 for e in self.outputs.values() {
498 read(e, &mut readers, &mut sources);
499 }
500
501 let inputs = order.iter().map(|id| (id.clone(), inputs.remove(id).unwrap_or_default())).collect();
502 let params = order.iter().filter_map(|id| params.remove(id).map(|p| (id.clone(), p))).collect();
503 let ops = order.iter().filter_map(|id| ops.remove(id).map(|o| (id.clone(), o))).collect();
504 let mut plan = Plan {
505 order,
506 ops,
507 inputs,
508 params,
509 forwards,
510 sources,
511 outputs: self.outputs.clone(),
512 margin: Margin::NONE,
513 readers,
514 };
515 plan.margin = plan.margin_with(|_, op, _| catalog.get(op).map(|s| s.margin).unwrap_or_default());
516 Ok(plan)
517 }
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523 use crate::ops::{OpSpec, PortSpec};
524 use crate::params::ParamSpec;
525
526 fn catalog() -> Catalog {
527 let mut c = Catalog::new(["image", "mask", "table"].map(Type::new));
528 c.add(
529 OpSpec::new("blur", "Blur")
530 .input(PortSpec::new("image", "image"))
531 .output(PortSpec::new("image", "image"))
532 .param(ParamSpec::number("sigma", 2.0).range(0.2, 20.0))
533 .margin(Margin::around(6, 2)),
534 )
535 .unwrap();
536 c.add(
537 OpSpec::new("otsu", "Otsu")
538 .input(PortSpec::new("image", "image"))
539 .output(PortSpec::new("mask", "mask"))
540 .margin(Margin::around(1, 2)),
541 )
542 .unwrap();
543 c.add(
544 OpSpec::new("and", "And")
545 .input(PortSpec::new("a", "mask"))
546 .input(PortSpec::new("b", "mask").optional())
547 .output(PortSpec::new("mask", "mask")),
548 )
549 .unwrap();
550 c.add(
551 OpSpec::new("count", "Count").input(PortSpec::new("mask", "mask")).output(PortSpec::new("counts", "table")),
552 )
553 .unwrap();
554 c
555 }
556
557 fn e(s: &str) -> Endpoint {
558 s.parse().unwrap()
559 }
560
561 fn graph() -> Pipeline {
563 let mut g = Pipeline::new("test");
564 g.sources.insert("nuclei".into(), Type::new("image"));
565 g.nodes.insert("blur".into(), Node::new("blur").with("sigma", ParamValue::Integer(3)));
566 g.nodes.insert("otsu".into(), Node::new("otsu"));
567 g.nodes.insert("and".into(), Node::new("and"));
568 g.nodes.insert("count".into(), Node::new("count"));
569 g.nodes.insert("blur2".into(), Node::new("blur"));
570 for (a, b) in [
571 ("nuclei", "blur.image"),
572 ("blur.image", "otsu.image"),
573 ("otsu.mask", "and.a"),
574 ("and.mask", "count.mask"),
575 ("nuclei", "blur2.image"),
576 ] {
577 g.connect(e(a), e(b));
578 }
579 g.outputs.insert("counts".into(), e("count.counts"));
580 g.outputs.insert("mask".into(), e("otsu.mask"));
581 g
582 }
583
584 #[test]
585 fn a_good_pipeline_plans_in_order_with_its_margin() {
586 let plan = graph().check(&catalog()).unwrap();
587 assert_eq!(plan.order, ["blur", "otsu", "and", "count"], "blur2 leads nowhere");
588 assert_eq!(plan.params["blur"]["sigma"], ParamValue::Number(3.0));
589 assert_eq!(plan.margin, Margin::around(7, 2), "blur 6 then otsu 1");
590 assert_eq!(plan.readers[&e("otsu.mask")], 2, "and, and the mask output");
591 assert_eq!(plan.sources, BTreeSet::from(["nuclei".to_string()]));
592 assert!(!plan.inputs["and"].contains_key("b"), "an optional input may stay open");
593 }
594
595 #[test]
596 fn a_margin_can_follow_the_parameters() {
597 let plan = graph().check(&catalog()).unwrap();
598 let m = plan.margin_with(|_, op, params| match op {
600 "blur" => Margin::around((4.0 * params["sigma"].as_f64().unwrap()).ceil() as usize, 2),
601 _ => catalog().get(op).unwrap().margin,
602 });
603 assert_eq!(m, Margin::around(13, 2), "blur 12 at sigma 3, then otsu 1");
604 let declared = plan.margin_with(|_, op, _| catalog().get(op).unwrap().margin);
605 assert_eq!(declared, plan.margin, "the check's margin is the declared one");
606 }
607
608 #[test]
609 fn every_problem_is_reported_at_once() {
610 let mut g = graph();
611 g.nodes.insert("ghost".into(), Node::new("nope"));
612 g.nodes.get_mut("blur").unwrap().params.insert("sigma".into(), ParamValue::Number(99.0));
613 g.connect(e("nuclei"), e("count.mask")); g.edges.retain(|x| x.1 != e("and.a")); let problems = g.check(&catalog()).unwrap_err();
616 let text: Vec<String> = problems.iter().map(|p| p.to_string()).collect();
617 for want in [
618 "ghost: no operation",
619 "blur: sigma is at most 20",
620 "count: mask takes mask, but nuclei gives image",
621 "and: a is not connected",
622 ] {
623 assert!(text.iter().any(|t| t.starts_with(want)), "{want:?} in {text:?}");
624 }
625 }
626
627 #[test]
628 fn loops_are_found() {
629 let mut g = graph();
630 g.connect(e("and.mask"), e("and.b"));
631 let problems = g.check(&catalog()).unwrap_err();
632 assert!(problems.iter().any(|p| p.message.contains("loops")), "{problems:?}");
633 }
634
635 #[test]
636 fn a_disabled_node_passes_its_input_on() {
637 let mut g = graph();
638 g.nodes.get_mut("blur").unwrap().enabled = false;
639 let plan = g.check(&catalog()).unwrap();
640 assert_eq!(plan.forwards["blur"]["image"], e("nuclei"));
641 assert_eq!(plan.margin, Margin::around(1, 2), "blur's margin no longer counts");
642 g.nodes.get_mut("otsu").unwrap().enabled = false;
644 assert!(g.check(&catalog()).unwrap_err().iter().any(|p| p.message.contains("cannot be turned off")));
645 }
646
647 #[test]
648 fn reads_and_writes_json() {
649 let g = graph();
650 let back = Pipeline::from_json(&g.to_json()).unwrap();
651 assert_eq!(back, g);
652 let text = r#"{"sources":{"a":"image"},"nodes":{"b":{"op":"blur"}},"edges":[["a","b.image"]],"outputs":{"o":"b.image"}}"#;
653 let g = Pipeline::from_json(text).unwrap();
654 assert_eq!(g.version, PIPELINE_VERSION);
655 assert!(g.check(&catalog()).is_ok());
656 assert!(Pipeline::from_json(r#"{"version":9,"sources":{},"outputs":{}}"#).is_err());
657 assert!(Pipeline::from_json(r#"{"kitchen_pipeline":1,"sources":{},"outputs":{}}"#).is_ok());
659 assert!("a.b.c".parse::<Endpoint>().is_err());
660 }
661}