Skip to main content

zenkey_model/
authoring.rs

1//! The authoring format, draft 4 (`examples/zk2/README.md`, r3.3): the
2//! TOML shape a contract file has, before any validation or defaulting.
3//! Draft 2 is draft 1 plus one spelling, `cardinality = "unbounded"`
4//! ([`Cardinality`], core 0.57, #937). Draft 3 adds `[schemas] packed`
5//! and the `packed:` references (core 0.75, §7.6, #979). Draft 4 adds a
6//! resource's `frame` table ([`FrameSpec`], core 0.83, §7.7, #981). None
7//! changed the canonical form of a contract that does not use what it
8//! adds, so its `format` tag is still `zk2-contract/draft-1`.
9//!
10//! `spec/contract.schema.json` is generated from these types (schemars) and
11//! committed. A test fails when the two drift.
12
13use std::collections::BTreeMap;
14
15use schemars::JsonSchema;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19/// The member under which a float that is not finite (`nan`, `inf`) is
20/// carried through an annotation value. JSON has no such number, and
21/// `serde_json` would turn it into `null` without a word; carried this way,
22/// the canonical-form restriction refuses it (E028, spec §9.5).
23pub const NON_FINITE: &str = "$__zk2_private_non_finite";
24
25/// The member under which the `toml` crate hands a datetime to serde. An
26/// annotation value holding one is E020 (spec §9.1).
27pub const DATETIME: &str = "$__toml_private_datetime";
28
29/// Annotation values are read as TOML values, then turned into JSON: a
30/// datetime and a float that is not finite are kept as marker objects
31/// ([`DATETIME`], [`NON_FINITE`]) for the lints to refuse.
32fn annotations<'de, D: serde::Deserializer<'de>>(
33    d: D,
34) -> Result<BTreeMap<String, Value>, D::Error> {
35    let raw = BTreeMap::<String, toml::Value>::deserialize(d)?;
36    Ok(raw.into_iter().map(|(k, v)| (k, from_toml(v))).collect())
37}
38
39fn from_toml(v: toml::Value) -> Value {
40    match v {
41        toml::Value::String(s) => Value::String(s),
42        toml::Value::Integer(i) => Value::from(i),
43        toml::Value::Float(f) => serde_json::Number::from_f64(f).map_or_else(
44            || {
45                Value::Object(
46                    [(NON_FINITE.to_owned(), Value::String(f.to_string()))]
47                        .into_iter()
48                        .collect(),
49                )
50            },
51            Value::Number,
52        ),
53        toml::Value::Boolean(b) => Value::Bool(b),
54        toml::Value::Datetime(dt) => Value::Object(
55            [(DATETIME.to_owned(), Value::String(dt.to_string()))]
56                .into_iter()
57                .collect(),
58        ),
59        toml::Value::Array(a) => Value::Array(a.into_iter().map(from_toml).collect()),
60        toml::Value::Table(t) => {
61            Value::Object(t.into_iter().map(|(k, v)| (k, from_toml(v))).collect())
62        }
63    }
64}
65
66/// One contract file: one interface major.
67#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
68#[serde(deny_unknown_fields)]
69pub struct ContractFile {
70    pub interface: InterfaceSection,
71    #[serde(default)]
72    pub defaults: Option<DefaultsSection>,
73    #[serde(default)]
74    pub schemas: SchemasSection,
75    #[serde(default)]
76    pub resources: BTreeMap<String, ResourceSpec>,
77    #[serde(default)]
78    pub requires: BTreeMap<String, Requirement>,
79}
80
81/// `[interface]`.
82#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct InterfaceSection {
85    /// `[a-z][a-z0-9_]*` segments joined by `.`; never ending in `.v<int>`.
86    pub name: String,
87    #[schemars(range(max = 4_294_967_295_u32))]
88    pub major: u32,
89    /// Informative; CI keeps it monotonic; not in the fingerprint.
90    #[serde(default)]
91    #[schemars(range(max = 4_294_967_295_u32))]
92    pub minor: Option<u32>,
93    /// Documentation; not in the fingerprint.
94    #[serde(default)]
95    pub summary: Option<String>,
96    /// Profiles whose annotations the contract uses (`freshness.v1`, …).
97    #[serde(default)]
98    pub uses: Vec<String>,
99}
100
101/// `[schemas]`.
102#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct SchemasSection {
105    /// `.proto` files, relative to the contract's directory. proto2/proto3.
106    #[serde(default)]
107    pub protobuf: Vec<String>,
108    /// Include roots for protobuf imports, relative to the contract's
109    /// directory. Default: `["proto"]` when that directory exists, else `["."]`.
110    #[serde(default)]
111    pub proto_include: Option<Vec<String>>,
112    /// JSON Schema 2020-12 files (the zk2 subset), definitions under `$defs`.
113    #[serde(default)]
114    pub jsonschema: Vec<String>,
115    /// Packed files (core §7.6, draft 3): strict JSON, types under `types`,
116    /// referenced as `packed:<Name>` or `packed:<stem>#<Name>`.
117    #[serde(default)]
118    pub packed: Vec<String>,
119}
120
121/// The fields `[defaults]` may set (r3.3 D2).
122#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
123#[serde(deny_unknown_fields)]
124pub struct DefaultsBlock {
125    #[serde(default, deserialize_with = "annotations")]
126    pub annotations: BTreeMap<String, Value>,
127    pub encoding: Option<Encoding>,
128    pub attachment_encoding: Option<Encoding>,
129    pub reliability: Option<Reliability>,
130    pub congestion: Option<Congestion>,
131    pub priority: Option<Priority>,
132    pub express: Option<bool>,
133    pub history: Option<History>,
134    pub idempotent: Option<bool>,
135    pub fanout: Option<Fanout>,
136    pub serving: Option<Serving>,
137    pub replies: Option<Replies>,
138    pub timeout_ms: Option<u64>,
139}
140
141/// `[defaults]` and `[defaults.<kind>]`.
142#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
143#[serde(deny_unknown_fields)]
144pub struct DefaultsSection {
145    #[serde(default, deserialize_with = "annotations")]
146    pub annotations: BTreeMap<String, Value>,
147    pub encoding: Option<Encoding>,
148    pub attachment_encoding: Option<Encoding>,
149    pub reliability: Option<Reliability>,
150    pub congestion: Option<Congestion>,
151    pub priority: Option<Priority>,
152    pub express: Option<bool>,
153    pub history: Option<History>,
154    pub idempotent: Option<bool>,
155    pub fanout: Option<Fanout>,
156    pub serving: Option<Serving>,
157    pub replies: Option<Replies>,
158    pub timeout_ms: Option<u64>,
159    pub stream: Option<DefaultsBlock>,
160    pub state: Option<DefaultsBlock>,
161    pub event: Option<DefaultsBlock>,
162    pub operation: Option<DefaultsBlock>,
163}
164
165impl DefaultsSection {
166    /// The base block (the fields set directly under `[defaults]`).
167    #[must_use]
168    pub fn base(&self) -> DefaultsBlock {
169        DefaultsBlock {
170            annotations: self.annotations.clone(),
171            encoding: self.encoding,
172            attachment_encoding: self.attachment_encoding,
173            reliability: self.reliability,
174            congestion: self.congestion,
175            priority: self.priority,
176            express: self.express,
177            history: self.history.clone(),
178            idempotent: self.idempotent,
179            fanout: self.fanout,
180            serving: self.serving,
181            replies: self.replies,
182            timeout_ms: self.timeout_ms,
183        }
184    }
185    #[must_use]
186    pub fn for_kind(&self, kind: Kind) -> Option<&DefaultsBlock> {
187        match kind {
188            Kind::Stream => self.stream.as_ref(),
189            Kind::State => self.state.as_ref(),
190            Kind::Event => self.event.as_ref(),
191            Kind::Operation => self.operation.as_ref(),
192        }
193    }
194}
195
196/// `[resources."<template>"]`: every field any kind may carry. Which ones
197/// a kind accepts is checked by the lints (E014).
198#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
199#[serde(deny_unknown_fields)]
200pub struct ResourceSpec {
201    pub kind: Kind,
202    #[serde(default)]
203    pub doc: Option<String>,
204    #[serde(default)]
205    pub params: BTreeMap<String, ParamType>,
206    #[serde(default)]
207    pub cardinality: Option<Cardinality>,
208    #[serde(default)]
209    pub epoch: Option<String>,
210    #[serde(default)]
211    pub optional: bool,
212    #[serde(default)]
213    pub gate: Option<Gate>,
214    #[serde(default)]
215    pub deprecated: Option<Deprecated>,
216    #[serde(default, deserialize_with = "annotations")]
217    pub annotations: BTreeMap<String, Value>,
218    // stream, state, event
219    #[serde(default, rename = "type")]
220    pub type_: Option<TypeRef>,
221    #[serde(default)]
222    pub attachment: Option<TypeRef>,
223    #[serde(default)]
224    pub encoding: Option<Encoding>,
225    #[serde(default)]
226    pub attachment_encoding: Option<Encoding>,
227    #[serde(default)]
228    pub explicit: Option<bool>,
229    #[serde(default)]
230    pub reliability: Option<Reliability>,
231    #[serde(default)]
232    pub congestion: Option<Congestion>,
233    #[serde(default)]
234    pub priority: Option<Priority>,
235    #[serde(default)]
236    pub express: Option<bool>,
237    #[serde(default)]
238    pub history: Option<History>,
239    /// A frame resource's `frame` table (core §7.7, draft 4): a plain
240    /// stream's alone, never defaulted.
241    #[serde(default)]
242    pub frame: Option<FrameSpec>,
243    #[serde(default)]
244    pub rate: Option<String>,
245    #[serde(default)]
246    pub retention: Option<String>,
247    // operation
248    #[serde(default)]
249    pub request: Option<TypeRef>,
250    #[serde(default)]
251    pub response: Option<TypeRef>,
252    #[serde(default)]
253    pub error: Option<TypeRef>,
254    #[serde(default)]
255    pub idempotent: Option<bool>,
256    #[serde(default)]
257    pub fanout: Option<Fanout>,
258    #[serde(default)]
259    pub serving: Option<Serving>,
260    #[serde(default)]
261    pub replies: Option<Replies>,
262    #[serde(default)]
263    pub summary: Option<TypeRef>,
264    #[serde(default)]
265    pub timeout_ms: Option<u64>,
266}
267
268/// `[requires.<role>]`.
269#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
270#[serde(deny_unknown_fields)]
271pub struct Requirement {
272    /// The required interface, `<name>.v<major>`.
273    pub interface: String,
274    /// What is consumed; default: everything.
275    #[serde(default)]
276    pub resources: Option<Vec<String>>,
277    #[serde(default)]
278    pub cardinality: Option<RequireCardinality>,
279    #[serde(default)]
280    pub optional: bool,
281    #[serde(default)]
282    pub doc: Option<String>,
283    #[serde(default, deserialize_with = "annotations")]
284    pub annotations: BTreeMap<String, Value>,
285}
286
287#[derive(
288    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, JsonSchema,
289)]
290#[serde(rename_all = "lowercase")]
291pub enum Kind {
292    Stream,
293    State,
294    Event,
295    Operation,
296}
297
298impl Kind {
299    #[must_use]
300    pub fn as_str(self) -> &'static str {
301        match self {
302            Self::Stream => "stream",
303            Self::State => "state",
304            Self::Event => "event",
305            Self::Operation => "operation",
306        }
307    }
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
311#[serde(rename_all = "lowercase")]
312pub enum ParamType {
313    String,
314    Uint,
315    Path,
316}
317
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
319#[serde(rename_all = "lowercase")]
320pub enum Encoding {
321    Json,
322    Cbor,
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
326#[serde(rename_all = "snake_case")]
327pub enum Reliability {
328    BestEffort,
329    Reliable,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
333#[serde(rename_all = "lowercase")]
334pub enum Congestion {
335    Drop,
336    Block,
337}
338
339/// Zenoh's seven priorities, by name.
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
341#[serde(rename_all = "snake_case")]
342pub enum Priority {
343    RealTime,
344    InteractiveHigh,
345    InteractiveLow,
346    DataHigh,
347    Data,
348    DataLow,
349    Background,
350}
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
353#[serde(rename_all = "lowercase")]
354pub enum Fanout {
355    Forbidden,
356    Allowed,
357}
358
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
360#[serde(rename_all = "lowercase")]
361pub enum Serving {
362    Exclusive,
363    Replicated,
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
367#[serde(rename_all = "lowercase")]
368pub enum Replies {
369    One,
370    Many,
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
374#[serde(rename_all = "lowercase")]
375pub enum RequireCardinality {
376    One,
377    Many,
378}
379
380/// A type reference: `"pkg.Message"`, `"json:Name"`, `"json:stem#Name"`,
381/// `"packed:Name"`, `"packed:stem#Name"`, or
382/// `{ raw = "<media type>", media_param = "<param>" }`.
383#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
384#[serde(untagged)]
385pub enum TypeRef {
386    Named(String),
387    Raw(RawType),
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
391#[serde(deny_unknown_fields)]
392pub struct RawType {
393    pub raw: String,
394    #[serde(default)]
395    pub media_param: Option<String>,
396}
397
398/// A templated resource's `cardinality` as written (core §2.2): a number,
399/// the most members one instance will hold, or `"unbounded"`, the name of
400/// the no-ceiling value (draft 2, core 0.57, #937). Both resolve to one
401/// integer, so `"unbounded"` and 4294967295 have one canonical form and
402/// one fingerprint (`spec/conformance/contracts/ok-cardinality-unbounded`).
403/// Any other string, a negative integer or a float is not the format's
404/// shape (E000); zero reads, and is E013's.
405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub enum Cardinality {
407    /// An integer, as written.
408    Count(u64),
409    /// `"unbounded"`: [`crate::budget::NO_CEILING`], 2^32−1.
410    Unbounded,
411}
412
413impl Cardinality {
414    /// The spelling of [`Cardinality::Unbounded`].
415    pub const UNBOUNDED: &'static str = "unbounded";
416
417    /// The integer the contract carries: `"unbounded"` is 4294967295.
418    #[must_use]
419    pub fn value(self) -> u64 {
420        match self {
421            Self::Count(n) => n,
422            Self::Unbounded => crate::budget::NO_CEILING,
423        }
424    }
425}
426
427impl Serialize for Cardinality {
428    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
429        match self {
430            Self::Count(n) => s.serialize_u64(*n),
431            Self::Unbounded => s.serialize_str(Self::UNBOUNDED),
432        }
433    }
434}
435
436impl<'de> Deserialize<'de> for Cardinality {
437    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
438        struct V;
439        impl serde::de::Visitor<'_> for V {
440            type Value = Cardinality;
441            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442                f.write_str("a number, the most members one instance will hold, or \"unbounded\"")
443            }
444            fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Cardinality, E> {
445                Ok(Cardinality::Count(n))
446            }
447            fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Cardinality, E> {
448                u64::try_from(n)
449                    .map(Cardinality::Count)
450                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(n), &self))
451            }
452            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Cardinality, E> {
453                if s == Cardinality::UNBOUNDED {
454                    Ok(Cardinality::Unbounded)
455                } else {
456                    Err(E::invalid_value(serde::de::Unexpected::Str(s), &self))
457                }
458            }
459        }
460        d.deserialize_any(V)
461    }
462}
463
464impl JsonSchema for Cardinality {
465    fn schema_name() -> std::borrow::Cow<'static, str> {
466        "Cardinality".into()
467    }
468
469    /// `"unbounded"` as a one-member `enum`, the keyword the schema's other
470    /// strings use, not `const`, which it uses nowhere.
471    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
472        schemars::json_schema!({
473            "description": "A templated resource's `cardinality`: a number, the most members \
474                            one instance will hold, or `\"unbounded\"`, which is 4294967295 \
475                            (core §2.2).",
476            "anyOf": [
477                {"type": "integer", "format": "uint64", "minimum": 0},
478                {"type": "string", "enum": ["unbounded"]}
479            ]
480        })
481    }
482}
483
484/// `gate = "capability:rssi"` or a list of them (AND).
485#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
486#[serde(untagged)]
487pub enum Gate {
488    One(String),
489    All(Vec<String>),
490}
491
492impl Gate {
493    #[must_use]
494    pub fn items(&self) -> Vec<&str> {
495        match self {
496            Self::One(s) => vec![s.as_str()],
497            Self::All(v) => v.iter().map(String::as_str).collect(),
498        }
499    }
500}
501
502/// `history = true` or `{ depth = <n>, miss_detection_ms = <ms> }`.
503#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
504#[serde(untagged)]
505pub enum History {
506    Flag(bool),
507    Params(HistoryParams),
508}
509
510#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
511#[serde(deny_unknown_fields)]
512pub struct HistoryParams {
513    #[schemars(range(max = 4_294_967_295_u32))]
514    pub depth: u32,
515    #[serde(default)]
516    pub miss_detection_ms: Option<u64>,
517}
518
519/// `frame = { records, step_ms, jitter_ms, keyframe_every, deadband }`
520/// (core §7.7, draft 4), as written: its bounds are E048's, never the
521/// schema's, so a value out of range is a lint and not a load failure.
522#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
523#[serde(deny_unknown_fields)]
524pub struct FrameSpec {
525    /// The most records one frame holds, 1 to 256; 1 when absent.
526    #[serde(default)]
527    pub records: Option<u64>,
528    /// Record i is scheduled `step_ms` × i after record 0: 1 to 2^32 − 1,
529    /// given exactly when `records` is above 1.
530    #[serde(default)]
531    pub step_ms: Option<u64>,
532    /// How far a scheduled record may lie from its instant: 0 to
533    /// `step_ms` / 2, only with `step_ms`; 0 when absent.
534    #[serde(default)]
535    pub jitter_ms: Option<u64>,
536    /// A full record at least once every this many records, 1 to 65,536;
537    /// 1 when absent.
538    #[serde(default)]
539    pub keyframe_every: Option<u64>,
540    /// A field's name → its deadband.
541    #[serde(default)]
542    pub deadband: BTreeMap<String, DeadbandSpec>,
543}
544
545/// A deadband (core §7.7): the field omitted while within `delta` of the
546/// value last included, and included at least every `max_records`.
547#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
548#[serde(deny_unknown_fields)]
549pub struct DeadbandSpec {
550    /// A decimal string above 0, in the field's units (§7.6's grammar).
551    pub delta: String,
552    /// 1 to 65,536.
553    pub max_records: u64,
554}
555
556#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
557#[serde(deny_unknown_fields)]
558pub struct Deprecated {
559    #[schemars(range(max = 4_294_967_295_u32))]
560    pub since: u32,
561    #[serde(default)]
562    pub replaced_by: Option<String>,
563    #[serde(default)]
564    pub reason: Option<String>,
565}