zenkey-model 0.22.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! The authoring format, draft 4 (`examples/zk2/README.md`, r3.3): the
//! TOML shape a contract file has, before any validation or defaulting.
//! Draft 2 is draft 1 plus one spelling, `cardinality = "unbounded"`
//! ([`Cardinality`], core 0.57, #937). Draft 3 adds `[schemas] packed`
//! and the `packed:` references (core 0.75, §7.6, #979). Draft 4 adds a
//! resource's `frame` table ([`FrameSpec`], core 0.83, §7.7, #981). None
//! changed the canonical form of a contract that does not use what it
//! adds, so its `format` tag is still `zk2-contract/draft-1`.
//!
//! `spec/contract.schema.json` is generated from these types (schemars) and
//! committed. A test fails when the two drift.

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// The member under which a float that is not finite (`nan`, `inf`) is
/// carried through an annotation value. JSON has no such number, and
/// `serde_json` would turn it into `null` without a word; carried this way,
/// the canonical-form restriction refuses it (E028, spec §9.5).
pub const NON_FINITE: &str = "$__zk2_private_non_finite";

/// The member under which the `toml` crate hands a datetime to serde. An
/// annotation value holding one is E020 (spec §9.1).
pub const DATETIME: &str = "$__toml_private_datetime";

/// Annotation values are read as TOML values, then turned into JSON: a
/// datetime and a float that is not finite are kept as marker objects
/// ([`DATETIME`], [`NON_FINITE`]) for the lints to refuse.
fn annotations<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<BTreeMap<String, Value>, D::Error> {
    let raw = BTreeMap::<String, toml::Value>::deserialize(d)?;
    Ok(raw.into_iter().map(|(k, v)| (k, from_toml(v))).collect())
}

fn from_toml(v: toml::Value) -> Value {
    match v {
        toml::Value::String(s) => Value::String(s),
        toml::Value::Integer(i) => Value::from(i),
        toml::Value::Float(f) => serde_json::Number::from_f64(f).map_or_else(
            || {
                Value::Object(
                    [(NON_FINITE.to_owned(), Value::String(f.to_string()))]
                        .into_iter()
                        .collect(),
                )
            },
            Value::Number,
        ),
        toml::Value::Boolean(b) => Value::Bool(b),
        toml::Value::Datetime(dt) => Value::Object(
            [(DATETIME.to_owned(), Value::String(dt.to_string()))]
                .into_iter()
                .collect(),
        ),
        toml::Value::Array(a) => Value::Array(a.into_iter().map(from_toml).collect()),
        toml::Value::Table(t) => {
            Value::Object(t.into_iter().map(|(k, v)| (k, from_toml(v))).collect())
        }
    }
}

/// One contract file: one interface major.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ContractFile {
    pub interface: InterfaceSection,
    #[serde(default)]
    pub defaults: Option<DefaultsSection>,
    #[serde(default)]
    pub schemas: SchemasSection,
    #[serde(default)]
    pub resources: BTreeMap<String, ResourceSpec>,
    #[serde(default)]
    pub requires: BTreeMap<String, Requirement>,
}

/// `[interface]`.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct InterfaceSection {
    /// `[a-z][a-z0-9_]*` segments joined by `.`; never ending in `.v<int>`.
    pub name: String,
    #[schemars(range(max = 4_294_967_295_u32))]
    pub major: u32,
    /// Informative; CI keeps it monotonic; not in the fingerprint.
    #[serde(default)]
    #[schemars(range(max = 4_294_967_295_u32))]
    pub minor: Option<u32>,
    /// Documentation; not in the fingerprint.
    #[serde(default)]
    pub summary: Option<String>,
    /// Profiles whose annotations the contract uses (`freshness.v1`, …).
    #[serde(default)]
    pub uses: Vec<String>,
}

/// `[schemas]`.
#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SchemasSection {
    /// `.proto` files, relative to the contract's directory. proto2/proto3.
    #[serde(default)]
    pub protobuf: Vec<String>,
    /// Include roots for protobuf imports, relative to the contract's
    /// directory. Default: `["proto"]` when that directory exists, else `["."]`.
    #[serde(default)]
    pub proto_include: Option<Vec<String>>,
    /// JSON Schema 2020-12 files (the zk2 subset), definitions under `$defs`.
    #[serde(default)]
    pub jsonschema: Vec<String>,
    /// Packed files (core §7.6, draft 3): strict JSON, types under `types`,
    /// referenced as `packed:<Name>` or `packed:<stem>#<Name>`.
    #[serde(default)]
    pub packed: Vec<String>,
}

/// The fields `[defaults]` may set (r3.3 D2).
#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DefaultsBlock {
    #[serde(default, deserialize_with = "annotations")]
    pub annotations: BTreeMap<String, Value>,
    pub encoding: Option<Encoding>,
    pub attachment_encoding: Option<Encoding>,
    pub reliability: Option<Reliability>,
    pub congestion: Option<Congestion>,
    pub priority: Option<Priority>,
    pub express: Option<bool>,
    pub history: Option<History>,
    pub idempotent: Option<bool>,
    pub fanout: Option<Fanout>,
    pub serving: Option<Serving>,
    pub replies: Option<Replies>,
    pub timeout_ms: Option<u64>,
}

/// `[defaults]` and `[defaults.<kind>]`.
#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DefaultsSection {
    #[serde(default, deserialize_with = "annotations")]
    pub annotations: BTreeMap<String, Value>,
    pub encoding: Option<Encoding>,
    pub attachment_encoding: Option<Encoding>,
    pub reliability: Option<Reliability>,
    pub congestion: Option<Congestion>,
    pub priority: Option<Priority>,
    pub express: Option<bool>,
    pub history: Option<History>,
    pub idempotent: Option<bool>,
    pub fanout: Option<Fanout>,
    pub serving: Option<Serving>,
    pub replies: Option<Replies>,
    pub timeout_ms: Option<u64>,
    pub stream: Option<DefaultsBlock>,
    pub state: Option<DefaultsBlock>,
    pub event: Option<DefaultsBlock>,
    pub operation: Option<DefaultsBlock>,
}

impl DefaultsSection {
    /// The base block (the fields set directly under `[defaults]`).
    #[must_use]
    pub fn base(&self) -> DefaultsBlock {
        DefaultsBlock {
            annotations: self.annotations.clone(),
            encoding: self.encoding,
            attachment_encoding: self.attachment_encoding,
            reliability: self.reliability,
            congestion: self.congestion,
            priority: self.priority,
            express: self.express,
            history: self.history.clone(),
            idempotent: self.idempotent,
            fanout: self.fanout,
            serving: self.serving,
            replies: self.replies,
            timeout_ms: self.timeout_ms,
        }
    }
    #[must_use]
    pub fn for_kind(&self, kind: Kind) -> Option<&DefaultsBlock> {
        match kind {
            Kind::Stream => self.stream.as_ref(),
            Kind::State => self.state.as_ref(),
            Kind::Event => self.event.as_ref(),
            Kind::Operation => self.operation.as_ref(),
        }
    }
}

/// `[resources."<template>"]`: every field any kind may carry. Which ones
/// a kind accepts is checked by the lints (E014).
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResourceSpec {
    pub kind: Kind,
    #[serde(default)]
    pub doc: Option<String>,
    #[serde(default)]
    pub params: BTreeMap<String, ParamType>,
    #[serde(default)]
    pub cardinality: Option<Cardinality>,
    #[serde(default)]
    pub epoch: Option<String>,
    #[serde(default)]
    pub optional: bool,
    #[serde(default)]
    pub gate: Option<Gate>,
    #[serde(default)]
    pub deprecated: Option<Deprecated>,
    #[serde(default, deserialize_with = "annotations")]
    pub annotations: BTreeMap<String, Value>,
    // stream, state, event
    #[serde(default, rename = "type")]
    pub type_: Option<TypeRef>,
    #[serde(default)]
    pub attachment: Option<TypeRef>,
    #[serde(default)]
    pub encoding: Option<Encoding>,
    #[serde(default)]
    pub attachment_encoding: Option<Encoding>,
    #[serde(default)]
    pub explicit: Option<bool>,
    #[serde(default)]
    pub reliability: Option<Reliability>,
    #[serde(default)]
    pub congestion: Option<Congestion>,
    #[serde(default)]
    pub priority: Option<Priority>,
    #[serde(default)]
    pub express: Option<bool>,
    #[serde(default)]
    pub history: Option<History>,
    /// A frame resource's `frame` table (core §7.7, draft 4): a plain
    /// stream's alone, never defaulted.
    #[serde(default)]
    pub frame: Option<FrameSpec>,
    #[serde(default)]
    pub rate: Option<String>,
    #[serde(default)]
    pub retention: Option<String>,
    // operation
    #[serde(default)]
    pub request: Option<TypeRef>,
    #[serde(default)]
    pub response: Option<TypeRef>,
    #[serde(default)]
    pub error: Option<TypeRef>,
    #[serde(default)]
    pub idempotent: Option<bool>,
    #[serde(default)]
    pub fanout: Option<Fanout>,
    #[serde(default)]
    pub serving: Option<Serving>,
    #[serde(default)]
    pub replies: Option<Replies>,
    #[serde(default)]
    pub summary: Option<TypeRef>,
    #[serde(default)]
    pub timeout_ms: Option<u64>,
}

/// `[requires.<role>]`.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Requirement {
    /// The required interface, `<name>.v<major>`.
    pub interface: String,
    /// What is consumed; default: everything.
    #[serde(default)]
    pub resources: Option<Vec<String>>,
    #[serde(default)]
    pub cardinality: Option<RequireCardinality>,
    #[serde(default)]
    pub optional: bool,
    #[serde(default)]
    pub doc: Option<String>,
    #[serde(default, deserialize_with = "annotations")]
    pub annotations: BTreeMap<String, Value>,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, JsonSchema,
)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    Stream,
    State,
    Event,
    Operation,
}

impl Kind {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Stream => "stream",
            Self::State => "state",
            Self::Event => "event",
            Self::Operation => "operation",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ParamType {
    String,
    Uint,
    Path,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Encoding {
    Json,
    Cbor,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Reliability {
    BestEffort,
    Reliable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Congestion {
    Drop,
    Block,
}

/// Zenoh's seven priorities, by name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Priority {
    RealTime,
    InteractiveHigh,
    InteractiveLow,
    DataHigh,
    Data,
    DataLow,
    Background,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Fanout {
    Forbidden,
    Allowed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Serving {
    Exclusive,
    Replicated,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Replies {
    One,
    Many,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum RequireCardinality {
    One,
    Many,
}

/// A type reference: `"pkg.Message"`, `"json:Name"`, `"json:stem#Name"`,
/// `"packed:Name"`, `"packed:stem#Name"`, or
/// `{ raw = "<media type>", media_param = "<param>" }`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum TypeRef {
    Named(String),
    Raw(RawType),
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RawType {
    pub raw: String,
    #[serde(default)]
    pub media_param: Option<String>,
}

/// A templated resource's `cardinality` as written (core §2.2): a number,
/// the most members one instance will hold, or `"unbounded"`, the name of
/// the no-ceiling value (draft 2, core 0.57, #937). Both resolve to one
/// integer, so `"unbounded"` and 4294967295 have one canonical form and
/// one fingerprint (`spec/conformance/contracts/ok-cardinality-unbounded`).
/// Any other string, a negative integer or a float is not the format's
/// shape (E000); zero reads, and is E013's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cardinality {
    /// An integer, as written.
    Count(u64),
    /// `"unbounded"`: [`crate::budget::NO_CEILING`], 2^32−1.
    Unbounded,
}

impl Cardinality {
    /// The spelling of [`Cardinality::Unbounded`].
    pub const UNBOUNDED: &'static str = "unbounded";

    /// The integer the contract carries: `"unbounded"` is 4294967295.
    #[must_use]
    pub fn value(self) -> u64 {
        match self {
            Self::Count(n) => n,
            Self::Unbounded => crate::budget::NO_CEILING,
        }
    }
}

impl Serialize for Cardinality {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Count(n) => s.serialize_u64(*n),
            Self::Unbounded => s.serialize_str(Self::UNBOUNDED),
        }
    }
}

impl<'de> Deserialize<'de> for Cardinality {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl serde::de::Visitor<'_> for V {
            type Value = Cardinality;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a number, the most members one instance will hold, or \"unbounded\"")
            }
            fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Cardinality, E> {
                Ok(Cardinality::Count(n))
            }
            fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Cardinality, E> {
                u64::try_from(n)
                    .map(Cardinality::Count)
                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(n), &self))
            }
            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Cardinality, E> {
                if s == Cardinality::UNBOUNDED {
                    Ok(Cardinality::Unbounded)
                } else {
                    Err(E::invalid_value(serde::de::Unexpected::Str(s), &self))
                }
            }
        }
        d.deserialize_any(V)
    }
}

impl JsonSchema for Cardinality {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Cardinality".into()
    }

    /// `"unbounded"` as a one-member `enum`, the keyword the schema's other
    /// strings use, not `const`, which it uses nowhere.
    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "description": "A templated resource's `cardinality`: a number, the most members \
                            one instance will hold, or `\"unbounded\"`, which is 4294967295 \
                            (core §2.2).",
            "anyOf": [
                {"type": "integer", "format": "uint64", "minimum": 0},
                {"type": "string", "enum": ["unbounded"]}
            ]
        })
    }
}

/// `gate = "capability:rssi"` or a list of them (AND).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum Gate {
    One(String),
    All(Vec<String>),
}

impl Gate {
    #[must_use]
    pub fn items(&self) -> Vec<&str> {
        match self {
            Self::One(s) => vec![s.as_str()],
            Self::All(v) => v.iter().map(String::as_str).collect(),
        }
    }
}

/// `history = true` or `{ depth = <n>, miss_detection_ms = <ms> }`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum History {
    Flag(bool),
    Params(HistoryParams),
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct HistoryParams {
    #[schemars(range(max = 4_294_967_295_u32))]
    pub depth: u32,
    #[serde(default)]
    pub miss_detection_ms: Option<u64>,
}

/// `frame = { records, step_ms, jitter_ms, keyframe_every, deadband }`
/// (core §7.7, draft 4), as written: its bounds are E048's, never the
/// schema's, so a value out of range is a lint and not a load failure.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct FrameSpec {
    /// The most records one frame holds, 1 to 256; 1 when absent.
    #[serde(default)]
    pub records: Option<u64>,
    /// Record i is scheduled `step_ms` × i after record 0: 1 to 2^32 − 1,
    /// given exactly when `records` is above 1.
    #[serde(default)]
    pub step_ms: Option<u64>,
    /// How far a scheduled record may lie from its instant: 0 to
    /// `step_ms` / 2, only with `step_ms`; 0 when absent.
    #[serde(default)]
    pub jitter_ms: Option<u64>,
    /// A full record at least once every this many records, 1 to 65,536;
    /// 1 when absent.
    #[serde(default)]
    pub keyframe_every: Option<u64>,
    /// A field's name → its deadband.
    #[serde(default)]
    pub deadband: BTreeMap<String, DeadbandSpec>,
}

/// A deadband (core §7.7): the field omitted while within `delta` of the
/// value last included, and included at least every `max_records`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DeadbandSpec {
    /// A decimal string above 0, in the field's units (§7.6's grammar).
    pub delta: String,
    /// 1 to 65,536.
    pub max_records: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Deprecated {
    #[schemars(range(max = 4_294_967_295_u32))]
    pub since: u32,
    #[serde(default)]
    pub replaced_by: Option<String>,
    #[serde(default)]
    pub reason: Option<String>,
}