Skip to main content

kitchen_contract/
types.rs

1//! Types: what flows between ops and what is stored ([standard §1](../../../standard/spec/01-types.md)).
2//!
3//! One type system for both: a port says `table`; the result it produced says `table` in
4//! `parquet`. This merges kitchen-pipeline's port types and kitchen-artifacts' kinds
5//! (`zarr/ome`, `table/parquet`), which named the same things at two moments
6//! ([`from_kind`] reads the old kinds).
7//!
8//! - **Shared types** have bare names, defined by the standard ([`shared`]).
9//! - **App types** are namespaced, `<namespace>:<name>` (`dspk:sorting`, `lucem:cells`).
10//! - An output of type `T` feeds an input of type `T`, or of `any`. There is no inheritance.
11
12use std::borrow::Cow;
13use std::fmt;
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16use serde::{Deserialize, Serialize};
17
18/// A type's name: `image`, `signal`, or an app's `dspk:sorting`. `any` accepts every type.
19#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(transparent)]
21pub struct Type(pub String);
22
23impl Type {
24    /// The type every input of type `any` accepts, and every type is.
25    pub const ANY: &'static str = "any";
26
27    /// The type named `name`, trimmed and lowercased (lenient: [`Type::parse`] checks the name).
28    pub fn new(name: impl AsRef<str>) -> Self {
29        Type(name.as_ref().trim().to_lowercase())
30    }
31
32    /// `name` as a type, checked: lowercase letters, digits and `-`, optionally after one
33    /// `<namespace>:` of the same characters.
34    pub fn parse(name: &str) -> Result<Self, String> {
35        let ok = |part: &str| {
36            !part.is_empty() && part.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
37        };
38        let valid = match name.split_once(':') {
39            Some((ns, n)) => ok(ns) && ok(n),
40            None => ok(name),
41        };
42        if valid {
43            Ok(Type(name.to_string()))
44        } else {
45            Err(format!("type {name:?}: lowercase letters, digits and '-', as `name` or `namespace:name`"))
46        }
47    }
48
49    /// Its name.
50    pub fn as_str(&self) -> &str {
51        &self.0
52    }
53
54    /// The namespace of an app type (`dspk` of `dspk:sorting`); `None` for a shared type.
55    pub fn namespace(&self) -> Option<&str> {
56        self.0.split_once(':').map(|(ns, _)| ns)
57    }
58
59    /// Whether an output of type `self` may feed an input of type `input`.
60    pub fn feeds(&self, input: &Type) -> bool {
61        self == input || input.0 == Self::ANY || self.0 == Self::ANY
62    }
63}
64
65impl fmt::Display for Type {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(&self.0)
68    }
69}
70
71impl JsonSchema for Type {
72    fn schema_name() -> Cow<'static, str> {
73        "Type".into()
74    }
75
76    fn json_schema(_: &mut SchemaGenerator) -> Schema {
77        json_schema!({
78            "type": "string",
79            "description": "A type's name: a shared type (`image`) or an app's (`dspk:sorting`).",
80            "pattern": "^([a-z0-9-]+:)?[a-z0-9-]+$"
81        })
82    }
83}
84
85/// How a stored result is encoded: `ome-zarr`, `nwb-zarr`, `parquet`, `csv`, `svg`, `png`.
86#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
87#[serde(transparent)]
88pub struct Format(pub String);
89
90impl Format {
91    /// `name` as a format, checked: lowercase letters, digits, `-`, `_` or `.`.
92    pub fn parse(name: &str) -> Result<Self, String> {
93        let ok = !name.is_empty()
94            && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | '.'));
95        if ok {
96            Ok(Format(name.to_string()))
97        } else {
98            Err(format!("format {name:?}: lowercase letters, digits, '-', '_' or '.'"))
99        }
100    }
101
102    /// Its name.
103    pub fn as_str(&self) -> &str {
104        &self.0
105    }
106}
107
108impl fmt::Display for Format {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        f.write_str(&self.0)
111    }
112}
113
114impl JsonSchema for Format {
115    fn schema_name() -> Cow<'static, str> {
116        "Format".into()
117    }
118
119    fn json_schema(_: &mut SchemaGenerator) -> Schema {
120        json_schema!({
121            "type": "string",
122            "description": "How a stored result is encoded (`ome-zarr`, `parquet`, `svg`).",
123            "pattern": "^[a-z0-9._-]+$"
124        })
125    }
126}
127
128/// An axis of an array type, and the kind of unit along it. The values (a recording's 30 kHz, a
129/// slide's 0.25 µm per pixel) come from each result's metadata, never from the type.
130#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
131pub struct Axis {
132    /// Its name (`channels`, `samples`, `y`).
133    pub name: String,
134    /// The kind of unit along it (`time`, `length`), or `None` for a count (channels).
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub unit: Option<String>,
137}
138
139/// A type, described once: what an agent reads to write an op that takes it correctly
140/// ([standard §1.5](../../../standard/spec/01-types.md)).
141#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
142pub struct TypeDescription {
143    /// Its name.
144    pub name: Type,
145    /// One paragraph: what it is.
146    pub summary: String,
147    /// The formats it can be stored in.
148    #[serde(default, skip_serializing_if = "Vec::is_empty")]
149    pub formats: Vec<Format>,
150    /// For arrays, its axes in order.
151    #[serde(default, skip_serializing_if = "Vec::is_empty")]
152    pub axes: Vec<Axis>,
153}
154
155fn describe(name: &str, summary: &str, formats: &[&str], axes: &[(&str, Option<&str>)]) -> TypeDescription {
156    TypeDescription {
157        name: Type(name.into()),
158        summary: summary.into(),
159        formats: formats.iter().map(|f| Format((*f).into())).collect(),
160        axes: axes.iter().map(|(n, u)| Axis { name: (*n).into(), unit: u.map(String::from) }).collect(),
161    }
162}
163
164/// The shared types ([standard §1.3](../../../standard/spec/01-types.md)).
165pub fn shared() -> Vec<TypeDescription> {
166    vec![
167        describe(
168            "signal",
169            "Samples over time on channels, with a rate.",
170            &["raw", "nwb-zarr", "zarr", "nwb"],
171            &[("channels", None), ("samples", Some("time"))],
172        ),
173        describe("events", "Points in time with labels: spikes, stimuli, TTLs.", &["parquet", "csv", "nwb"], &[]),
174        describe(
175            "image",
176            "Pixels: a plane, a stack, a pyramid; channels.",
177            &["ome-zarr", "ome-tiff", "png"],
178            &[("channels", None), ("z", Some("length")), ("y", Some("length")), ("x", Some("length"))],
179        ),
180        describe("mask", "Yes or no per pixel or sample.", &["ome-zarr", "png"], &[]),
181        describe("labels", "An integer per pixel or sample: objects.", &["ome-zarr"], &[]),
182        describe(
183            "region",
184            "Shapes in an image's or a recording's coordinates: polygons, intervals.",
185            &["geojson", "geoparquet", "json"],
186            &[],
187        ),
188        describe("table", "Rows and named columns.", &["parquet", "csv"], &[]),
189        describe(
190            "figure",
191            "Something to look at: static, or a description an app draws (decision 0013).",
192            &["svg", "png", "pdf", "plot-json"],
193            &[],
194        ),
195        describe(
196            "video",
197            "Frames with exact times.",
198            &["mp4", "image-sequence"],
199            &[("frames", Some("time")), ("y", Some("length")), ("x", Some("length"))],
200        ),
201        describe("file", "Anything else, opaque.", &[], &[]),
202        describe("any", "Accepts every type (inputs only).", &[], &[]),
203    ]
204}
205
206/// The type and format of an old artifact kind (`family/format`, kitchen-artifacts), as the
207/// contract names them; `None` for a kind no type covers.
208///
209/// | Kind | Type | Format |
210/// |---|---|---|
211/// | `raw/*` | `signal` | `raw` |
212/// | `zarr/nwb` | `signal` | `nwb-zarr` |
213/// | `zarr/ome` | `image` | `ome-zarr` |
214/// | `zarr/labels` | `labels` | `ome-zarr` |
215/// | `zarr/sorting` | `dspk:sorting` | `zarr` |
216/// | `table/parquet` | `table` | `parquet` |
217/// | `table/csv` | `table` | `csv` |
218/// | `table/geoparquet` | `region` | `geoparquet` |
219/// | `file/*` | `file` | the format |
220pub fn from_kind(kind: &str) -> Option<(Type, Format)> {
221    let (family, format) = kind.split_once('/')?;
222    let pair = |t: &str, f: &str| Some((Type(t.into()), Format(f.into())));
223    match (family, format) {
224        ("raw", _) => pair("signal", "raw"),
225        ("zarr", "nwb") => pair("signal", "nwb-zarr"),
226        ("zarr", "ome") => pair("image", "ome-zarr"),
227        ("zarr", "labels") => pair("labels", "ome-zarr"),
228        ("zarr", "sorting") => pair("dspk:sorting", "zarr"),
229        ("table", "parquet") => pair("table", "parquet"),
230        ("table", "csv") => pair("table", "csv"),
231        ("table", "geoparquet") => pair("region", "geoparquet"),
232        ("file", f) if !f.is_empty() => pair("file", f),
233        _ => None,
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn types_feed_their_own_and_any() {
243        let (image, mask, any) = (Type::new("Image"), Type::new("mask"), Type::new("any"));
244        assert_eq!(image.as_str(), "image");
245        assert!(image.feeds(&image));
246        assert!(!image.feeds(&mask));
247        assert!(image.feeds(&any));
248        assert!(any.feeds(&mask));
249    }
250
251    #[test]
252    fn names_are_checked_and_namespaced() {
253        assert!(Type::parse("signal").is_ok());
254        assert_eq!(Type::parse("dspk:sorting").unwrap().namespace(), Some("dspk"));
255        assert_eq!(Type::parse("table").unwrap().namespace(), None);
256        for bad in ["Image", "a:b:c", ":x", "x:", "two words", ""] {
257            assert!(Type::parse(bad).is_err(), "{bad:?}");
258        }
259        assert!(Format::parse("ome-zarr").is_ok());
260        assert!(Format::parse("OME").is_err());
261    }
262
263    #[test]
264    fn every_shared_type_is_described_once() {
265        let all = shared();
266        let mut names: Vec<&str> = all.iter().map(|t| t.name.as_str()).collect();
267        names.sort();
268        names.dedup();
269        assert_eq!(names.len(), all.len());
270        for t in &all {
271            Type::parse(t.name.as_str()).unwrap();
272            assert!(!t.summary.is_empty());
273        }
274        let signal = all.iter().find(|t| t.name.as_str() == "signal").unwrap();
275        assert_eq!(signal.axes[1].unit.as_deref(), Some("time"), "units are kinds; the rate is the data's");
276    }
277
278    #[test]
279    fn old_kinds_read_as_type_and_format() {
280        assert_eq!(from_kind("zarr/ome"), Some((Type::new("image"), Format("ome-zarr".into()))));
281        assert_eq!(from_kind("raw/spikeglx").unwrap().0, Type::new("signal"));
282        assert_eq!(from_kind("zarr/sorting").unwrap().0.namespace(), Some("dspk"));
283        assert_eq!(from_kind("table/geoparquet").unwrap().0, Type::new("region"));
284        assert_eq!(from_kind("file/png"), Some((Type::new("file"), Format("png".into()))));
285        assert_eq!(from_kind("zarr/unknown"), None);
286        assert_eq!(from_kind("nonsense"), None);
287    }
288}