1use std::path::PathBuf;
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use crate::params::ParamSpec;
14use crate::types::Type;
15
16#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
18pub struct PortSpec {
19 pub name: String,
21 #[serde(rename = "type")]
23 pub ty: Type,
24 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
26 pub optional: bool,
27 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
30 pub many: bool,
31}
32
33impl PortSpec {
34 pub fn new(name: impl Into<String>, ty: impl AsRef<str>) -> Self {
36 Self { name: name.into(), ty: Type::new(ty), optional: false, many: false }
37 }
38
39 pub fn optional(mut self) -> Self {
41 self.optional = true;
42 self
43 }
44
45 pub fn many(mut self) -> Self {
47 self.many = true;
48 self
49 }
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55pub struct Margin {
56 pub before: [usize; 3],
58 pub after: [usize; 3],
60}
61
62impl Margin {
63 pub const NONE: Margin = Margin { before: [0; 3], after: [0; 3] };
65
66 pub fn around(n: usize, axes: usize) -> Self {
69 let mut m = Margin::NONE;
70 for a in (3 - axes.min(3))..3 {
71 m.before[a] = n;
72 m.after[a] = n;
73 }
74 m
75 }
76
77 pub fn time(before: usize, after: usize) -> Self {
79 Margin { before: [0, 0, before], after: [0, 0, after] }
80 }
81
82 pub fn then(self, next: Margin) -> Margin {
84 let mut m = self;
85 for a in 0..3 {
86 m.before[a] += next.before[a];
87 m.after[a] += next.after[a];
88 }
89 m
90 }
91
92 pub fn max(self, other: Margin) -> Margin {
94 let mut m = self;
95 for a in 0..3 {
96 m.before[a] = m.before[a].max(other.before[a]);
97 m.after[a] = m.after[a].max(other.after[a]);
98 }
99 m
100 }
101
102 pub fn is_none(&self) -> bool {
104 *self == Margin::NONE
105 }
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
110#[serde(rename_all = "lowercase")]
111pub enum Language {
112 Python,
114 Rust,
116}
117
118impl Language {
119 pub fn of(path: &std::path::Path) -> Option<Language> {
121 match path.extension()?.to_str()? {
122 "py" => Some(Language::Python),
123 "rs" => Some(Language::Rust),
124 _ => None,
125 }
126 }
127
128 pub fn comment(self) -> &'static str {
130 match self {
131 Language::Python => "#",
132 Language::Rust => "//",
133 }
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
139#[serde(tag = "from", rename_all = "snake_case")]
140pub enum OpSource {
141 Builtin,
143 Script {
145 path: PathBuf,
147 language: Language,
149 hash: String,
151 },
152 Tool {
154 tool: String,
156 operation: String,
158 },
159 Recipe {
162 hash: String,
164 },
165}
166
167fn one() -> u32 {
168 1
169}
170
171fn yes() -> bool {
172 true
173}
174
175fn is_one(v: &u32) -> bool {
176 *v == 1
177}
178
179fn is_true(v: &bool) -> bool {
180 *v
181}
182
183#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
186pub struct OpSpec {
187 pub id: String,
189 #[serde(default = "one", skip_serializing_if = "is_one")]
192 pub version: u32,
193 pub title: String,
195 #[serde(default)]
197 pub family: String,
198 #[serde(default)]
200 pub summary: String,
201 pub inputs: Vec<PortSpec>,
203 pub outputs: Vec<PortSpec>,
205 #[serde(default)]
207 pub params: Vec<ParamSpec>,
208 #[serde(default, alias = "context")]
210 pub margin: Margin,
211 pub source: OpSource,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub finish: Option<String>,
217 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
220 pub effects: bool,
221 #[serde(default = "yes", skip_serializing_if = "is_true")]
223 pub available: bool,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub unavailable: Option<String>,
227}
228
229impl OpSpec {
230 pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
232 Self {
233 id: id.into(),
234 version: 1,
235 title: title.into(),
236 family: String::new(),
237 summary: String::new(),
238 inputs: Vec::new(),
239 outputs: Vec::new(),
240 params: Vec::new(),
241 margin: Margin::NONE,
242 source: OpSource::Builtin,
243 finish: None,
244 effects: false,
245 available: true,
246 unavailable: None,
247 }
248 }
249
250 pub fn family(mut self, family: impl Into<String>) -> Self {
252 self.family = family.into();
253 self
254 }
255
256 pub fn summary(mut self, summary: impl Into<String>) -> Self {
258 self.summary = summary.into();
259 self
260 }
261
262 pub fn input(mut self, port: PortSpec) -> Self {
264 self.inputs.push(port);
265 self
266 }
267
268 pub fn output(mut self, port: PortSpec) -> Self {
270 self.outputs.push(port);
271 self
272 }
273
274 pub fn param(mut self, param: ParamSpec) -> Self {
276 self.params.push(param);
277 self
278 }
279
280 pub fn margin(mut self, margin: Margin) -> Self {
282 self.margin = margin;
283 self
284 }
285
286 pub fn context(self, margin: Margin) -> Self {
288 self.margin(margin)
289 }
290
291 pub fn version(mut self, version: u32) -> Self {
293 self.version = version;
294 self
295 }
296
297 pub fn finish(mut self, finish: impl Into<String>) -> Self {
299 self.finish = Some(finish.into());
300 self
301 }
302
303 pub fn effects(mut self) -> Self {
305 self.effects = true;
306 self
307 }
308
309 pub fn unavailable(mut self, why: impl Into<String>) -> Self {
311 self.available = false;
312 self.unavailable = Some(why.into());
313 self
314 }
315
316 pub fn version_key(&self) -> String {
318 match &self.source {
319 OpSource::Script { hash, .. } | OpSource::Recipe { hash } => hash.clone(),
320 OpSource::Builtin | OpSource::Tool { .. } => format!("v{}", self.version),
321 }
322 }
323
324 pub fn input_port(&self, name: &str) -> Option<&PortSpec> {
326 self.inputs.iter().find(|p| p.name == name)
327 }
328
329 pub fn output_port(&self, name: &str) -> Option<&PortSpec> {
331 self.outputs.iter().find(|p| p.name == name)
332 }
333
334 pub fn check(&self) -> Result<(), String> {
337 let id = &self.id;
338 if id.trim().is_empty() {
339 return Err("an operation needs an id".into());
340 }
341 if self.outputs.is_empty() {
342 return Err(format!("{id}: no outputs"));
343 }
344 if self.version == 0 {
345 return Err(format!("{id}: versions start at 1"));
346 }
347 if !self.available && self.unavailable.is_none() {
348 return Err(format!("{id}: unavailable without a reason"));
349 }
350 for (what, names) in [
351 ("input", self.inputs.iter().map(|p| &p.name).collect::<Vec<_>>()),
352 ("output", self.outputs.iter().map(|p| &p.name).collect()),
353 ("parameter", self.params.iter().map(|p| &p.name).collect()),
354 ] {
355 let mut seen = std::collections::BTreeSet::new();
356 for n in names {
357 if n.is_empty() || !n.chars().all(|c| c.is_alphanumeric() || c == '_') {
358 return Err(format!("{id}: {what} name {n:?} (letters, digits and _ only)"));
359 }
360 if !seen.insert(n) {
361 return Err(format!("{id}: {what} {n} twice"));
362 }
363 }
364 }
365 for p in &self.params {
366 p.check(&p.default).map_err(|e| format!("{id}: default of {e}"))?;
367 }
368 Ok(())
369 }
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 use crate::params::ParamSpec;
377
378 fn blur() -> OpSpec {
379 OpSpec::new("gaussian_blur", "Gaussian blur")
380 .family("Filter")
381 .input(PortSpec::new("image", "image"))
382 .output(PortSpec::new("image", "image"))
383 .param(ParamSpec::number("sigma", 2.0).range(0.2, 20.0))
384 .margin(Margin::around(6, 2))
385 }
386
387 #[test]
388 fn a_well_formed_spec_checks() {
389 blur().check().unwrap();
390 let twice = blur().input(PortSpec::new("image", "mask"));
392 assert!(twice.check().unwrap_err().contains("input image twice"));
393 let no_out = OpSpec::new("x", "X").input(PortSpec::new("a", "image"));
394 assert!(no_out.check().unwrap_err().contains("no outputs"));
395 let bad_default = blur().param(ParamSpec::number("gain", 50.0).range(0.0, 10.0));
396 assert!(bad_default.check().unwrap_err().contains("default"));
397 let bad_name = blur().param(ParamSpec::number("two words", 1.0));
398 assert!(bad_name.check().is_err());
399 assert!(blur().version(0).check().unwrap_err().contains("start at 1"));
400 }
401
402 #[test]
403 fn versions_effects_and_availability() {
404 let b = blur();
405 assert_eq!(b.version, 1);
406 assert_eq!(b.version_key(), "v1");
407 assert_eq!(blur().version(3).version_key(), "v3");
408 let mut script = blur();
409 script.source = OpSource::Script { path: "a.py".into(), language: Language::Python, hash: "sha256:ab".into() };
410 assert_eq!(script.version_key(), "sha256:ab", "a script is versioned by its hash");
411 let upload = OpSpec::new("dandi_upload", "Upload to DANDI")
412 .input(PortSpec::new("x", "file"))
413 .output(PortSpec::new("receipt", "table"))
414 .effects();
415 let json = serde_json::to_string(&upload).unwrap();
416 assert!(json.contains(r#""effects":true"#) && !json.contains("version"), "{json}");
417 let sam = blur().unavailable("weights not downloaded");
418 assert!(!sam.available);
419 sam.check().unwrap();
420 let mut silent = blur();
421 silent.available = false;
422 assert!(silent.check().is_err());
423 let old: OpSpec = serde_json::from_str(r#"{"id":"x","title":"X","inputs":[],"outputs":[{"name":"o","type":"image"}],"context":{"before":[0,0,3],"after":[0,0,3]},"source":{"from":"builtin"}}"#).unwrap();
425 assert_eq!(old.margin, Margin::time(3, 3));
426 }
427
428 #[test]
429 fn margins_add_along_a_pipeline_and_take_the_larger_at_a_join() {
430 let blur = Margin::around(12, 2);
431 assert_eq!(blur.before, [0, 12, 12]);
432 let along = blur.then(Margin::around(3, 2));
433 assert_eq!(along.after, [0, 15, 15]);
434 let filter = Margin::time(300, 0);
435 assert_eq!(filter.max(Margin::time(10, 40)), Margin::time(300, 40));
436 assert!(Margin::NONE.is_none());
437 }
438
439 #[test]
440 fn specs_read_and_write_json() {
441 let spec = blur();
442 let json = serde_json::to_string(&spec).unwrap();
443 assert!(json.contains(r#""from":"builtin""#));
444 let back: OpSpec = serde_json::from_str(&json).unwrap();
445 assert_eq!(back, spec);
446 assert_eq!(Language::of(std::path::Path::new("a/b.py")), Some(Language::Python));
447 }
448}