Skip to main content

zenkey_model/
descriptor.rs

1//! The descriptor record (spec `core.md` §3.3, r4 §3.10).
2//!
3//! An instance answers a GET on its instance key with this JSON document,
4//! and puts it on every change. Exposure is *compact* (r3.3 D8): an
5//! interface's exposed resources are its contract's, minus the optional ones
6//! gated on a capability the instance does not hold, minus the listed
7//! `unavailable` exceptions.
8//!
9//! `spec/descriptor.schema.json` is generated from these types (schemars;
10//! a member left out when empty states its `default` through `extend`,
11//! since schemars derives none for a member that skips serializing it),
12//! and [`check`] reports findings with stable `D…` codes, which
13//! `spec/conformance/descriptors/` pins.
14
15use std::collections::{BTreeMap, BTreeSet};
16use std::str::FromStr;
17
18use schemars::JsonSchema;
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21
22use crate::canonical::Fingerprint;
23use crate::catalog::CatalogId;
24use crate::chunk::{is_ident, is_lower_hex, is_plain_chunk};
25use crate::contract::Contract;
26use crate::diag::{Diagnostic, Report};
27use crate::grammar::{IfaceId, KindToken};
28use crate::wire::Run;
29
30pub mod compact;
31
32/// The format tag of this version of the record.
33pub const FORMAT: &str = "zk2-descriptor/0.1";
34
35/// The form a descriptor travels in (core §3.3, "What carries it"), told
36/// by its put's or its reply's `Encoding` alone, never by its bytes.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Form {
39    /// The JSON form, under `application/json`.
40    Json,
41    /// The compact form ([`compact`]), under `zenoh/bytes`.
42    Compact,
43}
44
45impl Form {
46    /// The form `encoding` says, as zenoh writes an `Encoding`:
47    /// `zenoh/bytes` exactly ([`crate::wire::ENCODING`]) is the compact
48    /// form, and any other is read as JSON, where one that does not read is
49    /// D000. So a reader never decides by the bytes.
50    #[must_use]
51    pub fn of(encoding: &str) -> Form {
52        if encoding == crate::wire::ENCODING {
53            Form::Compact
54        } else {
55            Form::Json
56        }
57    }
58}
59
60/// One instance's descriptor.
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
62#[serde(deny_unknown_fields)]
63pub struct Descriptor {
64    /// `zk2-descriptor/0.1`.
65    pub format: String,
66    /// `<system>/<service>`.
67    pub service: String,
68    /// The instance id: 16 lowercase hex digits.
69    pub instance: String,
70    /// The run the instance writes under now (core §3.3, §4.3), as its bytes
71    /// in lowercase hexadecimal: 4 digits for a 16-bit run, 8 for a 32-bit
72    /// one. An owner states it; a checker reads it as optional, so a
73    /// descriptor that states none is not D000, and any other spelling is
74    /// D002. Never `null`.
75    #[serde(
76        default,
77        skip_serializing_if = "Option::is_none",
78        deserialize_with = "some_string"
79    )]
80    #[schemars(with = "String")]
81    pub run: Option<String>,
82    /// The id of the deployment catalog the instance writes under (core
83    /// §3.3, §8.6), as 8 lowercase hex digits. An owner given a catalog
84    /// states it, and one with none leaves it out; a checker reads it as
85    /// optional, and any other spelling is D002. Never `null`.
86    #[serde(
87        default,
88        skip_serializing_if = "Option::is_none",
89        deserialize_with = "some_string"
90    )]
91    #[schemars(with = "String")]
92    pub catalog: Option<String>,
93    /// The interfaces this instance implements.
94    pub interfaces: Vec<InterfaceEntry>,
95    /// The capabilities this instance holds, naming the `capability:` gates
96    /// of its contracts. Written only when one is held: absent is none
97    /// (§3.3).
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    #[schemars(extend("default" = []))]
100    pub capabilities: Vec<String>,
101    /// Every requirement, with its bindings as declared (R3). Written only
102    /// when there is one: absent is none.
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    #[schemars(extend("default" = []))]
105    pub requires: Vec<RequireEntry>,
106    /// The profiles this instance follows, as `<name>.v<major>`. Written
107    /// only when it follows one: absent is none.
108    #[serde(default, skip_serializing_if = "Vec::is_empty")]
109    #[schemars(extend("default" = []))]
110    pub profiles: Vec<String>,
111    /// Host, process, build: informative, never interpreted. `zid` is the
112    /// owner's session zid, which an owner SHOULD state: a tool attributes
113    /// a state stamp to the owner by it (§3.3, 0.10; S1). Written only when
114    /// it holds a member.
115    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
116    #[schemars(extend("default" = {}))]
117    pub meta: BTreeMap<String, Value>,
118}
119
120/// One implemented interface.
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
122#[serde(deny_unknown_fields)]
123pub struct InterfaceEntry {
124    /// `<name>.v<major>`.
125    pub iface: String,
126    /// The contract's fingerprint, `sha256:` + 64 lowercase hex digits.
127    pub contract: String,
128    /// The minor of the contract revision the entry names, as its authoring
129    /// file states it (§3.3). An owner that holds only the revision's bundle,
130    /// which keeps no minor (§9.5), leaves it out, never writing one its
131    /// revision does not have; a checker reads it as optional, and
132    /// `null` is D000.
133    #[serde(
134        default,
135        skip_serializing_if = "Option::is_none",
136        deserialize_with = "some_u64"
137    )]
138    #[schemars(with = "u64")]
139    pub minor: Option<u64>,
140    /// Whether the instance stands by on this interface (§3.3, §6, 0.39):
141    /// it lists it, and serves none of it now. Written only when `true`;
142    /// absent is serving.
143    #[serde(default, skip_serializing_if = "is_false")]
144    pub standby: bool,
145    /// Whether the instance holds this interface's token. `false` for an
146    /// interface in the deployment's tokenless set (U22, spec §8.1).
147    #[serde(default = "yes")]
148    pub token: bool,
149    /// Optional resources that are absent here although no missing
150    /// capability implies it. Written only when one is listed: absent is
151    /// none.
152    #[serde(default, skip_serializing_if = "Vec::is_empty")]
153    #[schemars(extend("default" = []))]
154    pub unavailable: Vec<Unavailable>,
155    /// A lower population bound for this instance, per templated resource,
156    /// keyed `<kind token>/<template>`. Written only when one is stated:
157    /// absent is none.
158    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
159    #[schemars(extend("default" = {}))]
160    pub cardinality: BTreeMap<String, u64>,
161}
162
163/// An optional resource this instance does not expose.
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
165#[serde(deny_unknown_fields)]
166pub struct Unavailable {
167    /// `<kind token>/<template>`, as in `state/covariance` or `@op/arm`.
168    pub resource: String,
169    pub cause: Cause,
170    /// For a human; never parsed.
171    #[serde(default)]
172    pub reason: Option<String>,
173}
174
175/// Why a resource is absent here (r3.3 D4).
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
177#[serde(rename_all = "lowercase")]
178pub enum Cause {
179    Build,
180    Config,
181    Capability,
182}
183
184/// One requirement and its bindings.
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
186#[serde(deny_unknown_fields)]
187pub struct RequireEntry {
188    /// The role's name, `[a-z][a-z0-9_]*`.
189    pub role: String,
190    /// The required interface, `<name>.v<major>`.
191    pub interface: String,
192    /// The interface whose contract declares the role, or `null` when the
193    /// component's own manifest does.
194    #[serde(default)]
195    pub declared_by: Option<String>,
196    /// Service addresses, `<system>/<service>`; either chunk may be `*`.
197    pub bindings: Vec<String>,
198    /// Template parameters bound by the binding (R2): parameter name →
199    /// `self.system`, `self.service`, or a value. Written only when one is
200    /// bound: absent is none.
201    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
202    #[schemars(extend("default" = {}))]
203    pub params: BTreeMap<String, String>,
204    /// Whether the role is optional: the instance works without a provider
205    /// (§3.2, 0.10). Written only when `true`; absent is required. A role a
206    /// contract declares is optional as that contract says; one the
207    /// component's manifest declares, as the manifest says.
208    #[serde(default, skip_serializing_if = "is_false")]
209    pub optional: bool,
210}
211
212#[allow(clippy::trivially_copy_pass_by_ref)]
213fn is_false(b: &bool) -> bool {
214    !*b
215}
216
217/// An optional member present as a string: `null` is not its shape (D000).
218fn some_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
219    String::deserialize(d).map(Some)
220}
221
222/// An optional member present as an integer: `null` is not its shape (D000).
223fn some_u64<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
224    u64::deserialize(d).map(Some)
225}
226
227/// Parses and checks a descriptor. `contracts` are the contracts it is
228/// checked against, by fingerprint; an interface whose contract is not
229/// supplied is checked for syntax only.
230#[must_use]
231pub fn check(text: &str, contracts: &[&Contract]) -> (Option<Descriptor>, Report) {
232    let value = match crate::strict::parse_json(text) {
233        Ok(v) => v,
234        Err(e) => {
235            let mut report = Report::default();
236            report.push(Diagnostic::error(
237                "D000",
238                "descriptor",
239                format!("not strict JSON: {e}"),
240            ));
241            return (None, report);
242        }
243    };
244    let d: Descriptor = match serde_json::from_value(value) {
245        Ok(d) => d,
246        Err(e) => {
247            let mut report = Report::default();
248            report.push(Diagnostic::error(
249                "D000",
250                "descriptor",
251                format!("shape: {e}"),
252            ));
253            return (None, report);
254        }
255    };
256    let report = check_descriptor(&d, contracts);
257    (Some(d), report)
258}
259
260/// Checks a descriptor already read: every code but D000, which is the
261/// reading's. What [`check`] reports once the JSON reads, and what a
262/// checker reports on a compact descriptor's decoding (core §3.3, "The
263/// checks on a decoded descriptor"; [`compact::decode`]).
264#[must_use]
265pub fn check_descriptor(d: &Descriptor, contracts: &[&Contract]) -> Report {
266    let mut report = Report::default();
267    if d.format != FORMAT {
268        report.push(Diagnostic::error(
269            "D001",
270            "format",
271            format!("{:?} is not {FORMAT:?}", d.format),
272        ));
273    }
274    let service_ok = d
275        .service
276        .split_once('/')
277        .is_some_and(|(sys, svc)| is_plain_chunk(sys) && is_plain_chunk(svc));
278    if !service_ok {
279        report.push(Diagnostic::error(
280            "D002",
281            "service",
282            format!("{:?} is not <system>/<service> (plain chunks)", d.service),
283        ));
284    }
285    if !is_lower_hex(&d.instance, 16) {
286        report.push(Diagnostic::error(
287            "D002",
288            "instance",
289            format!("{:?} is not 16 lowercase hex digits", d.instance),
290        ));
291    }
292    if let Some(run) = d.run.as_deref()
293        && Run::from_hex(run).is_none()
294    {
295        report.push(Diagnostic::error(
296            "D002",
297            "run",
298            format!("{run:?} is not 4 or 8 lowercase hex digits"),
299        ));
300    }
301    if let Some(catalog) = d.catalog.as_deref()
302        && CatalogId::from_hex(catalog).is_none()
303    {
304        report.push(Diagnostic::error(
305            "D002",
306            "catalog",
307            format!("{catalog:?} is not 8 lowercase hex digits"),
308        ));
309    }
310    for (i, c) in d.capabilities.iter().enumerate() {
311        if !is_name(c) {
312            report.push(Diagnostic::error(
313                "D008",
314                format!("capabilities[{i}]"),
315                format!("{c:?} is not [a-z0-9][a-z0-9_.-]*"),
316            ));
317        }
318    }
319    if d.capabilities.iter().collect::<BTreeSet<_>>().len() != d.capabilities.len() {
320        report.push(Diagnostic::error(
321            "D008",
322            "capabilities",
323            "a capability is listed twice",
324        ));
325    }
326    let held: BTreeSet<&str> = d.capabilities.iter().map(String::as_str).collect();
327    let mut seen = BTreeSet::new();
328    let mut ifaces = BTreeSet::new();
329    for (i, e) in d.interfaces.iter().enumerate() {
330        let at = format!("interfaces[{i}]");
331        if IfaceId::from_str(&e.iface).is_err() {
332            report.push(Diagnostic::error(
333                "D003",
334                &at,
335                format!("{:?} is not <name>.v<major>", e.iface),
336            ));
337            continue;
338        }
339        if !seen.insert(e.iface.clone()) {
340            report.push(Diagnostic::error(
341                "D003",
342                &at,
343                format!("{} is listed twice", e.iface),
344            ));
345        }
346        ifaces.insert(e.iface.clone());
347        // §4.4 (0.17): an archive is never tokenless. D011 reads `iface` and
348        // `token` only, so a malformed `contract` below does not suppress it
349        // (cascade 6, 0.18).
350        if e.iface == "archive.v1" && !e.token {
351            report.push(Diagnostic::error(
352                "D011",
353                &at,
354                "archive.v1 is marked \"token\": false: an archive is never tokenless (§4.4)",
355            ));
356        }
357        // §3.3, §6 (0.39): an interface with a standby is never tokenless.
358        // D012 reads `standby` and `token` only, as D011 reads `iface` and
359        // `token` (cascade 7).
360        if e.standby && !e.token {
361            report.push(Diagnostic::error(
362                "D012",
363                &at,
364                format!(
365                    "{} is marked \"standby\": true and \"token\": false: an interface with a \
366                     standby is never tokenless (§6, §8.1)",
367                    e.iface
368                ),
369            ));
370        }
371        let fp_ok = e
372            .contract
373            .strip_prefix("sha256:")
374            .is_some_and(|h| is_lower_hex(h, 64));
375        if !fp_ok {
376            report.push(Diagnostic::error(
377                "D003",
378                &at,
379                format!(
380                    "contract {:?} is not sha256: + 64 lowercase hex digits",
381                    e.contract
382                ),
383            ));
384            continue;
385        }
386        let same_iface: Vec<&&Contract> = contracts
387            .iter()
388            .filter(|c| c.iface.to_string() == e.iface)
389            .collect();
390        let Some(c) = same_iface
391            .iter()
392            .find(|c| Fingerprint::of(c).to_string() == e.contract)
393        else {
394            if !same_iface.is_empty() {
395                report.push(Diagnostic::error(
396                    "D004",
397                    &at,
398                    format!(
399                        "{} names a contract revision that was not supplied",
400                        e.iface
401                    ),
402                ));
403            }
404            continue;
405        };
406        check_exposure(e, c, &held, &at, &mut report);
407    }
408    for (i, r) in d.requires.iter().enumerate() {
409        let at = format!("requires[{i}]");
410        let mut bad = Vec::new();
411        if !is_ident(&r.role) {
412            bad.push(format!("role {:?} is not [a-z][a-z0-9_]*", r.role));
413        }
414        if IfaceId::from_str(&r.interface).is_err() {
415            bad.push(format!(
416                "interface {:?} is not <name>.v<major>",
417                r.interface
418            ));
419        }
420        if let Some(by) = &r.declared_by
421            && !ifaces.contains(by)
422        {
423            bad.push(format!(
424                "declared_by {by:?} is not one of this instance's interfaces"
425            ));
426        }
427        for (k, v) in &r.params {
428            if !is_ident(k) || v.is_empty() {
429                bad.push(format!(
430                    "parameter binding {k:?} = {v:?} is not <name> = a non-empty value"
431                ));
432            }
433        }
434        for b in &r.bindings {
435            let ok = b.split_once('/').is_some_and(|(sys, svc)| {
436                (sys == "*" || is_plain_chunk(sys)) && (svc == "*" || is_plain_chunk(svc))
437            });
438            if !ok {
439                bad.push(format!(
440                    "binding {b:?} is not <system>/<service> (a chunk may be *)"
441                ));
442            }
443        }
444        for m in bad {
445            report.push(Diagnostic::error("D009", &at, m));
446        }
447    }
448    for (i, p) in d.profiles.iter().enumerate() {
449        if IfaceId::from_str(p).is_err() {
450            report.push(Diagnostic::error(
451                "D010",
452                format!("profiles[{i}]"),
453                format!("{p:?} is not <name>.v<major>"),
454            ));
455        }
456    }
457    // Like a capability (D008) and an interface (D003), a profile is listed
458    // once.
459    if d.profiles.iter().collect::<BTreeSet<_>>().len() != d.profiles.len() {
460        report.push(Diagnostic::error(
461            "D010",
462            "profiles",
463            "a profile is listed twice",
464        ));
465    }
466    report
467}
468
469/// The exposure rules of one interface against its contract.
470fn check_exposure(
471    e: &InterfaceEntry,
472    c: &Contract,
473    held: &BTreeSet<&str>,
474    at: &str,
475    report: &mut Report,
476) {
477    for u in &e.unavailable {
478        let Some(r) = resource(c, &u.resource) else {
479            report.push(Diagnostic::error(
480                "D005",
481                at,
482                format!(
483                    "unavailable {:?} is not a resource of {}",
484                    u.resource, c.iface
485                ),
486            ));
487            continue;
488        };
489        if !r.optional {
490            report.push(Diagnostic::error(
491                "D005",
492                at,
493                format!("unavailable {:?} is a required resource", u.resource),
494            ));
495            continue;
496        }
497        let implied = r.gate.iter().any(|g| {
498            g.strip_prefix("capability:")
499                .is_some_and(|cap| !held.contains(cap))
500        });
501        if implied {
502            report.push(Diagnostic::warning(
503                "D006",
504                at,
505                format!(
506                    "unavailable {:?} is already implied by a capability not held",
507                    u.resource
508                ),
509            ));
510        }
511    }
512    for (name, n) in &e.cardinality {
513        let ceiling = resource(c, name).and_then(|r| r.cardinality);
514        match ceiling {
515            None => report.push(Diagnostic::error(
516                "D007",
517                at,
518                format!(
519                    "cardinality {name:?} names no templated resource of {}",
520                    c.iface
521                ),
522            )),
523            Some(max) if *n == 0 || *n > max => report.push(Diagnostic::error(
524                "D007",
525                at,
526                format!("cardinality {name:?} = {n} is not within 1..={max}"),
527            )),
528            Some(_) => {}
529        }
530    }
531}
532
533/// The bytes an owner's descriptor SHOULD stay within (core §3.3): 1 KB.
534pub const SIZE_BYTES: usize = 1024;
535
536/// What the rest of a descriptor stays within where the descriptor MAY
537/// exceed [`SIZE_BYTES`] (core §3.3): the rest is [`Size::other`].
538pub const OTHER_BYTES: usize = 512;
539
540/// A descriptor's bytes against core §3.3's size rule, as
541/// [`Descriptor::size_of`] counts them.
542#[derive(Debug, Clone, Copy, PartialEq, Eq)]
543pub struct Size {
544    /// The whole document's, as its owner wrote it.
545    pub bytes: usize,
546    /// The rest (core §3.3): the size of the same document with
547    /// `interfaces`, `capabilities`, `requires` and `profiles` taken out.
548    /// That is its two braces, every other member and the commas between
549    /// those.
550    pub other: usize,
551}
552
553impl Size {
554    /// Whether the descriptor meets the rule: within [`SIZE_BYTES`], or
555    /// over it with a rest within [`OTHER_BYTES`].
556    #[must_use]
557    pub fn meets(&self) -> bool {
558        self.bytes <= SIZE_BYTES || self.other <= OTHER_BYTES
559    }
560}
561
562impl Descriptor {
563    /// The size of `served`, the document this descriptor's owner put and
564    /// answers, as the owner wrote it (core §3.3): its count of bytes, and
565    /// the rest, which is that count less each of `interfaces`,
566    /// `capabilities`, `requires` and `profiles` the descriptor states.
567    ///
568    /// A member is counted from the opening quote of its name to the last
569    /// byte of its value, and one comma with it. A member taken out of an
570    /// object that keeps another takes exactly one comma with it, wherever
571    /// it stands, and `format`, `service` and `instance` are always
572    /// written. So the rest is exact for the compact form the reference
573    /// writes, every empty member left out. A member's value is counted
574    /// as it serializes here, so the rest of a document its owner spaced
575    /// otherwise counts that member's spacing too.
576    ///
577    /// Nothing here can fail: a value that does not serialize counts for
578    /// nothing, and the rest never falls below 0.
579    #[must_use]
580    pub fn size_of(&self, served: &[u8]) -> Size {
581        fn member<T: Serialize>(name: &str, value: &T, written: bool) -> usize {
582            if !written {
583                return 0;
584            }
585            // `"name":` + the value + `,`.
586            serde_json::to_vec(value).map_or(0, |value| name.len() + 3 + value.len() + 1)
587        }
588        let bytes = served.len();
589        let lists = member("interfaces", &self.interfaces, true)
590            + member(
591                "capabilities",
592                &self.capabilities,
593                !self.capabilities.is_empty(),
594            )
595            + member("requires", &self.requires, !self.requires.is_empty())
596            + member("profiles", &self.profiles, !self.profiles.is_empty());
597        Size {
598            bytes,
599            other: bytes.saturating_sub(lists),
600        }
601    }
602
603    /// This descriptor's size as it serializes here ([`Descriptor::size_of`]
604    /// over its compact JSON, every empty member left out): what an owner
605    /// that has not written it yet would serve.
606    ///
607    /// # Errors
608    /// The descriptor does not serialize.
609    pub fn size(&self) -> Result<Size, serde_json::Error> {
610        Ok(self.size_of(&serde_json::to_vec(self)?))
611    }
612
613    /// The run the descriptor states (core §3.3), `None` when it states
614    /// none or spells it otherwise than 4 or 8 lowercase hex digits (D002).
615    #[must_use]
616    pub fn stated_run(&self) -> Option<Run> {
617        self.run.as_deref().and_then(Run::from_hex)
618    }
619
620    /// The catalog the descriptor names (core §3.3, §8.6), `None` when it
621    /// names none or spells it otherwise than 8 lowercase hex digits (D002).
622    #[must_use]
623    pub fn stated_catalog(&self) -> Option<CatalogId> {
624        self.catalog.as_deref().and_then(CatalogId::from_hex)
625    }
626
627    /// The resources of `contract` this instance exposes (§3.3): the
628    /// contract's, minus the optional ones gated on a capability it does not
629    /// hold, minus those its entry lists `unavailable`; none at all when the
630    /// entry marks the interface `"standby": true` (§3.3, §6, 0.39), whose
631    /// `unavailable` says what it will expose once it serves. `None` when it
632    /// lists no entry for the contract's interface.
633    ///
634    /// What a tool decides a split-brain from, beside replicated serving
635    /// (§6, 0.7, #660). The entry's revision is the caller's to match: this
636    /// reads `contract` as given.
637    #[must_use]
638    pub fn exposed<'c>(
639        &self,
640        contract: &'c Contract,
641    ) -> Option<Vec<&'c crate::contract::Resource>> {
642        let iface = contract.iface.to_string();
643        let entry = self.interfaces.iter().find(|e| e.iface == iface)?;
644        if entry.standby {
645            return Some(Vec::new());
646        }
647        let held = |cap: &str| self.capabilities.iter().any(|h| h == cap);
648        Some(
649            contract
650                .resources
651                .iter()
652                .filter(|r| {
653                    let name = format!("{}/{}", r.token, r.template);
654                    let gated_off = r
655                        .gate
656                        .iter()
657                        .any(|g| g.strip_prefix("capability:").is_some_and(|cap| !held(cap)));
658                    let listed = entry.unavailable.iter().any(|u| u.resource == name);
659                    !(r.optional && (gated_off || listed))
660                })
661                .collect(),
662        )
663    }
664}
665
666fn yes() -> bool {
667    true
668}
669
670/// A resource named `<kind token>/<template>`.
671fn resource<'c>(c: &'c Contract, name: &str) -> Option<&'c crate::contract::Resource> {
672    let (token, template) = name.split_once('/')?;
673    let token = KindToken::from_str(token).ok()?;
674    c.resource(token, template)
675}
676
677/// A capability name: `[a-z0-9][a-z0-9_.-]*`, as in a `capability:` gate.
678fn is_name(s: &str) -> bool {
679    let mut cs = s.chars();
680    cs.next()
681        .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
682        && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "_.-".contains(c))
683}
684
685#[cfg(test)]
686mod tests {
687    use super::{Descriptor, Form};
688
689    /// §3.3, "What carries it": `zenoh/bytes` exactly is the compact form,
690    /// and every other `Encoding` the JSON one, a schema suffix included.
691    #[test]
692    fn the_encoding_alone_tells_the_two_forms_apart() {
693        assert_eq!(Form::of("zenoh/bytes"), Form::Compact);
694        for other in [
695            "application/json",
696            "text/plain",
697            "zenoh/bytes;x",
698            "application/octet-stream",
699        ] {
700            assert_eq!(Form::of(other), Form::Json, "{other}");
701        }
702    }
703
704    /// §3.3's compact exposure: a missing capability implies an optional
705    /// resource absent, as a listed one is; a required resource is always
706    /// exposed.
707    #[test]
708    fn exposure_is_the_contract_minus_the_gated_off_and_the_listed() {
709        let op = |name: &str, extra: &str| {
710            format!(
711                "[resources.{name}]\nkind = \"operation\"\n{extra}\
712                 request = {{ raw = \"text/plain\" }}\nresponse = {{ raw = \"text/plain\" }}\n"
713            )
714        };
715        let toml = format!(
716            "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n{}{}{}",
717            op("a", ""),
718            op("b", "optional = true\n"),
719            op("c", "optional = true\ngate = [\"capability:x\"]\n"),
720        );
721        let l = crate::contract::load_str(&toml, std::path::Path::new("."), None);
722        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
723        let d = |caps: &str, unavailable: &str| -> Descriptor {
724            serde_json::from_str(&format!(
725                r#"{{"format": "zk2-descriptor/0.1", "service": "s/t", "instance": "000000000000000a",
726                    "interfaces": [{{"iface": "t.v1", "contract": "sha256:{}", "minor": 0,
727                                     "unavailable": [{unavailable}]}}],
728                    "capabilities": [{caps}]}}"#,
729                "0".repeat(64)
730            ))
731            .unwrap()
732        };
733        let names = |d: &Descriptor| -> Vec<String> {
734            d.exposed(&c)
735                .unwrap()
736                .iter()
737                .map(|r| r.template.as_str().to_owned())
738                .collect()
739        };
740        assert_eq!(names(&d("", "")), ["a", "b"]);
741        assert_eq!(names(&d("\"x\"", "")), ["a", "b", "c"]);
742        assert_eq!(
743            names(&d("\"x\"", r#"{"resource": "@op/b", "cause": "config"}"#)),
744            ["a", "c"]
745        );
746        // A standby exposes nothing, whatever else its entry says (0.39).
747        let mut standby = d("\"x\"", "");
748        standby.interfaces[0].standby = true;
749        assert!(names(&standby).is_empty());
750        let mut other = d("", "");
751        other.interfaces[0].iface = "u.v1".into();
752        assert!(other.exposed(&c).is_none());
753    }
754
755    /// §3.3: a member the schema defaults is written only when it holds
756    /// something (#1126), and `minor` only when the revision has one
757    /// (#1127); each reads back as it was, and a `null` minor is D000.
758    #[test]
759    fn empty_members_and_an_unknown_minor_are_left_out() {
760        let fp = format!("sha256:{}", "0".repeat(64));
761        let mut d: Descriptor = serde_json::from_str(&format!(
762            r#"{{"format": "zk2-descriptor/0.1", "service": "s/t", "instance": "000000000000000a",
763                "interfaces": [{{"iface": "t.v1", "contract": "{fp}"}}]}}"#
764        ))
765        .unwrap();
766        assert_eq!(d.interfaces[0].minor, None);
767        assert!(d.interfaces[0].token, "absent is true");
768        let text = serde_json::to_string(&d).unwrap();
769        assert_eq!(
770            text,
771            format!(
772                r#"{{"format":"zk2-descriptor/0.1","service":"s/t","instance":"000000000000000a","interfaces":[{{"iface":"t.v1","contract":"{fp}","token":true}}]}}"#
773            )
774        );
775        d.interfaces[0].minor = Some(4);
776        let text = serde_json::to_string(&d).unwrap();
777        assert!(text.contains(r#""minor":4"#), "{text}");
778        assert_eq!(serde_json::from_str::<Descriptor>(&text).unwrap(), d);
779        let null = text.replace(r#""minor":4"#, r#""minor":null"#);
780        let (_, report) = super::check(&null, &[]);
781        assert_eq!(report.codes(), ["D000"], "{report}");
782    }
783
784    /// §3.3's size rule: within 1 KB, or over it with a rest within
785    /// 512 B, the rest being the document with `interfaces`,
786    /// `capabilities`, `requires` and `profiles` taken out.
787    #[test]
788    fn a_descriptor_over_1_kb_is_judged_by_its_other_members() {
789        let fp = format!("sha256:{}", "0".repeat(64));
790        let mut d: Descriptor = serde_json::from_str(&format!(
791            r#"{{"format": "zk2-descriptor/0.1", "service": "s/t", "instance": "000000000000000a",
792                "interfaces": [{{"iface": "t.v1", "contract": "{fp}"}}],
793                "meta": {{"zid": "1"}}}}"#
794        ))
795        .unwrap();
796        let text = serde_json::to_string(&d).unwrap();
797        let small = d.size().unwrap();
798        assert_eq!(small, d.size_of(text.as_bytes()), "as it serializes here");
799        assert_eq!(small.bytes, text.len());
800        // The rest, where a member follows the four.
801        let other = r#"{"format":"zk2-descriptor/0.1","service":"s/t","instance":"000000000000000a","meta":{"zid":"1"}}"#;
802        assert_eq!(small.other, other.len());
803        assert!(small.bytes <= super::SIZE_BYTES && small.meets());
804
805        // Many interfaces and capabilities: over 1 KB by what it must state.
806        let entry = d.interfaces[0].clone();
807        for n in 2..=8 {
808            let mut e = entry.clone();
809            e.iface = format!("t{n}.v1");
810            d.interfaces.push(e);
811        }
812        d.capabilities = (0..30).map(|n| format!("capability_{n}")).collect();
813        d.profiles = vec!["freshness.v2".into()];
814        let many = d.size().unwrap();
815        assert_eq!(many.bytes, serde_json::to_string(&d).unwrap().len());
816        assert!(many.bytes > super::SIZE_BYTES, "{many:?}");
817        assert_eq!(many.other, other.len(), "the four count for nothing");
818        assert!(many.meets());
819
820        // The four come last, `profiles` the last member written: a member
821        // takes one comma with it wherever it stands, so the rest is the
822        // three members left and their braces, to the byte.
823        let mut last = d.clone();
824        last.meta.clear();
825        let text = serde_json::to_string(&last).unwrap();
826        assert!(text.ends_with(r#""profiles":["freshness.v2"]}"#), "{text}");
827        let rest =
828            r#"{"format":"zk2-descriptor/0.1","service":"s/t","instance":"000000000000000a"}"#;
829        assert_eq!(
830            last.size().unwrap(),
831            super::Size {
832                bytes: text.len(),
833                other: rest.len()
834            }
835        );
836        // `interfaces` alone of the four, and the last member written.
837        last.capabilities.clear();
838        last.profiles.clear();
839        let text = serde_json::to_string(&last).unwrap();
840        assert!(text.ends_with("]}") && !text.contains("profiles"), "{text}");
841        assert_eq!(last.size().unwrap().other, rest.len());
842
843        // The same lists beside a `meta` of its own 600 B: not met.
844        d.meta.insert("build".into(), "x".repeat(600).into());
845        let padded = d.size().unwrap();
846        assert!(
847            padded.other > super::OTHER_BYTES && !padded.meets(),
848            "{padded:?}"
849        );
850        // A small descriptor may spend its 1 KB as it likes.
851        d.interfaces.truncate(1);
852        d.capabilities.clear();
853        d.profiles.clear();
854        let lone = d.size().unwrap();
855        assert!(lone.other > super::OTHER_BYTES && lone.bytes <= super::SIZE_BYTES);
856        assert!(lone.meets());
857
858        // The size is the served document's, and the rest never falls
859        // below 0: fewer bytes than the four members take leave none.
860        assert_eq!(
861            d.size_of(b"{}"),
862            super::Size { bytes: 2, other: 0 },
863            "saturating"
864        );
865    }
866}