kitchen_contract/
catalog.rs1use std::collections::BTreeMap;
7
8use crate::ops::{OpSource, OpSpec};
9use crate::types::Type;
10
11#[derive(Clone, Debug, Default)]
13pub struct Catalog {
14 specs: BTreeMap<String, OpSpec>,
15 types: Vec<Type>,
16}
17
18impl Catalog {
19 pub fn new(types: impl IntoIterator<Item = Type>) -> Self {
21 Self { specs: BTreeMap::new(), types: types.into_iter().collect() }
22 }
23
24 pub fn types(&self) -> &[Type] {
26 &self.types
27 }
28
29 pub fn knows(&self, ty: &Type) -> bool {
31 ty.as_str() == Type::ANY || self.types.contains(ty)
32 }
33
34 pub fn add(&mut self, spec: OpSpec) -> Result<(), String> {
37 spec.check()?;
38 if let Some(p) = spec.inputs.iter().chain(&spec.outputs).find(|p| !self.knows(&p.ty)) {
39 let known: Vec<&str> = self.types.iter().map(Type::as_str).collect();
40 return Err(format!("{}: port {} has type {}, not one of {}", spec.id, p.name, p.ty, known.join(", ")));
41 }
42 self.specs.insert(spec.id.clone(), spec);
43 Ok(())
44 }
45
46 pub fn remove(&mut self, id: &str) -> bool {
48 self.specs.remove(id).is_some()
49 }
50
51 pub fn get(&self, id: &str) -> Option<&OpSpec> {
53 self.specs.get(id)
54 }
55
56 pub fn all(&self) -> impl Iterator<Item = &OpSpec> {
58 self.specs.values()
59 }
60
61 pub fn len(&self) -> usize {
63 self.specs.len()
64 }
65
66 pub fn is_empty(&self) -> bool {
68 self.specs.is_empty()
69 }
70
71 pub fn by_family(&self) -> Vec<(String, Vec<&OpSpec>)> {
74 let mut out: BTreeMap<String, Vec<&OpSpec>> = BTreeMap::new();
75 for s in self.specs.values() {
76 let family = if !s.family.is_empty() {
77 s.family.clone()
78 } else {
79 match &s.source {
80 OpSource::Builtin => "Other".into(),
81 OpSource::Script { .. } => "Scripts".into(),
82 OpSource::Tool { tool, .. } => tool.clone(),
83 OpSource::Recipe { .. } => "Recipes".into(),
84 }
85 };
86 out.entry(family).or_default().push(s);
87 }
88 let mut out: Vec<(String, Vec<&OpSpec>)> = out.into_iter().collect();
89 for (_, ops) in &mut out {
90 ops.sort_by_key(|o| o.title.to_lowercase());
91 }
92 out
93 }
94
95 pub fn taking(&self, ty: &Type) -> Vec<&OpSpec> {
97 self.specs.values().filter(|s| s.inputs.iter().any(|p| ty.feeds(&p.ty))).collect()
98 }
99
100 pub fn fillable_by(&self, offers: &[Type]) -> Vec<&OpSpec> {
103 self.specs
104 .values()
105 .filter(|s| s.inputs.iter().filter(|p| !p.optional).all(|p| offers.iter().any(|o| o.feeds(&p.ty))))
106 .collect()
107 }
108
109 pub fn search(&self, query: &str) -> Vec<&OpSpec> {
112 let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
113 self.specs
114 .values()
115 .filter(|s| {
116 let text = format!("{} {} {} {}", s.title, s.id, s.family, s.summary).to_lowercase();
117 words.iter().all(|w| text.contains(w))
118 })
119 .collect()
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::ops::PortSpec;
127 use crate::params::ParamSpec;
128
129 fn catalog() -> Catalog {
130 let mut c = Catalog::new(["image", "mask", "table"].map(Type::new));
131 c.add(
132 OpSpec::new("blur", "Gaussian blur")
133 .family("Filter")
134 .input(PortSpec::new("image", "image"))
135 .output(PortSpec::new("image", "image"))
136 .param(ParamSpec::number("sigma", 2.0)),
137 )
138 .unwrap();
139 c.add(
140 OpSpec::new("otsu", "Otsu threshold")
141 .family("Threshold")
142 .input(PortSpec::new("image", "image"))
143 .output(PortSpec::new("mask", "mask")),
144 )
145 .unwrap();
146 c.add(
147 OpSpec::new("count", "Count objects")
148 .summary("Counts the objects of a mask")
149 .input(PortSpec::new("mask", "mask"))
150 .output(PortSpec::new("counts", "table")),
151 )
152 .unwrap();
153 c
154 }
155
156 #[test]
157 fn refuses_unknown_types() {
158 let mut c = catalog();
159 let err = c
160 .add(
161 OpSpec::new("hp", "High-pass").input(PortSpec::new("x", "signal")).output(PortSpec::new("x", "signal")),
162 )
163 .unwrap_err();
164 assert!(err.contains("signal") && err.contains("image, mask, table"), "{err}");
165 assert_eq!(c.len(), 3);
166 }
167
168 #[test]
169 fn groups_finds_and_follows() {
170 let c = catalog();
171 let grouped = c.by_family();
172 let families: Vec<&str> = grouped.iter().map(|(f, _)| f.as_str()).collect();
173 assert_eq!(families, ["Filter", "Other", "Threshold"]);
174 let after_mask: Vec<&str> = c.taking(&Type::new("mask")).iter().map(|s| s.id.as_str()).collect();
175 assert_eq!(after_mask, ["count"]);
176 assert_eq!(c.search("objects COUNT").len(), 1);
177 assert_eq!(c.search("thresh").first().map(|s| s.id.as_str()), Some("otsu"));
178 }
179
180 #[test]
181 fn a_screen_lists_the_ops_its_offers_can_run() {
182 let c = catalog();
183 let fill = |offers: &[&str]| -> Vec<String> {
184 c.fillable_by(&offers.iter().map(Type::new).collect::<Vec<_>>()).iter().map(|s| s.id.clone()).collect()
185 };
186 assert_eq!(fill(&["image"]), ["blur", "otsu"]);
187 assert_eq!(fill(&["mask"]), ["count"]);
188 assert!(fill(&["table"]).is_empty());
189 }
190}