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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! The descriptor record (spec `core.md` §3.3, r4 §3.10).
//!
//! An instance answers a GET on its instance key with this JSON document,
//! and puts it on every change. Exposure is *compact* (r3.3 D8): an
//! interface's exposed resources are its contract's, minus the optional ones
//! gated on a capability the instance does not hold, minus the listed
//! `unavailable` exceptions.
//!
//! `spec/descriptor.schema.json` is generated from these types (schemars),
//! and [`check`] reports findings with stable `D…` codes, which
//! `spec/conformance/descriptors/` pins.

use std::collections::{BTreeMap, BTreeSet};
use std::str::FromStr;

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

use crate::canonical::Fingerprint;
use crate::catalog::CatalogId;
use crate::chunk::{is_ident, is_lower_hex, is_plain_chunk};
use crate::contract::Contract;
use crate::diag::{Diagnostic, Report};
use crate::grammar::{IfaceId, KindToken};
use crate::wire::Run;

/// The format tag of this version of the record.
pub const FORMAT: &str = "zk2-descriptor/0.1";

/// One instance's descriptor.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Descriptor {
    /// `zk2-descriptor/0.1`.
    pub format: String,
    /// `<system>/<service>`.
    pub service: String,
    /// The instance id: 16 lowercase hex digits.
    pub instance: String,
    /// The run the instance writes under now (core §3.3, §4.3), as its bytes
    /// in lowercase hexadecimal: 4 digits for a 16-bit run, 8 for a 32-bit
    /// one. An owner states it; a checker reads it as optional, so a
    /// descriptor that states none is not D000, and any other spelling is
    /// D002. Never `null`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "some_string"
    )]
    #[schemars(with = "String")]
    pub run: Option<String>,
    /// The id of the deployment catalog the instance writes under (core
    /// §3.3, §8.6), as 8 lowercase hex digits. An owner given a catalog
    /// states it, and one with none leaves it out; a checker reads it as
    /// optional, and any other spelling is D002. Never `null`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "some_string"
    )]
    #[schemars(with = "String")]
    pub catalog: Option<String>,
    /// The interfaces this instance implements.
    pub interfaces: Vec<InterfaceEntry>,
    /// The capabilities this instance holds, naming the `capability:` gates
    /// of its contracts.
    #[serde(default)]
    pub capabilities: Vec<String>,
    /// Every requirement, with its bindings as declared (R3).
    #[serde(default)]
    pub requires: Vec<RequireEntry>,
    /// The profiles this instance follows, as `<name>.v<major>`.
    #[serde(default)]
    pub profiles: Vec<String>,
    /// Host, process, build: informative, never interpreted. `zid` is the
    /// owner's session zid, which an owner SHOULD state: a tool attributes
    /// a state stamp to the owner by it (§3.3, 0.10; S1).
    #[serde(default)]
    pub meta: BTreeMap<String, Value>,
}

/// One implemented interface.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct InterfaceEntry {
    /// `<name>.v<major>`.
    pub iface: String,
    /// The contract's fingerprint, `sha256:` + 64 lowercase hex digits.
    pub contract: String,
    /// The contract's informative minor.
    pub minor: u64,
    /// Whether the instance stands by on this interface (§3.3, §6, 0.39):
    /// it lists it, and serves none of it now. Written only when `true`;
    /// absent is serving.
    #[serde(default, skip_serializing_if = "is_false")]
    pub standby: bool,
    /// Whether the instance holds this interface's token. `false` for an
    /// interface in the deployment's tokenless set (U22, spec §8.1).
    #[serde(default = "yes")]
    pub token: bool,
    /// Optional resources that are absent here although no missing
    /// capability implies it.
    #[serde(default)]
    pub unavailable: Vec<Unavailable>,
    /// A lower population bound for this instance, per templated resource,
    /// keyed `<kind token>/<template>`.
    #[serde(default)]
    pub cardinality: BTreeMap<String, u64>,
}

/// An optional resource this instance does not expose.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Unavailable {
    /// `<kind token>/<template>`, as in `state/covariance` or `@op/arm`.
    pub resource: String,
    pub cause: Cause,
    /// For a human; never parsed.
    #[serde(default)]
    pub reason: Option<String>,
}

/// Why a resource is absent here (r3.3 D4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Cause {
    Build,
    Config,
    Capability,
}

/// One requirement and its bindings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RequireEntry {
    /// The role's name, `[a-z][a-z0-9_]*`.
    pub role: String,
    /// The required interface, `<name>.v<major>`.
    pub interface: String,
    /// The interface whose contract declares the role, or `null` when the
    /// component's own manifest does.
    #[serde(default)]
    pub declared_by: Option<String>,
    /// Service addresses, `<system>/<service>`; either chunk may be `*`.
    pub bindings: Vec<String>,
    /// Template parameters bound by the binding (R2): parameter name →
    /// `self.system`, `self.service`, or a value.
    #[serde(default)]
    pub params: BTreeMap<String, String>,
    /// Whether the role is optional: the instance works without a provider
    /// (§3.2, 0.10). Written only when `true`; absent is required. A role a
    /// contract declares is optional as that contract says; one the
    /// component's manifest declares, as the manifest says.
    #[serde(default, skip_serializing_if = "is_false")]
    pub optional: bool,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
    !*b
}

/// An optional member present as a string: `null` is not its shape (D000).
fn some_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
    String::deserialize(d).map(Some)
}

/// Parses and checks a descriptor. `contracts` are the contracts it is
/// checked against, by fingerprint; an interface whose contract is not
/// supplied is checked for syntax only.
#[must_use]
pub fn check(text: &str, contracts: &[&Contract]) -> (Option<Descriptor>, Report) {
    let mut report = Report::default();
    let value = match crate::strict::parse_json(text) {
        Ok(v) => v,
        Err(e) => {
            report.push(Diagnostic::error(
                "D000",
                "descriptor",
                format!("not strict JSON: {e}"),
            ));
            return (None, report);
        }
    };
    let d: Descriptor = match serde_json::from_value(value) {
        Ok(d) => d,
        Err(e) => {
            report.push(Diagnostic::error(
                "D000",
                "descriptor",
                format!("shape: {e}"),
            ));
            return (None, report);
        }
    };
    if d.format != FORMAT {
        report.push(Diagnostic::error(
            "D001",
            "format",
            format!("{:?} is not {FORMAT:?}", d.format),
        ));
    }
    let service_ok = d
        .service
        .split_once('/')
        .is_some_and(|(sys, svc)| is_plain_chunk(sys) && is_plain_chunk(svc));
    if !service_ok {
        report.push(Diagnostic::error(
            "D002",
            "service",
            format!("{:?} is not <system>/<service> (plain chunks)", d.service),
        ));
    }
    if !is_lower_hex(&d.instance, 16) {
        report.push(Diagnostic::error(
            "D002",
            "instance",
            format!("{:?} is not 16 lowercase hex digits", d.instance),
        ));
    }
    if let Some(run) = d.run.as_deref()
        && Run::from_hex(run).is_none()
    {
        report.push(Diagnostic::error(
            "D002",
            "run",
            format!("{run:?} is not 4 or 8 lowercase hex digits"),
        ));
    }
    if let Some(catalog) = d.catalog.as_deref()
        && CatalogId::from_hex(catalog).is_none()
    {
        report.push(Diagnostic::error(
            "D002",
            "catalog",
            format!("{catalog:?} is not 8 lowercase hex digits"),
        ));
    }
    for (i, c) in d.capabilities.iter().enumerate() {
        if !is_name(c) {
            report.push(Diagnostic::error(
                "D008",
                format!("capabilities[{i}]"),
                format!("{c:?} is not [a-z0-9][a-z0-9_.-]*"),
            ));
        }
    }
    if d.capabilities.iter().collect::<BTreeSet<_>>().len() != d.capabilities.len() {
        report.push(Diagnostic::error(
            "D008",
            "capabilities",
            "a capability is listed twice",
        ));
    }
    let held: BTreeSet<&str> = d.capabilities.iter().map(String::as_str).collect();
    let mut seen = BTreeSet::new();
    let mut ifaces = BTreeSet::new();
    for (i, e) in d.interfaces.iter().enumerate() {
        let at = format!("interfaces[{i}]");
        if IfaceId::from_str(&e.iface).is_err() {
            report.push(Diagnostic::error(
                "D003",
                &at,
                format!("{:?} is not <name>.v<major>", e.iface),
            ));
            continue;
        }
        if !seen.insert(e.iface.clone()) {
            report.push(Diagnostic::error(
                "D003",
                &at,
                format!("{} is listed twice", e.iface),
            ));
        }
        ifaces.insert(e.iface.clone());
        // §4.4 (0.17): an archive is never tokenless. D011 reads `iface` and
        // `token` only, so a malformed `contract` below does not suppress it
        // (cascade 6, 0.18).
        if e.iface == "archive.v1" && !e.token {
            report.push(Diagnostic::error(
                "D011",
                &at,
                "archive.v1 is marked \"token\": false: an archive is never tokenless (§4.4)",
            ));
        }
        // §3.3, §6 (0.39): an interface with a standby is never tokenless.
        // D012 reads `standby` and `token` only, as D011 reads `iface` and
        // `token` (cascade 7).
        if e.standby && !e.token {
            report.push(Diagnostic::error(
                "D012",
                &at,
                format!(
                    "{} is marked \"standby\": true and \"token\": false: an interface with a \
                     standby is never tokenless (§6, §8.1)",
                    e.iface
                ),
            ));
        }
        let fp_ok = e
            .contract
            .strip_prefix("sha256:")
            .is_some_and(|h| is_lower_hex(h, 64));
        if !fp_ok {
            report.push(Diagnostic::error(
                "D003",
                &at,
                format!(
                    "contract {:?} is not sha256: + 64 lowercase hex digits",
                    e.contract
                ),
            ));
            continue;
        }
        let same_iface: Vec<&&Contract> = contracts
            .iter()
            .filter(|c| c.iface.to_string() == e.iface)
            .collect();
        let Some(c) = same_iface
            .iter()
            .find(|c| Fingerprint::of(c).to_string() == e.contract)
        else {
            if !same_iface.is_empty() {
                report.push(Diagnostic::error(
                    "D004",
                    &at,
                    format!(
                        "{} names a contract revision that was not supplied",
                        e.iface
                    ),
                ));
            }
            continue;
        };
        check_exposure(e, c, &held, &at, &mut report);
    }
    for (i, r) in d.requires.iter().enumerate() {
        let at = format!("requires[{i}]");
        let mut bad = Vec::new();
        if !is_ident(&r.role) {
            bad.push(format!("role {:?} is not [a-z][a-z0-9_]*", r.role));
        }
        if IfaceId::from_str(&r.interface).is_err() {
            bad.push(format!(
                "interface {:?} is not <name>.v<major>",
                r.interface
            ));
        }
        if let Some(by) = &r.declared_by
            && !ifaces.contains(by)
        {
            bad.push(format!(
                "declared_by {by:?} is not one of this instance's interfaces"
            ));
        }
        for (k, v) in &r.params {
            if !is_ident(k) || v.is_empty() {
                bad.push(format!(
                    "parameter binding {k:?} = {v:?} is not <name> = a non-empty value"
                ));
            }
        }
        for b in &r.bindings {
            let ok = b.split_once('/').is_some_and(|(sys, svc)| {
                (sys == "*" || is_plain_chunk(sys)) && (svc == "*" || is_plain_chunk(svc))
            });
            if !ok {
                bad.push(format!(
                    "binding {b:?} is not <system>/<service> (a chunk may be *)"
                ));
            }
        }
        for m in bad {
            report.push(Diagnostic::error("D009", &at, m));
        }
    }
    for (i, p) in d.profiles.iter().enumerate() {
        if IfaceId::from_str(p).is_err() {
            report.push(Diagnostic::error(
                "D010",
                format!("profiles[{i}]"),
                format!("{p:?} is not <name>.v<major>"),
            ));
        }
    }
    // Like a capability (D008) and an interface (D003), a profile is listed
    // once.
    if d.profiles.iter().collect::<BTreeSet<_>>().len() != d.profiles.len() {
        report.push(Diagnostic::error(
            "D010",
            "profiles",
            "a profile is listed twice",
        ));
    }
    (Some(d), report)
}

/// The exposure rules of one interface against its contract.
fn check_exposure(
    e: &InterfaceEntry,
    c: &Contract,
    held: &BTreeSet<&str>,
    at: &str,
    report: &mut Report,
) {
    for u in &e.unavailable {
        let Some(r) = resource(c, &u.resource) else {
            report.push(Diagnostic::error(
                "D005",
                at,
                format!(
                    "unavailable {:?} is not a resource of {}",
                    u.resource, c.iface
                ),
            ));
            continue;
        };
        if !r.optional {
            report.push(Diagnostic::error(
                "D005",
                at,
                format!("unavailable {:?} is a required resource", u.resource),
            ));
            continue;
        }
        let implied = r.gate.iter().any(|g| {
            g.strip_prefix("capability:")
                .is_some_and(|cap| !held.contains(cap))
        });
        if implied {
            report.push(Diagnostic::warning(
                "D006",
                at,
                format!(
                    "unavailable {:?} is already implied by a capability not held",
                    u.resource
                ),
            ));
        }
    }
    for (name, n) in &e.cardinality {
        let ceiling = resource(c, name).and_then(|r| r.cardinality);
        match ceiling {
            None => report.push(Diagnostic::error(
                "D007",
                at,
                format!(
                    "cardinality {name:?} names no templated resource of {}",
                    c.iface
                ),
            )),
            Some(max) if *n == 0 || *n > max => report.push(Diagnostic::error(
                "D007",
                at,
                format!("cardinality {name:?} = {n} is not within 1..={max}"),
            )),
            Some(_) => {}
        }
    }
}

impl Descriptor {
    /// The run the descriptor states (core §3.3), `None` when it states
    /// none or spells it otherwise than 4 or 8 lowercase hex digits (D002).
    #[must_use]
    pub fn stated_run(&self) -> Option<Run> {
        self.run.as_deref().and_then(Run::from_hex)
    }

    /// The catalog the descriptor names (core §3.3, §8.6), `None` when it
    /// names none or spells it otherwise than 8 lowercase hex digits (D002).
    #[must_use]
    pub fn stated_catalog(&self) -> Option<CatalogId> {
        self.catalog.as_deref().and_then(CatalogId::from_hex)
    }

    /// The resources of `contract` this instance exposes (§3.3): the
    /// contract's, minus the optional ones gated on a capability it does not
    /// hold, minus those its entry lists `unavailable`; none at all when the
    /// entry marks the interface `"standby": true` (§3.3, §6, 0.39), whose
    /// `unavailable` says what it will expose once it serves. `None` when it
    /// lists no entry for the contract's interface.
    ///
    /// What a tool decides a split-brain from, beside replicated serving
    /// (§6, 0.7, #660). The entry's revision is the caller's to match: this
    /// reads `contract` as given.
    #[must_use]
    pub fn exposed<'c>(
        &self,
        contract: &'c Contract,
    ) -> Option<Vec<&'c crate::contract::Resource>> {
        let iface = contract.iface.to_string();
        let entry = self.interfaces.iter().find(|e| e.iface == iface)?;
        if entry.standby {
            return Some(Vec::new());
        }
        let held = |cap: &str| self.capabilities.iter().any(|h| h == cap);
        Some(
            contract
                .resources
                .iter()
                .filter(|r| {
                    let name = format!("{}/{}", r.token, r.template);
                    let gated_off = r
                        .gate
                        .iter()
                        .any(|g| g.strip_prefix("capability:").is_some_and(|cap| !held(cap)));
                    let listed = entry.unavailable.iter().any(|u| u.resource == name);
                    !(r.optional && (gated_off || listed))
                })
                .collect(),
        )
    }
}

fn yes() -> bool {
    true
}

/// A resource named `<kind token>/<template>`.
fn resource<'c>(c: &'c Contract, name: &str) -> Option<&'c crate::contract::Resource> {
    let (token, template) = name.split_once('/')?;
    let token = KindToken::from_str(token).ok()?;
    c.resource(token, template)
}

/// A capability name: `[a-z0-9][a-z0-9_.-]*`, as in a `capability:` gate.
fn is_name(s: &str) -> bool {
    let mut cs = s.chars();
    cs.next()
        .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
        && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "_.-".contains(c))
}

#[cfg(test)]
mod tests {
    use super::Descriptor;

    /// §3.3's compact exposure: a missing capability implies an optional
    /// resource absent, as a listed one is; a required resource is always
    /// exposed.
    #[test]
    fn exposure_is_the_contract_minus_the_gated_off_and_the_listed() {
        let op = |name: &str, extra: &str| {
            format!(
                "[resources.{name}]\nkind = \"operation\"\n{extra}\
                 request = {{ raw = \"text/plain\" }}\nresponse = {{ raw = \"text/plain\" }}\n"
            )
        };
        let toml = format!(
            "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n{}{}{}",
            op("a", ""),
            op("b", "optional = true\n"),
            op("c", "optional = true\ngate = [\"capability:x\"]\n"),
        );
        let l = crate::contract::load_str(&toml, std::path::Path::new("."), None);
        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
        let d = |caps: &str, unavailable: &str| -> Descriptor {
            serde_json::from_str(&format!(
                r#"{{"format": "zk2-descriptor/0.1", "service": "s/t", "instance": "000000000000000a",
                    "interfaces": [{{"iface": "t.v1", "contract": "sha256:{}", "minor": 0,
                                     "unavailable": [{unavailable}]}}],
                    "capabilities": [{caps}]}}"#,
                "0".repeat(64)
            ))
            .unwrap()
        };
        let names = |d: &Descriptor| -> Vec<String> {
            d.exposed(&c)
                .unwrap()
                .iter()
                .map(|r| r.template.as_str().to_owned())
                .collect()
        };
        assert_eq!(names(&d("", "")), ["a", "b"]);
        assert_eq!(names(&d("\"x\"", "")), ["a", "b", "c"]);
        assert_eq!(
            names(&d("\"x\"", r#"{"resource": "@op/b", "cause": "config"}"#)),
            ["a", "c"]
        );
        // A standby exposes nothing, whatever else its entry says (0.39).
        let mut standby = d("\"x\"", "");
        standby.interfaces[0].standby = true;
        assert!(names(&standby).is_empty());
        let mut other = d("", "");
        other.interfaces[0].iface = "u.v1".into();
        assert!(other.exposed(&c).is_none());
    }
}