1use std::collections::{BTreeMap, BTreeSet};
16use std::path::Path;
17use std::str::FromStr;
18
19use serde_json::Value;
20
21use crate::authoring::{
22 self as a, ContractFile, DefaultsBlock, DefaultsSection, Encoding, Kind, ParamType,
23 ResourceSpec, TypeRef,
24};
25use crate::chunk::is_ident;
26use crate::diag::{Diagnostic, Report};
27use crate::grammar::{IfaceId, KindToken};
28use crate::schema::{Artifact, SchemaSet, TypeId};
29use crate::template::{Segment, Template};
30
31pub use crate::authoring::{
32 Congestion, Fanout, HistoryParams, Priority, Reliability, Replies, RequireCardinality, Serving,
33};
34
35#[derive(Debug, Clone)]
37pub struct Contract {
38 pub iface: IfaceId,
39 pub minor: Option<u32>,
41 pub summary: Option<String>,
43 pub uses: Vec<IfaceId>,
45 pub resources: Vec<Resource>,
47 pub requires: BTreeMap<String, Requirement>,
48 pub artifacts: BTreeMap<String, Artifact>,
50}
51
52impl Contract {
53 #[must_use]
55 pub fn resource(&self, token: KindToken, template: &str) -> Option<&Resource> {
56 self.resources
57 .iter()
58 .find(|r| r.token == token && r.template.as_str() == template)
59 }
60
61 pub fn packed_layout(&self, ty: &TypeId) -> Result<Option<crate::packed::Layout>, String> {
70 let TypeId::Packed { name, schema } = ty else {
71 return Ok(None);
72 };
73 match self.artifacts.get(schema).map(|a| &a.data) {
74 Some(crate::schema::ArtifactData::Json(doc)) => {
75 crate::packed::layout_in(doc, name).map(Some)
76 }
77 _ => Err(format!(
78 "packed:{name}: the contract carries no packed artifact {schema}"
79 )),
80 }
81 }
82}
83
84#[derive(Debug, Clone)]
86pub struct Resource {
87 pub template: Template,
88 pub kind: Kind,
89 pub token: KindToken,
90 pub doc: Option<String>,
92 pub params: BTreeMap<String, ParamType>,
93 pub cardinality: Option<u64>,
94 pub epoch: Option<String>,
95 pub optional: bool,
96 pub gate: Vec<String>,
98 pub deprecated: Option<a::Deprecated>,
99 pub annotations: BTreeMap<String, Value>,
101 pub body: Body,
102}
103
104#[derive(Debug, Clone)]
105pub enum Body {
106 Data(Data),
107 Operation(Operation),
108}
109
110#[derive(Debug, Clone)]
112pub struct Data {
113 pub type_: TypeId,
114 pub attachment: Option<TypeId>,
115 pub encoding: Option<Encoding>,
117 pub attachment_encoding: Option<Encoding>,
119 pub reliability: Reliability,
120 pub congestion: Congestion,
121 pub priority: Priority,
122 pub express: bool,
123 pub history: Option<HistoryParams>,
124 pub frame: Option<crate::frame::FrameParams>,
127 pub rate: Option<Rate>,
129 pub retention_s: Option<u64>,
131}
132
133#[derive(Debug, Clone)]
135pub struct Operation {
136 pub request: TypeId,
137 pub response: TypeId,
138 pub error: Option<TypeId>,
139 pub summary: Option<TypeId>,
140 pub encoding: Option<Encoding>,
142 pub idempotent: bool,
143 pub fanout: Fanout,
144 pub serving: Serving,
145 pub replies: Replies,
146 pub timeout_ms: Option<u64>,
147 pub priority: Priority,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub enum Rate {
154 Rare,
156 Low,
158 Burst(u32),
160}
161
162impl Rate {
163 #[must_use]
166 pub fn parse(s: &str) -> Option<Self> {
167 match s {
168 "rare" => Some(Self::Rare),
169 "low" => Some(Self::Low),
170 _ => {
171 let n = s.strip_prefix("burst(")?.strip_suffix("/h)")?;
172 if n.is_empty()
173 || !n.bytes().all(|b| b.is_ascii_digit())
174 || (n.len() > 1 && n.starts_with('0'))
175 {
176 return None;
177 }
178 n.parse().ok().filter(|n| *n > 0).map(Self::Burst)
179 }
180 }
181 }
182}
183
184impl std::fmt::Display for Rate {
185 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186 match self {
187 Self::Rare => f.write_str("rare"),
188 Self::Low => f.write_str("low"),
189 Self::Burst(n) => write!(f, "burst({n}/h)"),
190 }
191 }
192}
193
194fn parse_duration_s(s: &str) -> Option<u64> {
196 let unit = s.chars().last()?;
197 let n = &s[..s.len() - 1];
198 if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) {
199 return None;
200 }
201 let mul = match unit {
202 's' => 1,
203 'm' => 60,
204 'h' => 3600,
205 'd' => 86_400,
206 'w' => 604_800,
207 _ => return None,
208 };
209 n.parse::<u64>().ok()?.checked_mul(mul).filter(|v| *v > 0)
210}
211
212#[derive(Debug, Clone)]
214pub struct Requirement {
215 pub interface: IfaceId,
216 pub resources: Option<Vec<String>>,
218 pub cardinality: RequireCardinality,
219 pub optional: bool,
220 pub doc: Option<String>,
222 pub annotations: BTreeMap<String, Value>,
223}
224
225#[derive(Debug)]
227pub struct Loaded {
228 pub contract: Option<Contract>,
230 pub report: Report,
231}
232
233#[must_use]
236pub fn load_path(path: &Path) -> Loaded {
237 let mut report = Report::default();
238 let text = match std::fs::read_to_string(path) {
239 Ok(t) => t,
240 Err(e) => {
241 report.push(Diagnostic::error(
242 "E000",
243 "file",
244 format!("cannot be read: {e}"),
245 ));
246 return Loaded {
247 contract: None,
248 report,
249 };
250 }
251 };
252 let dir = path.parent().unwrap_or(Path::new("."));
253 let name = path.file_name().and_then(|n| n.to_str());
254 load_str(&text, dir, name)
255}
256
257#[must_use]
260pub fn load_str(text: &str, dir: &Path, file_name: Option<&str>) -> Loaded {
261 let mut report = Report::default();
262 let parsed = toml::from_str(text).map(|f| (f, crate::toml10::first_beyond_toml10(text)));
263 let file: ContractFile = match parsed {
264 Ok((_, Some((line, what)))) => {
265 report.push(Diagnostic::error(
266 "E000",
267 "file",
268 format!("line {line}: {what} is not TOML 1.0, which a contract is (spec §9.1)"),
269 ));
270 return Loaded {
271 contract: None,
272 report,
273 };
274 }
275 Ok((f, None)) => f,
276 Err(e) => {
277 let msg = e.to_string().trim().replace('\n', " ");
278 report.push(Diagnostic::error("E000", "file", msg));
279 return Loaded {
280 contract: None,
281 report,
282 };
283 }
284 };
285 let contract = resolve(&file, dir, file_name, &mut report);
286 let contract = if report.has_errors() { None } else { contract };
287 if let Some(c) = &contract {
288 crate::canonical::check_contract_restrictions(&crate::canonical::canonical(c), &mut report);
289 }
290 let contract = if report.has_errors() { None } else { contract };
291 Loaded { contract, report }
292}
293
294struct Ctx<'a> {
295 report: &'a mut Report,
296 schemas: SchemaSet,
297 defaults: DefaultsSection,
298 base: DefaultsBlock,
299 profiles: BTreeMap<String, u32>,
301 minor: Option<u32>,
302}
303
304fn resolve(
305 file: &ContractFile,
306 dir: &Path,
307 file_name: Option<&str>,
308 report: &mut Report,
309) -> Option<Contract> {
310 let i = &file.interface;
311 let iface = match IfaceId::new(&i.name, i.major) {
312 Ok(id) => Some(id),
313 Err(e) => {
314 report.push(Diagnostic::error("E001", "interface", e.to_string()));
315 None
316 }
317 };
318 if i.minor.is_none() {
319 report.push(Diagnostic::warning(
320 "W104",
321 "interface",
322 "`minor` is missing",
323 ));
324 }
325 if let (Some(id), Some(f)) = (&iface, file_name) {
326 let want = format!("{id}.toml");
327 if f != want {
328 report.push(Diagnostic::warning(
329 "W107",
330 "file",
331 format!("the file is named {f:?}; the convention is {want:?}"),
332 ));
333 }
334 }
335 let mut uses = BTreeSet::new();
336 for u in &i.uses {
337 match IfaceId::from_str(u) {
338 Ok(p) => {
339 uses.insert(p);
340 }
341 Err(_) => report.push(Diagnostic::error(
342 "E002",
343 "interface.uses",
344 format!("{u:?} is not a profile id <name>.v<major>"),
345 )),
346 }
347 }
348 let mut majors: BTreeMap<&str, Vec<String>> = BTreeMap::new();
351 for p in &uses {
352 majors.entry(p.name()).or_default().push(p.to_string());
353 }
354 for (name, ids) in majors.iter().filter(|(_, ids)| ids.len() > 1) {
355 report.push(Diagnostic::error(
356 "E002",
357 "interface.uses",
358 format!(
359 "profile {name:?} is listed at more than one major ({}): an annotation key \
360 names its profile without a major, so a contract uses one major of it",
361 ids.join(", ")
362 ),
363 ));
364 }
365 let profiles = uses
366 .iter()
367 .map(|p| (p.name().to_owned(), p.major()))
368 .collect();
369 let schemas = SchemaSet::load(dir, &file.schemas, report);
370 let defaults = file.defaults.clone().unwrap_or_default();
371 let mut cx = Ctx {
372 report,
373 schemas,
374 base: defaults.base(),
375 defaults,
376 profiles,
377 minor: i.minor,
378 };
379 check_defaults(&mut cx);
380
381 let mut resources = Vec::new();
382 for (raw, spec) in &file.resources {
383 if let Some(r) = resolve_resource(raw, spec, &mut cx) {
384 resources.push(r);
385 }
386 }
387 resources.sort_by(|x: &Resource, y: &Resource| {
388 (x.token.as_str(), x.template.as_str()).cmp(&(y.token.as_str(), y.template.as_str()))
389 });
390 if cx.schemas.has_tag_zero() {
394 let uses: Vec<IfaceId> = uses.iter().cloned().collect();
395 let derived = crate::config::v2::derived_types(&crate::config::v2::Resources::of_parts(
396 &uses,
397 &resources,
398 cx.schemas.artifacts(),
399 ));
400 cx.schemas.report_tag_zero(&derived, cx.report);
401 }
402 check_shapes(file, cx.report);
403 check_overlaps(&resources, cx.report);
404 let mut epochs = file.resources.iter().filter(|(_, s)| s.epoch.is_some());
407 if epochs.next().is_some() {
408 for (raw, _) in epochs {
409 cx.report.push(Diagnostic::error(
410 "E022",
411 at_res(raw),
412 "a second `epoch` template in one interface: member keys carry no template",
413 ));
414 }
415 }
416 for (raw, spec) in &file.resources {
417 if let Some(d) = &spec.deprecated
418 && let Some(to) = &d.replaced_by
419 && (to == raw || !file.resources.contains_key(to))
420 {
421 cx.report.push(Diagnostic::error(
422 "E031",
423 at_res(raw),
424 format!(
425 "`deprecated.replaced_by` {to:?} names no other template of this interface"
426 ),
427 ));
428 }
429 }
430
431 let mut requires = BTreeMap::new();
432 for (role, req) in &file.requires {
433 if let Some(r) = resolve_requirement(role, req, &mut cx) {
434 requires.insert(role.clone(), r);
435 }
436 }
437
438 Some(Contract {
439 iface: iface?,
440 minor: i.minor,
441 summary: i.summary.clone(),
442 uses: uses.into_iter().collect(),
443 resources,
444 requires,
445 artifacts: cx.schemas.artifacts().clone(),
446 })
447}
448
449#[must_use]
451pub fn token_of(kind: Kind, explicit: bool) -> KindToken {
452 match (kind, explicit) {
453 (Kind::Stream, false) => KindToken::Stream,
454 (Kind::Stream, true) => KindToken::ExplicitStream,
455 (Kind::State, false) => KindToken::State,
456 (Kind::State, true) => KindToken::ExplicitState,
457 (Kind::Event, _) => KindToken::Events,
458 (Kind::Operation, _) => KindToken::Op,
459 }
460}
461
462fn at_res(raw: &str) -> String {
463 format!("resources.{raw:?}")
464}
465
466const DATA_FIELDS: &[&str] = &[
467 "type",
468 "attachment",
469 "encoding",
470 "attachment_encoding",
471 "reliability",
472 "congestion",
473 "priority",
474 "express",
475];
476const OP_FIELDS: &[&str] = &[
477 "request",
478 "response",
479 "error",
480 "summary",
481 "encoding",
482 "idempotent",
483 "fanout",
484 "serving",
485 "replies",
486 "timeout_ms",
487 "priority",
488];
489
490fn illegal(kind: Kind, explicit: bool, field: &str) -> Option<&'static str> {
492 let ok = match field {
493 "history" => {
494 return (!(matches!(kind, Kind::Stream | Kind::State) && !explicit)).then_some("E019");
495 }
496 "frame" => return (!(kind == Kind::Stream && !explicit)).then_some("E046"),
499 "explicit" => matches!(kind, Kind::Stream | Kind::State),
500 "rate" | "retention" => kind == Kind::Event,
501 f if kind == Kind::Operation => OP_FIELDS.contains(&f),
502 f => DATA_FIELDS.contains(&f),
503 };
504 (!ok).then_some("E014")
505}
506
507fn block_fields(b: &DefaultsBlock) -> Vec<&'static str> {
508 let mut v = Vec::new();
509 let mut p = |set: bool, n: &'static str| {
510 if set {
511 v.push(n);
512 }
513 };
514 p(b.encoding.is_some(), "encoding");
515 p(b.attachment_encoding.is_some(), "attachment_encoding");
516 p(b.reliability.is_some(), "reliability");
517 p(b.congestion.is_some(), "congestion");
518 p(b.priority.is_some(), "priority");
519 p(b.express.is_some(), "express");
520 p(b.history.is_some(), "history");
521 p(b.idempotent.is_some(), "idempotent");
522 p(b.fanout.is_some(), "fanout");
523 p(b.serving.is_some(), "serving");
524 p(b.replies.is_some(), "replies");
525 p(b.timeout_ms.is_some(), "timeout_ms");
526 v
527}
528
529fn spec_fields(s: &ResourceSpec) -> Vec<&'static str> {
530 let mut v = Vec::new();
531 let mut p = |set: bool, n: &'static str| {
532 if set {
533 v.push(n);
534 }
535 };
536 p(s.type_.is_some(), "type");
537 p(s.attachment.is_some(), "attachment");
538 p(s.encoding.is_some(), "encoding");
539 p(s.attachment_encoding.is_some(), "attachment_encoding");
540 p(s.explicit.is_some(), "explicit");
541 p(s.reliability.is_some(), "reliability");
542 p(s.congestion.is_some(), "congestion");
543 p(s.priority.is_some(), "priority");
544 p(s.express.is_some(), "express");
545 p(s.history.is_some(), "history");
546 p(s.frame.is_some(), "frame");
547 p(s.rate.is_some(), "rate");
548 p(s.retention.is_some(), "retention");
549 p(s.request.is_some(), "request");
550 p(s.response.is_some(), "response");
551 p(s.error.is_some(), "error");
552 p(s.idempotent.is_some(), "idempotent");
553 p(s.fanout.is_some(), "fanout");
554 p(s.serving.is_some(), "serving");
555 p(s.replies.is_some(), "replies");
556 p(s.summary.is_some(), "summary");
557 p(s.timeout_ms.is_some(), "timeout_ms");
558 v
559}
560
561fn check_defaults(cx: &mut Ctx<'_>) {
562 check_annotations(&cx.base.annotations, "defaults", &cx.profiles, cx.report);
563 check_history(cx.base.history.as_ref(), "defaults", cx.report);
564 for kind in [Kind::Stream, Kind::State, Kind::Event, Kind::Operation] {
565 let Some(b) = cx.defaults.for_kind(kind) else {
566 continue;
567 };
568 let at = format!("defaults.{}", kind.as_str());
569 for f in block_fields(b) {
570 if let Some(code) = illegal(kind, false, f) {
571 cx.report.push(Diagnostic::error(
572 code,
573 at.clone(),
574 format!("`{f}` is not a field of kind = {:?}", kind.as_str()),
575 ));
576 }
577 }
578 check_annotations(&b.annotations, &at, &cx.profiles, cx.report);
579 check_history(b.history.as_ref(), &at, cx.report);
580 }
581}
582
583fn check_history(h: Option<&a::History>, at: &str, report: &mut Report) {
584 if let Some(a::History::Params(p)) = h
585 && p.depth == 0
586 {
587 report.push(Diagnostic::error(
588 "E034",
589 at,
590 "`history.depth` must be at least 1",
591 ));
592 }
593}
594
595const VOCABULARIES: &[(&str, &[&str])] = &[
619 (crate::freshness::NAME, crate::freshness::VOCABULARY),
620 (crate::timing::NAME, crate::timing::VOCABULARY),
621 (crate::telemetry::NAME, crate::telemetry::VOCABULARY),
622 (crate::link::NAME, crate::link::VOCABULARY),
623 (crate::arbitration::NAME, crate::arbitration::VOCABULARY),
624 (crate::desired::NAME, crate::desired::VOCABULARY),
625 (crate::alarms::NAME, crate::alarms::VOCABULARY),
626 (
627 "media",
628 &[
629 "tiers",
630 "tier_param",
631 "frame_clock",
632 "control",
633 "receiver_report",
634 ],
635 ),
636 ("views", &["document"]),
637 (crate::redundancy::NAME, crate::redundancy::VOCABULARY),
638];
639
640fn vocabulary(name: &str, major: u32) -> Option<&'static [&'static str]> {
643 if name == crate::telemetry::NAME && major == 2 {
644 return Some(crate::telemetry::VOCABULARY_V2);
645 }
646 if name == crate::desired::NAME && major == 2 {
647 return Some(crate::desired::v2::VOCABULARY);
648 }
649 if name == crate::health::NAME && major == 2 {
650 return Some(crate::health::v2::VOCABULARY);
651 }
652 if name == crate::alarms::NAME && major == 2 {
653 return Some(crate::alarms::v2::VOCABULARY);
654 }
655 VOCABULARIES
656 .iter()
657 .find(|(n, _)| *n == name)
658 .map(|(_, keys)| *keys)
659}
660
661fn check_annotations(
662 map: &BTreeMap<String, Value>,
663 at: &str,
664 profiles: &BTreeMap<String, u32>,
665 report: &mut Report,
666) {
667 for (k, v) in map {
668 if has_datetime(v) {
669 report.push(Diagnostic::error(
670 "E020",
671 at,
672 format!("annotation {k:?}: a TOML datetime has no JSON value"),
673 ));
674 }
675 let Some((p, key)) = k.rsplit_once('.') else {
676 report.push(Diagnostic::error(
677 "E020",
678 at,
679 format!("annotation {k:?} is not <profile>.<key>"),
680 ));
681 continue;
682 };
683 if IfaceId::new(p, 1).is_err() || !is_ident(key) {
684 report.push(Diagnostic::error(
685 "E020",
686 at,
687 format!("annotation {k:?} is not <profile>.<key>"),
688 ));
689 } else if !profiles.contains_key(p) {
690 report.push(Diagnostic::error(
691 "E020",
692 at,
693 format!("annotation {k:?}: profile {p:?} is not listed in `uses`"),
694 ));
695 } else if let Some(keys) = vocabulary(p, profiles[p])
696 && !keys.contains(&key)
697 {
698 report.push(Diagnostic::warning(
699 "W105",
700 at,
701 format!("annotation {k:?} is not in {p}'s vocabulary {keys:?}"),
702 ));
703 }
704 }
705}
706
707fn has_datetime(v: &Value) -> bool {
709 match v {
710 Value::Object(m) => m.contains_key(a::DATETIME) || m.values().any(has_datetime),
711 Value::Array(a) => a.iter().any(has_datetime),
712 _ => false,
713 }
714}
715
716fn check_gate(g: &str) -> bool {
717 let Some((kind, name)) = g.split_once(':') else {
718 return false;
719 };
720 let mut cs = name.chars();
721 matches!(kind, "build" | "config" | "capability")
722 && cs
723 .next()
724 .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
725 && cs.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "_.-".contains(c))
726}
727
728fn pick<T: Clone>(
730 own: Option<&T>,
731 kind: Option<&DefaultsBlock>,
732 base: &DefaultsBlock,
733 f: impl Fn(&DefaultsBlock) -> Option<&T>,
734) -> Option<T> {
735 own.or_else(|| kind.and_then(&f))
736 .or_else(|| f(base))
737 .cloned()
738}
739
740const E013_SPELLINGS: &str =
743 "write a number, the most members one instance will hold, or \"unbounded\"";
744
745#[allow(clippy::too_many_lines)]
746fn resolve_resource(raw: &str, spec: &ResourceSpec, cx: &mut Ctx<'_>) -> Option<Resource> {
747 let at = at_res(raw);
748 let template = match Template::parse(raw) {
749 Ok(t) => t,
750 Err(e) => {
751 cx.report.push(Diagnostic::error("E010", at, e.to_string()));
752 return None;
753 }
754 };
755 let kind = spec.kind;
756 let explicit = spec.explicit.unwrap_or(false);
757 let token = token_of(kind, explicit);
758 let errors_before = cx.report.errors().count();
759 for f in spec_fields(spec) {
760 if let Some(code) = illegal(kind, explicit, f) {
761 let why = match code {
762 "E019" => "`history` is for plain (non-explicit) stream and state resources only"
763 .to_owned(),
764 "E046" => "`frame` is for a plain (non-explicit) stream resource only".to_owned(),
765 _ => format!("`{f}` is not a field of kind = {:?}", kind.as_str()),
766 };
767 cx.report.push(Diagnostic::error(code, at.clone(), why));
768 } else if f == "frame" && template.has_params() {
769 cx.report.push(Diagnostic::error(
770 "E046",
771 at.clone(),
772 "`frame` on a template with a parameter: a frame resource's fields are concrete",
773 ));
774 }
775 }
776
777 let tparams: Vec<(&str, bool)> = template.params().collect();
779 for (name, rest) in &tparams {
780 match spec.params.get(*name) {
781 None => cx.report.push(Diagnostic::error(
782 "E011",
783 at.clone(),
784 format!("template parameter {name:?} has no entry in `params`"),
785 )),
786 Some(t) => {
787 if (*t == ParamType::Path) != *rest {
788 cx.report.push(Diagnostic::error(
789 "E012",
790 at.clone(),
791 format!("parameter {name:?}: `path` is the type of a rest parameter {{x...}}, and only of one"),
792 ));
793 }
794 }
795 }
796 }
797 for name in spec.params.keys() {
798 if !tparams.iter().any(|(n, _)| n == name) {
799 cx.report.push(Diagnostic::error(
800 "E011",
801 at.clone(),
802 format!("`params` declares {name:?}, which the template does not have"),
803 ));
804 }
805 }
806 let cardinality = spec.cardinality.map(a::Cardinality::value);
809 match (template.has_params(), cardinality) {
810 (true, None) => cx.report.push(Diagnostic::error(
811 "E013",
812 at.clone(),
813 format!("a templated resource declares its `cardinality`; {E013_SPELLINGS}"),
814 )),
815 (true, Some(0)) => cx.report.push(Diagnostic::error(
816 "E013",
817 at.clone(),
818 format!("`cardinality` is at least 1; {E013_SPELLINGS}"),
819 )),
820 (false, Some(_)) => cx.report.push(Diagnostic::error(
821 "E014",
822 at.clone(),
823 "`cardinality` on a template without parameters",
824 )),
825 _ => {}
826 }
827 let single = |n: &str| {
828 template
829 .segments()
830 .iter()
831 .any(|s| matches!(s, Segment::Param(p) if p == n))
832 };
833 if let Some(e) = &spec.epoch
834 && !single(e)
835 {
836 cx.report.push(Diagnostic::error(
837 "E022",
838 at.clone(),
839 format!("`epoch` {e:?} is not a single-chunk parameter of the template"),
840 ));
841 }
842
843 let mut gate: Vec<String> = spec
845 .gate
846 .as_ref()
847 .map(|g| g.items().into_iter().map(str::to_owned).collect())
848 .unwrap_or_default();
849 gate.sort();
850 gate.dedup();
851 if !gate.is_empty() && !spec.optional {
852 cx.report.push(Diagnostic::error(
853 "E016",
854 at.clone(),
855 "`gate` without `optional = true`",
856 ));
857 }
858 for g in &gate {
859 if !check_gate(g) {
860 let hint = if g.starts_with("feature:") {
861 " (draft 0's `feature:` is `build:` in draft 1)"
862 } else {
863 ""
864 };
865 cx.report.push(Diagnostic::error(
866 "E017",
867 at.clone(),
868 format!(
869 "gate {g:?} is not build:|config:|capability: plus [a-z0-9][a-z0-9_.-]*{hint}"
870 ),
871 ));
872 }
873 }
874 if let Some(d) = &spec.deprecated
875 && let Some(m) = cx.minor
876 && d.since > m
877 {
878 cx.report.push(Diagnostic::error(
879 "E031",
880 at.clone(),
881 format!(
882 "`deprecated.since` = {} is later than the interface minor {m}",
883 d.since
884 ),
885 ));
886 }
887
888 check_annotations(&spec.annotations, &at, &cx.profiles, cx.report);
890 let kd = cx.defaults.for_kind(kind).cloned();
891 let kd = kd.as_ref();
892 let mut annotations = cx.base.annotations.clone();
893 if let Some(k) = kd {
894 annotations.extend(k.annotations.clone());
895 }
896 annotations.extend(spec.annotations.clone());
897
898 let body = if kind == Kind::Operation {
899 resolve_op(&at, spec, kd, &tparams, cx)
900 } else {
901 resolve_data(&at, spec, kind, explicit, kd, &template, &annotations, cx)
902 };
903 if cx.report.errors().count() > errors_before {
904 return None;
905 }
906 Some(Resource {
907 template,
908 kind,
909 token,
910 doc: spec.doc.clone(),
911 params: spec.params.clone(),
912 cardinality,
913 epoch: spec.epoch.clone(),
914 optional: spec.optional,
915 gate,
916 deprecated: spec.deprecated.clone(),
917 annotations,
918 body: body?,
919 })
920}
921
922fn resolve_type(
923 r: Option<&TypeRef>,
924 what: &str,
925 at: &str,
926 template: Option<&Template>,
927 cx: &mut Ctx<'_>,
928) -> Option<TypeId> {
929 let t = cx.schemas.resolve(r?, &format!("{at} {what}"), cx.report)?;
930 if let (
931 TypeId::Raw {
932 media_param: Some(p),
933 ..
934 },
935 Some(tpl),
936 ) = (&t, template)
937 {
938 let ok = tpl
939 .segments()
940 .iter()
941 .any(|s| matches!(s, Segment::Param(n) if n == p));
942 if !ok {
943 cx.report.push(Diagnostic::error(
944 "E025",
945 at,
946 format!(
947 "{what}: `media_param` {p:?} is not a single-chunk parameter of the template"
948 ),
949 ));
950 }
951 }
952 Some(t)
953}
954
955#[allow(clippy::too_many_arguments)]
956fn resolve_data(
957 at: &str,
958 spec: &ResourceSpec,
959 kind: Kind,
960 explicit: bool,
961 kd: Option<&DefaultsBlock>,
962 template: &Template,
963 annotations: &BTreeMap<String, Value>,
964 cx: &mut Ctx<'_>,
965) -> Option<Body> {
966 if spec.type_.is_none() {
967 cx.report.push(Diagnostic::error(
968 "E015",
969 at,
970 format!("kind = {:?} requires `type`", kind.as_str()),
971 ));
972 }
973 let type_ = resolve_type(spec.type_.as_ref(), "type", at, Some(template), cx);
974 let attachment = resolve_type(
975 spec.attachment.as_ref(),
976 "attachment",
977 at,
978 Some(template),
979 cx,
980 );
981 if kind == Kind::Stream && explicit && type_.as_ref().is_some_and(TypeId::is_packed) {
984 cx.report.push(Diagnostic::error(
985 "E044",
986 at,
987 "type: a packed type on an explicit stream, whose samples carry no CH for its tag",
988 ));
989 }
990 if attachment.as_ref().is_some_and(TypeId::is_packed) {
991 cx.report.push(Diagnostic::error(
992 "E044",
993 at,
994 "attachment: a packed type as an attachment, which carries no CH for its tag",
995 ));
996 }
997 let base = cx.base.clone();
998 let encoding = match &type_ {
1001 Some(t) if t.is_json() => Some(
1002 pick(spec.encoding.as_ref(), kd, &base, |b| b.encoding.as_ref())
1003 .unwrap_or(Encoding::Json),
1004 ),
1005 Some(_) => {
1006 if spec.encoding.is_some() {
1007 cx.report.push(Diagnostic::warning(
1008 "W103",
1009 at,
1010 "`encoding` on a protobuf or raw type is ignored",
1011 ));
1012 }
1013 None
1014 }
1015 None => None,
1016 };
1017 let attachment_encoding = match &attachment {
1018 Some(t) if t.is_json() => Some(
1019 pick(spec.attachment_encoding.as_ref(), kd, &base, |b| {
1020 b.attachment_encoding.as_ref()
1021 })
1022 .unwrap_or(Encoding::Json),
1023 ),
1024 None if spec.attachment.is_some() => None,
1025 _ => {
1026 if spec.attachment_encoding.is_some() {
1027 cx.report.push(Diagnostic::warning(
1028 "W103",
1029 at,
1030 "`attachment_encoding` without a JSON Schema attachment is ignored",
1031 ));
1032 }
1033 None
1034 }
1035 };
1036 let (rel, cong, prio) = match (kind, explicit) {
1037 (Kind::Stream, false) => (Reliability::BestEffort, Congestion::Drop, Priority::Data),
1038 (Kind::Stream, true) => (Reliability::BestEffort, Congestion::Drop, Priority::DataLow),
1039 _ => (Reliability::Reliable, Congestion::Block, Priority::Data),
1040 };
1041 let history = if illegal(kind, explicit, "history").is_none() {
1042 let h = pick(spec.history.as_ref(), kd, &base, |b| b.history.as_ref());
1043 check_history(spec.history.as_ref(), at, cx.report);
1044 match h {
1045 None | Some(a::History::Flag(false)) => None,
1046 Some(a::History::Flag(true)) => Some(HistoryParams {
1047 depth: 1,
1048 miss_detection_ms: None,
1049 }),
1050 Some(a::History::Params(p)) => Some(p),
1051 }
1052 } else {
1053 None
1054 };
1055 let frame = match &spec.frame {
1056 Some(f) if kind == Kind::Stream && !explicit && !template.has_params() => {
1057 resolve_frame(at, f, type_.as_ref(), annotations, cx)
1058 }
1059 _ => None,
1060 };
1061 let (mut rate, mut retention_s) = (None, None);
1062 if kind == Kind::Event {
1063 match &spec.rate {
1064 None => cx.report.push(Diagnostic::error(
1065 "E015",
1066 at,
1067 "kind = \"event\" requires `rate`",
1068 )),
1069 Some(s) => {
1070 rate = Rate::parse(s);
1071 if rate.is_none() {
1072 cx.report.push(Diagnostic::error(
1073 "E026",
1074 at,
1075 format!("`rate` {s:?} is not \"rare\", \"low\" or \"burst(<n>/h)\""),
1076 ));
1077 }
1078 }
1079 }
1080 match &spec.retention {
1081 None => cx.report.push(Diagnostic::error(
1082 "E015",
1083 at,
1084 "kind = \"event\" requires `retention`",
1085 )),
1086 Some(s) => {
1087 retention_s = parse_duration_s(s);
1088 if retention_s.is_none() {
1089 cx.report.push(Diagnostic::error(
1090 "E026",
1091 at,
1092 format!("`retention` {s:?} is not a positive duration <n>s|m|h|d|w"),
1093 ));
1094 }
1095 }
1096 }
1097 }
1098 Some(Body::Data(Data {
1099 type_: type_?,
1100 attachment,
1101 encoding,
1102 attachment_encoding,
1103 reliability: pick(spec.reliability.as_ref(), kd, &base, |b| {
1104 b.reliability.as_ref()
1105 })
1106 .unwrap_or(rel),
1107 congestion: pick(spec.congestion.as_ref(), kd, &base, |b| {
1108 b.congestion.as_ref()
1109 })
1110 .unwrap_or(cong),
1111 priority: pick(spec.priority.as_ref(), kd, &base, |b| b.priority.as_ref()).unwrap_or(prio),
1112 express: pick(spec.express.as_ref(), kd, &base, |b| b.express.as_ref()).unwrap_or(false),
1113 history,
1114 frame,
1115 rate,
1116 retention_s,
1117 }))
1118}
1119
1120fn resolve_frame(
1127 at: &str,
1128 spec: &a::FrameSpec,
1129 type_: Option<&TypeId>,
1130 annotations: &BTreeMap<String, Value>,
1131 cx: &mut Ctx<'_>,
1132) -> Option<crate::frame::FrameParams> {
1133 let params = match crate::frame::FrameParams::resolve(spec) {
1134 Ok(p) => Some(p),
1135 Err(why) => {
1136 for w in why {
1137 cx.report.push(Diagnostic::error("E048", at, w));
1138 }
1139 None
1140 }
1141 };
1142 match type_ {
1144 Some(t) if !t.is_packed() => cx.report.push(Diagnostic::error(
1145 "E047",
1146 at,
1147 format!("a frame resource's type is {}, not packed", t.kind_str()),
1148 )),
1149 Some(t) => {
1150 if let Some(layout) = cx.schemas.packed_layout(t).cloned() {
1151 if layout
1152 .items
1153 .iter()
1154 .any(|i| matches!(i, crate::packed::Item::Marker))
1155 {
1156 cx.report.push(Diagnostic::error(
1157 "E047",
1158 at,
1159 "a frame resource's packed type has an extension marker: a delta \
1160 record's bitmap has one width for every reader",
1161 ));
1162 }
1163 for name in spec.deadband.keys() {
1164 match layout.fields().find(|f| &f.name == name) {
1165 None => cx.report.push(Diagnostic::error(
1166 "E049",
1167 at,
1168 format!("the deadband names {name:?}, no field of the record type"),
1169 )),
1170 Some(f) if !crate::frame::takes_deadband(f) => {
1171 cx.report.push(Diagnostic::error(
1172 "E049",
1173 at,
1174 format!(
1175 "the deadband names {name:?}, a {} field: only an int, \
1176 fixed or counter takes one",
1177 f.kind.as_str()
1178 ),
1179 ));
1180 }
1181 Some(_) => {}
1182 }
1183 }
1184 }
1185 }
1186 None => {}
1187 }
1188 let params = params?;
1189 check_frame_timing(at, ¶ms, annotations, cx.report);
1190 check_frame_horizon(at, ¶ms, annotations, cx.report);
1191 Some(params)
1192}
1193
1194fn check_frame_horizon(
1199 at: &str,
1200 params: &crate::frame::FrameParams,
1201 annotations: &BTreeMap<String, Value>,
1202 report: &mut Report,
1203) {
1204 let (Some(ttl), Some(interval)) = (
1205 crate::freshness::horizon(Kind::Stream, annotations).ttl(),
1206 params.interval_ms(annotations),
1207 ) else {
1208 return;
1209 };
1210 if u128::from(interval) * 2 > ttl.as_millis() {
1211 report.push(Diagnostic::warning(
1212 "W108",
1213 at,
1214 format!(
1215 "the frame's interval, {interval} ms, is above half its `freshness.ttl_s` = {}: \
1216 its owner puts a frame at least every ttl/2",
1217 ttl.as_secs()
1218 ),
1219 ));
1220 }
1221}
1222
1223fn check_frame_timing(
1229 at: &str,
1230 params: &crate::frame::FrameParams,
1231 annotations: &BTreeMap<String, Value>,
1232 report: &mut Report,
1233) {
1234 let crate::timing::Declaration::Declared(d) =
1235 crate::timing::declaration(Kind::Stream, annotations)
1236 else {
1237 return;
1238 };
1239 let ms = |x: std::time::Duration| u64::try_from(x.as_millis()).unwrap_or(u64::MAX);
1240 if let Some(deadline) = d.deadline.map(ms) {
1241 if let Some(span) = params.span_ms()
1242 && deadline < span
1243 {
1244 report.push(Diagnostic::error(
1245 "E050",
1246 at,
1247 format!(
1248 "`timing.deadline_ms` = {deadline} is below the frame's span, {span} ms: \
1249 every frame that keeps its cadence would miss it"
1250 ),
1251 ));
1252 }
1253 let interval = params.interval_ms(annotations);
1254 for (name, db) in ¶ms.deadband {
1255 let fits =
1256 interval.is_some_and(|i| u64::from(db.max_records).saturating_mul(i) <= deadline);
1257 if !fits {
1258 report.push(Diagnostic::error(
1259 "E050",
1260 at,
1261 match interval {
1262 Some(i) => format!(
1263 "the deadband on {name:?}: {} records of {i} ms pass \
1264 `timing.deadline_ms` = {deadline}",
1265 db.max_records
1266 ),
1267 None => format!(
1268 "the deadband on {name:?} beside `timing.deadline_ms`, and no \
1269 interval stated: neither a step nor `timing.period_ms`"
1270 ),
1271 },
1272 ));
1273 }
1274 }
1275 }
1276 if d.lifespan.is_some() {
1277 report.push(Diagnostic::error(
1278 "E050",
1279 at,
1280 "`timing.lifespan_ms` on a frame resource: a lifespan reads each sample's Zenoh \
1281 timestamp, and a frame's records carry none of their own",
1282 ));
1283 }
1284}
1285
1286fn resolve_op(
1287 at: &str,
1288 spec: &ResourceSpec,
1289 kd: Option<&DefaultsBlock>,
1290 tparams: &[(&str, bool)],
1291 cx: &mut Ctx<'_>,
1292) -> Option<Body> {
1293 for (f, set) in [
1294 ("request", spec.request.is_some()),
1295 ("response", spec.response.is_some()),
1296 ] {
1297 if !set {
1298 cx.report.push(Diagnostic::error(
1299 "E015",
1300 at,
1301 format!("kind = \"operation\" requires `{f}`"),
1302 ));
1303 }
1304 }
1305 let request = resolve_type(spec.request.as_ref(), "request", at, None, cx);
1306 let response = resolve_type(spec.response.as_ref(), "response", at, None, cx);
1307 let error = resolve_type(spec.error.as_ref(), "error", at, None, cx);
1308 let summary = resolve_type(spec.summary.as_ref(), "summary", at, None, cx);
1309 let base = cx.base.clone();
1312 let replies =
1313 pick(spec.replies.as_ref(), kd, &base, |b| b.replies.as_ref()).unwrap_or(Replies::One);
1314 if spec.summary.is_some() && replies != Replies::Many {
1315 cx.report.push(Diagnostic::error(
1316 "E033",
1317 at,
1318 "`summary` without `replies = \"many\"`",
1319 ));
1320 }
1321 let idempotent = pick(spec.idempotent.as_ref(), kd, &base, |b| {
1322 b.idempotent.as_ref()
1323 })
1324 .unwrap_or(false);
1325 let serving = pick(spec.serving.as_ref(), kd, &base, |b| b.serving.as_ref())
1326 .unwrap_or(Serving::Exclusive);
1327 if serving == Serving::Replicated && !idempotent {
1328 cx.report.push(Diagnostic::error(
1329 "E018",
1330 at,
1331 "`serving = \"replicated\"` requires `idempotent = true`",
1332 ));
1333 }
1334 if let Some(req) = &request
1335 && let Some(fields) = cx.schemas.field_names(req)
1336 {
1337 let rep: Vec<&str> = tparams
1338 .iter()
1339 .map(|(n, _)| *n)
1340 .filter(|n| fields.iter().any(|f| f == n))
1341 .collect();
1342 if !rep.is_empty() {
1343 cx.report.push(Diagnostic::warning(
1344 "W102",
1345 at,
1346 format!("the request type repeats template parameter(s) {rep:?} (D21)"),
1347 ));
1348 }
1349 }
1350 let any_json = [&request, &response, &error, &summary]
1351 .into_iter()
1352 .any(|t| t.as_ref().is_some_and(TypeId::is_json));
1353 let unresolved = [
1355 (&spec.request, &request),
1356 (&spec.response, &response),
1357 (&spec.error, &error),
1358 (&spec.summary, &summary),
1359 ]
1360 .iter()
1361 .any(|(written, resolved)| written.is_some() && resolved.is_none())
1362 || request.is_none()
1363 || response.is_none();
1364 let encoding = if any_json {
1365 Some(
1366 pick(spec.encoding.as_ref(), kd, &base, |b| b.encoding.as_ref())
1367 .unwrap_or(Encoding::Json),
1368 )
1369 } else {
1370 if spec.encoding.is_some() && !unresolved {
1371 cx.report.push(Diagnostic::warning(
1372 "W103",
1373 at,
1374 "`encoding` on an operation without JSON Schema types is ignored",
1375 ));
1376 }
1377 None
1378 };
1379 Some(Body::Operation(Operation {
1380 request: request?,
1381 response: response?,
1382 error,
1383 summary,
1384 encoding,
1385 idempotent,
1386 fanout: pick(spec.fanout.as_ref(), kd, &base, |b| b.fanout.as_ref())
1387 .unwrap_or(Fanout::Forbidden),
1388 serving,
1389 replies,
1390 timeout_ms: pick(spec.timeout_ms.as_ref(), kd, &base, |b| {
1391 b.timeout_ms.as_ref()
1392 }),
1393 priority: pick(spec.priority.as_ref(), kd, &base, |b| b.priority.as_ref())
1394 .unwrap_or(Priority::InteractiveHigh),
1395 }))
1396}
1397
1398fn read_type(r: &Resource) -> (Option<&TypeId>, Option<&TypeId>) {
1400 match &r.body {
1401 Body::Data(d) => (Some(&d.type_), None),
1402 Body::Operation(o) => (Some(&o.request), Some(&o.response)),
1403 }
1404}
1405
1406fn check_shapes(file: &ContractFile, report: &mut Report) {
1410 let mut shapes: BTreeMap<(KindToken, String), &str> = BTreeMap::new();
1411 for (raw, spec) in &file.resources {
1412 let Ok(t) = Template::parse(raw) else {
1413 continue;
1414 };
1415 let token = token_of(spec.kind, spec.explicit.unwrap_or(false));
1416 let k = (token, t.shape());
1417 if let Some(first) = shapes.get(&k) {
1418 report.push(Diagnostic::error(
1419 "E021",
1420 at_res(raw),
1421 format!(
1422 "same shape {:?} as {first:?} under the `{}` token",
1423 t.shape(),
1424 token.as_str()
1425 ),
1426 ));
1427 } else {
1428 shapes.insert(k, raw);
1429 }
1430 }
1431}
1432
1433fn check_overlaps(resources: &[Resource], report: &mut Report) {
1436 for (i, x) in resources.iter().enumerate() {
1437 for y in &resources[i + 1..] {
1438 if x.token == y.token
1439 && x.template.overlaps(&y.template)
1440 && read_type(x) != read_type(y)
1441 {
1442 report.push(Diagnostic::warning(
1443 "W101",
1444 at_res(y.template.as_str()),
1445 format!(
1446 "overlaps {:?} under `{}` with a different type; a key resolves most-literal-first",
1447 x.template.as_str(),
1448 x.token.as_str()
1449 ),
1450 ));
1451 }
1452 }
1453 }
1454}
1455
1456fn resolve_requirement(role: &str, req: &a::Requirement, cx: &mut Ctx<'_>) -> Option<Requirement> {
1457 let at = format!("requires.{role}");
1458 let before = cx.report.errors().count();
1459 if !is_ident(role) {
1460 cx.report.push(Diagnostic::error(
1461 "E030",
1462 at.clone(),
1463 format!("role {role:?} is not [a-z][a-z0-9_]*"),
1464 ));
1465 }
1466 let iface = IfaceId::from_str(&req.interface);
1467 if iface.is_err() {
1468 cx.report.push(Diagnostic::error(
1469 "E030",
1470 at.clone(),
1471 format!("interface {:?} is not <name>.v<major>", req.interface),
1472 ));
1473 }
1474 let resources = req.resources.as_ref().map(|v| {
1475 let mut v = v.clone();
1476 v.sort();
1477 v.dedup();
1478 v
1479 });
1480 for r in resources.iter().flatten() {
1481 if Template::parse(r).is_err() {
1482 cx.report.push(Diagnostic::error(
1483 "E030",
1484 at.clone(),
1485 format!("resource {r:?} is not a template"),
1486 ));
1487 }
1488 }
1489 if resources.as_ref().is_some_and(Vec::is_empty) {
1490 cx.report.push(Diagnostic::error(
1491 "E030",
1492 at.clone(),
1493 "`resources = []` consumes nothing; omit it to consume everything",
1494 ));
1495 }
1496 check_annotations(&req.annotations, &at, &cx.profiles, cx.report);
1497 if cx.report.errors().count() > before {
1498 return None;
1499 }
1500 Some(Requirement {
1501 interface: iface.ok()?,
1502 resources,
1503 cardinality: req.cardinality.unwrap_or(RequireCardinality::One),
1504 optional: req.optional,
1505 doc: req.doc.clone(),
1506 annotations: req.annotations.clone(),
1507 })
1508}
1509
1510#[must_use]
1516pub fn check_set(contracts: &[&Contract]) -> Report {
1517 let mut report = Report::default();
1518 let mut by_id: BTreeMap<String, &Contract> = BTreeMap::new();
1519 for c in contracts {
1520 match by_id.entry(c.iface.to_string()) {
1521 std::collections::btree_map::Entry::Occupied(e) => {
1522 report.push(Diagnostic::error(
1523 "E036",
1524 "interface",
1525 format!("{} is declared twice", e.key()),
1526 ));
1527 }
1528 std::collections::btree_map::Entry::Vacant(e) => {
1529 e.insert(c);
1530 }
1531 }
1532 }
1533 for c in contracts {
1534 for (role, req) in &c.requires {
1535 let Some(target) = by_id.get(&req.interface.to_string()) else {
1536 continue;
1537 };
1538 for r in req.resources.iter().flatten() {
1539 if !target.resources.iter().any(|x| x.template.as_str() == r) {
1540 report.push(Diagnostic::error(
1541 "E035",
1542 format!("{}: requires.{role}", c.iface),
1543 format!("{} declares no resource {r:?}", req.interface),
1544 ));
1545 }
1546 }
1547 }
1548 }
1549 report
1550}
1551
1552#[cfg(test)]
1553mod tests {
1554 use super::*;
1555
1556 fn codes(src: &str) -> Vec<&'static str> {
1557 load_str(src, Path::new("."), None).report.codes()
1558 }
1559
1560 const HEAD: &str = "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n";
1561
1562 #[test]
1565 fn a_later_major_reads_its_own_vocabulary() {
1566 let src = |major: u32| {
1567 format!(
1568 "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\nuses = [\"telemetry.v{major}\"]\n\
1569 [resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\n\
1570 annotations = {{ \"telemetry.series\" = {{ n = {{ kind = \"counter\" }} }} }}\n"
1571 )
1572 };
1573 assert_eq!(codes(&src(1)), ["W105"]);
1574 assert!(codes(&src(2)).is_empty(), "{:?}", codes(&src(2)));
1575 }
1576
1577 #[test]
1580 fn alarms_v2_reads_its_own_vocabulary() {
1581 let src = |major: u32, key: &str| {
1582 format!(
1583 "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\nuses = [\"alarms.v{major}\"]\n\
1584 [resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\n\
1585 annotations = {{ \"alarms.{key}\" = [] }}\n"
1586 )
1587 };
1588 assert_eq!(codes(&src(1, "rules")), ["W105"]);
1589 assert!(
1590 codes(&src(2, "rules")).is_empty(),
1591 "{:?}",
1592 codes(&src(2, "rules"))
1593 );
1594 assert_eq!(codes(&src(2, "severity_default")), ["W105"]);
1595 }
1596
1597 #[test]
1598 fn rates_and_durations() {
1599 assert_eq!(Rate::parse("burst(12/h)"), Some(Rate::Burst(12)));
1600 for bad in ["burst(0/h)", "burst(012/h)", "burst(/h)", "often"] {
1601 assert_eq!(Rate::parse(bad), None, "{bad}");
1602 }
1603 assert_eq!(parse_duration_s("7d"), Some(604_800));
1604 assert_eq!(parse_duration_s("0s"), None);
1605 assert_eq!(parse_duration_s("7"), None);
1606 }
1607
1608 #[test]
1609 fn defaults_expand_before_resolution() {
1610 let src = format!(
1611 "{HEAD}[defaults.stream]\npriority = \"data_low\"\n\
1612 [resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\n\
1613 [resources.\"b\"]\nkind = \"stream\"\ntype = {{ raw = \"image/jpeg\" }}\npriority = \"data_high\"\n"
1614 );
1615 let l = load_str(&src, Path::new("."), None);
1616 let c = l.contract.expect("valid");
1617 let prio = |t: &str| match &c.resource(KindToken::Stream, t).unwrap().body {
1618 Body::Data(d) => d.priority,
1619 Body::Operation(_) => unreachable!(),
1620 };
1621 assert_eq!(prio("a"), Priority::DataLow);
1622 assert_eq!(prio("b"), Priority::DataHigh);
1623 }
1624
1625 #[test]
1626 fn kind_tokens() {
1627 let src = format!(
1628 "{HEAD}[resources.\"a\"]\nkind = \"state\"\nexplicit = true\ntype = {{ raw = \"text/plain\" }}\n\
1629 [resources.\"b\"]\nkind = \"event\"\nrate = \"low\"\nretention = \"7d\"\ntype = {{ raw = \"text/plain\" }}\n"
1630 );
1631 let c = load_str(&src, Path::new("."), None)
1632 .contract
1633 .expect("valid");
1634 assert!(c.resource(KindToken::ExplicitState, "a").is_some());
1635 assert!(c.resource(KindToken::Events, "b").is_some());
1636 }
1637
1638 #[test]
1639 fn lints_have_stable_codes() {
1640 let raw = "type = { raw = \"text/plain\" }";
1641 assert_eq!(
1642 codes(&format!(
1643 "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\n{raw}\n"
1644 )),
1645 ["E011", "E013"]
1646 );
1647 assert_eq!(
1648 codes(&format!(
1649 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\n{raw}\ngate = \"feature:x\"\n"
1650 )),
1651 ["E016", "E017"]
1652 );
1653 assert_eq!(
1654 codes(&format!(
1655 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\nexplicit = true\nhistory = true\n{raw}\n"
1656 )),
1657 ["E019"]
1658 );
1659 assert_eq!(
1660 codes(&format!(
1661 "{HEAD}[resources.\"a\"]\nkind = \"event\"\n{raw}\n"
1662 )),
1663 ["E015", "E015"]
1664 );
1665 assert_eq!(
1666 codes(&format!(
1667 "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\nparams = {{ x = \"string\" }}\ncardinality = 4\n{raw}\n\
1668 [resources.\"a/{{y}}\"]\nkind = \"stream\"\nparams = {{ y = \"string\" }}\ncardinality = 4\n{raw}\n"
1669 )),
1670 ["E021"]
1671 );
1672 assert_eq!(
1673 codes(&format!(
1674 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\n{raw}\nannotations = {{ \"freshness.ttl_s\" = 1 }}\n"
1675 )),
1676 ["E020"]
1677 );
1678 assert_eq!(
1679 codes(&format!(
1680 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = \"json:Nope\"\n"
1681 )),
1682 ["E023"]
1683 );
1684 assert_eq!(codes("[interface]\nname = \"t\"\nmajor = 1\n"), ["W104"]);
1685 assert_eq!(codes("[interface]\nname = \"t\"\n"), ["E000"]);
1686 }
1687
1688 #[test]
1693 fn cardinality_unbounded_is_the_no_ceiling_value() {
1694 let src = |card: &str| {
1695 format!(
1696 "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\nparams = {{ x = \"string\" }}\n\
1697 {card}type = {{ raw = \"text/plain\" }}\n"
1698 )
1699 };
1700 let load = |card: &str| load_str(&src(card), Path::new("."), None);
1701 let named = load("cardinality = \"unbounded\"\n")
1702 .contract
1703 .expect("valid");
1704 let number = load("cardinality = 4294967295\n").contract.expect("valid");
1705 let r = named.resource(KindToken::Stream, "a/{x}").unwrap();
1706 assert_eq!(r.cardinality, Some(crate::budget::NO_CEILING));
1707 assert_eq!(
1708 crate::canonical::canonical_bytes(&named),
1709 crate::canonical::canonical_bytes(&number)
1710 );
1711 assert_eq!(
1712 crate::canonical::Fingerprint::of(&named),
1713 crate::canonical::Fingerprint::of(&number)
1714 );
1715 for bad in [
1716 "cardinality = \"Unbounded\"\n",
1717 "cardinality = \"many\"\n",
1718 "cardinality = \"4\"\n",
1719 "cardinality = -1\n",
1720 "cardinality = 4.0\n",
1721 ] {
1722 assert_eq!(codes(&src(bad)), ["E000"], "{bad}");
1723 }
1724 let at_least_one = load("cardinality = 0\n");
1725 for l in [load(""), at_least_one] {
1726 let d = &l.report.0;
1727 assert_eq!(d.len(), 1, "{}", l.report);
1728 assert_eq!(d[0].code, "E013");
1729 assert!(
1730 d[0].message.ends_with(
1731 "write a number, the most members one instance will hold, or \"unbounded\""
1732 ),
1733 "{}",
1734 d[0].message
1735 );
1736 }
1737 let untemplated = format!(
1738 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ncardinality = \"unbounded\"\n\
1739 type = {{ raw = \"text/plain\" }}\n"
1740 );
1741 assert_eq!(codes(&untemplated), ["E014"]);
1742 }
1743
1744 #[test]
1747 fn w103_waits_for_the_types() {
1748 let op = |types: &str| {
1749 codes(&format!(
1750 "{HEAD}[resources.\"a\"]\nkind = \"operation\"\n{types}\nencoding = \"cbor\"\n"
1751 ))
1752 };
1753 assert_eq!(
1754 codes(&format!(
1755 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = \"json:Nope\"\nencoding = \"cbor\"\n"
1756 )),
1757 ["E023"]
1758 );
1759 assert_eq!(
1760 codes(&format!(
1761 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"a/b\" }}\nattachment = \"json:Nope\"\nattachment_encoding = \"cbor\"\n"
1762 )),
1763 ["E023"]
1764 );
1765 assert_eq!(
1766 codes(&format!(
1767 "{HEAD}[resources.\"a\"]\nkind = \"stream\"\ntype = {{ raw = \"a/b\" }}\nattachment_encoding = \"cbor\"\n"
1768 )),
1769 ["W103"]
1770 );
1771 let raw = "{ raw = \"a/b\" }";
1772 assert_eq!(op(&format!("request = {raw}\nresponse = {raw}")), ["W103"]);
1773 assert_eq!(
1774 op(&format!(
1775 "request = {raw}\nresponse = {raw}\nerror = \"json:Nope\""
1776 )),
1777 ["E023"]
1778 );
1779 }
1780
1781 #[test]
1784 fn a_set_checks_against_the_first_declaration() {
1785 let load = |src: String| load_str(&src, Path::new("."), None).contract.unwrap();
1786 let decl = |res: &str| {
1787 load(format!(
1788 "[interface]\nname = \"d\"\nmajor = 1\nminor = 0\n\
1789 [resources.{res}]\nkind = \"stream\"\ntype = {{ raw = \"a/b\" }}\n"
1790 ))
1791 };
1792 let (first, second) = (decl("x"), decl("y"));
1793 let user = load(format!(
1794 "{HEAD}[requires.r]\ninterface = \"d.v1\"\nresources = [\"x\"]\n"
1795 ));
1796 assert_eq!(check_set(&[&first, &second, &user]).codes(), ["E036"]);
1797 assert_eq!(
1798 check_set(&[&second, &first, &user]).codes(),
1799 ["E035", "E036"]
1800 );
1801 }
1802
1803 #[test]
1804 fn same_shape_under_different_tokens_is_fine() {
1805 let raw = "type = { raw = \"text/plain\" }";
1806 let src = format!(
1807 "{HEAD}[resources.\"a/{{x}}\"]\nkind = \"stream\"\nparams = {{ x = \"string\" }}\ncardinality = 2\n{raw}\n\
1808 [resources.\"a/{{y}}\"]\nkind = \"state\"\nparams = {{ y = \"string\" }}\ncardinality = 2\n{raw}\n"
1809 );
1810 assert!(codes(&src).is_empty());
1811 }
1812}