1use 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
32pub const FORMAT: &str = "zk2-descriptor/0.1";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Form {
39 Json,
41 Compact,
43}
44
45impl Form {
46 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
62#[serde(deny_unknown_fields)]
63pub struct Descriptor {
64 pub format: String,
66 pub service: String,
68 pub instance: String,
70 #[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 #[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 pub interfaces: Vec<InterfaceEntry>,
95 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 #[schemars(extend("default" = []))]
100 pub capabilities: Vec<String>,
101 #[serde(default, skip_serializing_if = "Vec::is_empty")]
104 #[schemars(extend("default" = []))]
105 pub requires: Vec<RequireEntry>,
106 #[serde(default, skip_serializing_if = "Vec::is_empty")]
109 #[schemars(extend("default" = []))]
110 pub profiles: Vec<String>,
111 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
116 #[schemars(extend("default" = {}))]
117 pub meta: BTreeMap<String, Value>,
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
122#[serde(deny_unknown_fields)]
123pub struct InterfaceEntry {
124 pub iface: String,
126 pub contract: String,
128 #[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 #[serde(default, skip_serializing_if = "is_false")]
144 pub standby: bool,
145 #[serde(default = "yes")]
148 pub token: bool,
149 #[serde(default, skip_serializing_if = "Vec::is_empty")]
153 #[schemars(extend("default" = []))]
154 pub unavailable: Vec<Unavailable>,
155 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
159 #[schemars(extend("default" = {}))]
160 pub cardinality: BTreeMap<String, u64>,
161}
162
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
165#[serde(deny_unknown_fields)]
166pub struct Unavailable {
167 pub resource: String,
169 pub cause: Cause,
170 #[serde(default)]
172 pub reason: Option<String>,
173}
174
175#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
186#[serde(deny_unknown_fields)]
187pub struct RequireEntry {
188 pub role: String,
190 pub interface: String,
192 #[serde(default)]
195 pub declared_by: Option<String>,
196 pub bindings: Vec<String>,
198 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
202 #[schemars(extend("default" = {}))]
203 pub params: BTreeMap<String, String>,
204 #[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
217fn some_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
219 String::deserialize(d).map(Some)
220}
221
222fn some_u64<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
224 u64::deserialize(d).map(Some)
225}
226
227#[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#[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 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 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 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
469fn 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
533pub const SIZE_BYTES: usize = 1024;
535
536pub const OTHER_BYTES: usize = 512;
539
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
543pub struct Size {
544 pub bytes: usize,
546 pub other: usize,
551}
552
553impl Size {
554 #[must_use]
557 pub fn meets(&self) -> bool {
558 self.bytes <= SIZE_BYTES || self.other <= OTHER_BYTES
559 }
560}
561
562impl Descriptor {
563 #[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 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 pub fn size(&self) -> Result<Size, serde_json::Error> {
610 Ok(self.size_of(&serde_json::to_vec(self)?))
611 }
612
613 #[must_use]
616 pub fn stated_run(&self) -> Option<Run> {
617 self.run.as_deref().and_then(Run::from_hex)
618 }
619
620 #[must_use]
623 pub fn stated_catalog(&self) -> Option<CatalogId> {
624 self.catalog.as_deref().and_then(CatalogId::from_hex)
625 }
626
627 #[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
670fn 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
677fn 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 #[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 #[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 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 #[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 #[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 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 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 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 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 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 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 assert_eq!(
861 d.size_of(b"{}"),
862 super::Size { bytes: 2, other: 0 },
863 "saturating"
864 );
865 }
866}