1pub mod rules;
49pub mod state;
50
51mod messages;
52
53use alloc::format;
54use alloc::string::{String, ToString};
55use alloc::vec::Vec;
56
57use crate::message::MessageKind;
58use crate::schema;
59use crate::types::common::{
60 CommodityQuantity, ControlType, EnergyManagementRole, InstructionStatus, NumberRange,
61 ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
62};
63use crate::types::{Duration, Id, Timestamp, WireProfile, ddbc, frbc, ombc, pebc, ppbc};
64
65pub use rules::Rule;
66pub use state::{Allowance, Phase, allowed};
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
74pub struct RuleId(pub &'static str);
75
76impl RuleId {
77 #[must_use]
79 pub const fn as_str(self) -> &'static str {
80 self.0
81 }
82
83 #[must_use]
85 pub fn rule(self) -> Option<&'static Rule> {
86 Rule::find(self)
87 }
88}
89
90impl core::fmt::Display for RuleId {
91 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92 f.write_str(self.0)
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub enum Severity {
99 Error,
101 Warning,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Violation {
108 pub rule: RuleId,
110 pub severity: Severity,
112 pub path: String,
114 pub message: String,
116 pub related: Vec<Id>,
118}
119
120impl core::fmt::Display for Violation {
121 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
122 if self.path.is_empty() {
123 write!(f, "{}: {}", self.rule, self.message)
124 } else {
125 write!(f, "{} at {}: {}", self.rule, self.path, self.message)
126 }
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct Report {
133 violations: Vec<Violation>,
134}
135
136impl Report {
137 #[must_use]
139 pub const fn new() -> Self {
140 Self {
141 violations: Vec::new(),
142 }
143 }
144
145 pub fn push(&mut self, rule: RuleId, path: &str, message: impl Into<String>) {
147 let severity = rule.rule().map_or(Severity::Error, |r| r.severity);
148 self.violations.push(Violation {
149 rule,
150 severity,
151 path: path.to_string(),
152 message: message.into(),
153 related: Vec::new(),
154 });
155 }
156
157 pub fn push_related(
159 &mut self,
160 rule: RuleId,
161 path: &str,
162 message: impl Into<String>,
163 related: impl IntoIterator<Item = Id>,
164 ) {
165 self.push(rule, path, message);
166 if let Some(last) = self.violations.last_mut() {
167 last.related = related.into_iter().collect();
168 }
169 }
170
171 #[must_use]
173 pub fn violations(&self) -> &[Violation] {
174 &self.violations
175 }
176
177 pub fn errors(&self) -> impl Iterator<Item = &Violation> {
179 self.violations
180 .iter()
181 .filter(|v| v.severity == Severity::Error)
182 }
183
184 pub fn warnings(&self) -> impl Iterator<Item = &Violation> {
186 self.violations
187 .iter()
188 .filter(|v| v.severity == Severity::Warning)
189 }
190
191 #[must_use]
193 pub fn is_empty(&self) -> bool {
194 self.violations.is_empty()
195 }
196
197 #[must_use]
199 pub fn has_errors(&self) -> bool {
200 self.errors().next().is_some()
201 }
202
203 #[must_use]
205 pub fn first_error(&self) -> Option<&Violation> {
206 self.errors().next()
207 }
208
209 #[must_use]
211 pub fn contains(&self, rule: RuleId) -> bool {
212 self.violations.iter().any(|v| v.rule == rule)
213 }
214
215 pub fn fired(&self) -> impl Iterator<Item = RuleId> + '_ {
217 self.violations.iter().map(|v| v.rule)
218 }
219
220 #[must_use]
222 pub fn reception_status(&self) -> ReceptionStatusValues {
223 if self.has_errors() {
224 ReceptionStatusValues::InvalidContent
225 } else {
226 ReceptionStatusValues::Ok
227 }
228 }
229
230 #[must_use]
233 pub fn diagnostic_label(&self) -> Option<String> {
234 self.first_error().map(ToString::to_string)
235 }
236
237 pub fn extend(&mut self, other: Report) {
239 self.violations.extend(other.violations);
240 }
241}
242
243impl core::fmt::Display for Report {
244 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
245 for (i, v) in self.violations.iter().enumerate() {
246 if i > 0 {
247 writeln!(f)?;
248 }
249 write!(f, "{v}")?;
250 }
251 Ok(())
252 }
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub struct TimerState {
265 pub actuator: Id,
271 pub timer: Id,
273 pub finished_at: Timestamp,
277}
278
279#[derive(Debug, Clone, Copy, Default)]
289pub struct Context<'a> {
290 pub profile: WireProfile,
292 pub sender: Option<EnergyManagementRole>,
294 pub phase: Phase,
298 pub s2_connect: bool,
301 pub details: Option<&'a ResourceManagerDetails>,
303 pub frbc: Option<&'a frbc::SystemDescription>,
305 pub ombc: Option<&'a ombc::SystemDescription>,
307 pub ddbc: Option<&'a ddbc::SystemDescription>,
309 pub pebc_constraints: &'a [pebc::PowerConstraints],
311 pub ppbc_profiles: &'a [ppbc::PowerProfileDefinition],
313 pub instructions: &'a [Id],
315 pub instruction_messages: &'a [(Id, Id)],
318 pub instruction_statuses: &'a [(Id, InstructionStatus)],
320 pub seen_message_ids: &'a [Id],
322 pub published: &'a [(RevokableObjects, Id)],
324 pub active_modes: &'a [(Id, Id)],
327 pub timers: &'a [TimerState],
329 pub fill_level: Option<f64>,
331 pub now: Option<Timestamp>,
333 pub skew_tolerance: Duration,
335}
336
337impl<'a> Context<'a> {
338 #[must_use]
340 pub fn empty() -> Self {
341 Self {
342 skew_tolerance: Duration::from_secs(30),
343 ..Self::default()
344 }
345 }
346
347 #[must_use]
349 pub fn with_details(mut self, details: &'a ResourceManagerDetails) -> Self {
350 self.details = Some(details);
351 self
352 }
353
354 #[must_use]
356 pub fn at(mut self, now: Timestamp) -> Self {
357 self.now = Some(now);
358 self
359 }
360
361 #[must_use]
363 pub fn sent_by(mut self, sender: EnergyManagementRole) -> Self {
364 self.sender = Some(sender);
365 self
366 }
367
368 #[must_use]
370 pub fn active(mut self, control_type: ControlType) -> Self {
371 self.phase = Phase::selected(control_type);
372 self
373 }
374
375 #[must_use]
377 pub const fn in_phase(mut self, phase: Phase) -> Self {
378 self.phase = phase;
379 self
380 }
381
382 #[must_use]
384 pub const fn active_control_type(&self) -> Option<ControlType> {
385 self.phase.active_control_type()
386 }
387
388 #[must_use]
390 pub fn is_empty(&self) -> bool {
391 self.sender.is_none() && self.details.is_none() && self.phase == Phase::Connected
392 }
393
394 fn timer_finished_at(&self, actuator: &Id, timer: &Id) -> Option<Timestamp> {
395 self.timers
396 .iter()
397 .find(|t| t.actuator == *actuator && t.timer == *timer)
398 .map(|t| t.finished_at)
399 }
400
401 fn active_mode_of(&self, actuator: &Id) -> Option<Id> {
402 self.active_modes
403 .iter()
404 .find(|(a, _)| a == actuator)
405 .map(|(_, m)| *m)
406 }
407}
408
409pub trait Validate {
411 fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report);
413
414 fn validate(&self, ctx: &Context<'_>) -> Report {
416 let mut report = Report::new();
417 self.validate_at("", ctx, &mut report);
418 report
419 }
420}
421
422#[must_use]
427#[allow(clippy::format_push_string)] pub fn rules_markdown() -> String {
429 let mut out = String::from(
430 "# Rule catalogue\n\n\
431 Generated from `s2_kit::validate::rules::RULES` — do not edit.\n\n\
432 Every rule quotes the sentence it implements. An **error** is a requirement the\n\
433 standard states plainly; a **warning** is one it leaves ambiguous, silent or\n\
434 self-contradictory, and never refuses traffic. The identifier travels in the\n\
435 `diagnostic_label` of every failing `ReceptionStatus` this crate sends.\n\n",
436 );
437 let errors = rules::RULES
438 .iter()
439 .filter(|r| r.severity == Severity::Error)
440 .count();
441 out.push_str(&format!(
442 "{} rules: {} errors, {} warnings.\n\n",
443 rules::RULES.len(),
444 errors,
445 rules::RULES.len() - errors
446 ));
447 out.push_str("| Rule | Severity | Needs session | Checks | Source |\n|---|---|---|---|---|\n");
448 for rule in rules::RULES {
449 out.push_str(&format!(
450 "| `{}` | {} | {} | {} | {} |\n",
451 rule.id,
452 match rule.severity {
453 Severity::Error => "error",
454 Severity::Warning => "warning",
455 },
456 if rule.needs_context { "yes" } else { "no" },
457 rule.summary,
458 rule.source.replace('|', "\\|")
459 ));
460 }
461 out
462}
463
464pub(crate) fn child(path: &str, name: &str) -> String {
469 format!("{path}/{name}")
470}
471
472pub(crate) fn index(path: &str, i: usize) -> String {
473 format!("{path}/{i}")
474}
475
476pub(crate) fn check_finite(value: f64, path: &str, out: &mut Report) {
478 if !value.is_finite() {
479 out.push(
480 rules::NON_FINITE,
481 path,
482 format!("{value} cannot be represented in JSON"),
483 );
484 }
485}
486
487pub(crate) fn check_interpolated(range: NumberRange, path: &str, out: &mut Report) {
496 check_finite(range.start_of_range, &child(path, "start_of_range"), out);
497 check_finite(range.end_of_range, &child(path, "end_of_range"), out);
498}
499
500pub(crate) fn check_range(range: NumberRange, path: &str, out: &mut Report) {
502 check_finite(range.start_of_range, &child(path, "start_of_range"), out);
503 check_finite(range.end_of_range, &child(path, "end_of_range"), out);
504 if range.is_finite() && range.start_of_range > range.end_of_range {
505 out.push(
506 rules::RANGE_ORDER,
507 path,
508 format!(
509 "start_of_range {} is after end_of_range {}",
510 range.start_of_range, range.end_of_range
511 ),
512 );
513 }
514}
515
516pub(crate) fn check_band(range: NumberRange, path: &str, out: &mut Report) {
518 check_finite(range.start_of_range, &child(path, "start_of_range"), out);
519 check_finite(range.end_of_range, &child(path, "end_of_range"), out);
520 if range.is_finite() && range.start_of_range >= range.end_of_range {
521 out.push(
522 rules::RANGE_STRICT_ORDER,
523 path,
524 format!(
525 "fill level band {}..{} is empty; the start must be below the end",
526 range.start_of_range, range.end_of_range
527 ),
528 );
529 }
530}
531
532pub(crate) fn check_factor(factor: f64, path: &str, out: &mut Report) {
533 check_finite(factor, path, out);
534 if factor.is_finite() && !(0.0..=1.0).contains(&factor) {
535 out.push(
536 rules::FACTOR_RANGE,
537 path,
538 format!("operation mode factor {factor} is outside [0, 1]"),
539 );
540 }
541}
542
543pub(crate) fn check_array(
545 type_name: &str,
546 property: &str,
547 len: usize,
548 path: &str,
549 out: &mut Report,
550) {
551 let Some(bounds) = schema::type_spec(type_name)
552 .and_then(|t| t.property(property))
553 .and_then(|p| p.kind.bounds())
554 else {
555 return;
556 };
557 if !bounds.accepts(len as u64) {
558 out.push(
559 rules::ARRAY_BOUNDS,
560 &child(path, property),
561 format!(
562 "{len} items, but the schema allows {}..={}",
563 bounds.min.unwrap_or(0),
564 bounds
565 .max
566 .map_or_else(|| "unbounded".to_string(), |m| m.to_string())
567 ),
568 );
569 }
570}
571
572pub(crate) fn check_unique_quantities<I>(quantities: I, path: &str, out: &mut Report)
574where
575 I: IntoIterator<Item = CommodityQuantity>,
576{
577 let mut seen: Vec<CommodityQuantity> = Vec::new();
578 let mut per_phase = false;
579 let mut symmetric = false;
580 for q in quantities {
581 if seen.contains(&q) {
582 out.push(
583 rules::ONE_VALUE_PER_QUANTITY,
584 path,
585 format!("{} appears more than once", q.as_str()),
586 );
587 } else {
588 seen.push(q);
589 }
590 per_phase |= q.is_per_phase_electric();
591 symmetric |= q == CommodityQuantity::ElectricPower3PhaseSymmetric;
592 }
593 if per_phase && symmetric {
594 out.push(
595 rules::PHASE_EXCLUSIVITY,
596 path,
597 "per-phase and three-phase-symmetric electric power are both present; \
598 a CEM cannot tell whether to add them or choose between them",
599 );
600 }
601}
602
603pub(crate) fn check_unique_ids<'i, I>(ids: I, scope: &str, path: &str, out: &mut Report)
605where
606 I: IntoIterator<Item = &'i Id>,
607{
608 let mut seen: Vec<&Id> = Vec::new();
609 for id in ids {
610 if seen.contains(&id) {
611 out.push_related(
612 rules::DUPLICATE_ID,
613 path,
614 format!("{id} appears more than once within {scope}"),
615 [*id],
616 );
617 } else {
618 seen.push(id);
619 }
620 }
621}
622
623pub(crate) fn check_contiguous(
625 ranges: &[NumberRange],
626 rule: RuleId,
627 what: &str,
628 path: &str,
629 out: &mut Report,
630) {
631 for (i, pair) in ranges.windows(2).enumerate() {
632 let [a, b] = pair else { continue };
633 if !a.is_finite() || !b.is_finite() {
634 continue;
635 }
636 let tolerance =
641 4.0 * f64::EPSILON * a.end_of_range.abs().max(b.start_of_range.abs()).max(1.0);
642 if (a.end_of_range - b.start_of_range).abs() > tolerance {
643 out.push(
644 rule,
645 &index(path, i + 1),
646 format!(
647 "{what} are not contiguous: the previous band ends at {} and this one starts at {}",
648 a.end_of_range, b.start_of_range
649 ),
650 );
651 }
652 }
653}
654
655pub(crate) fn check_percentiles(
657 bands: &[(&'static str, Option<f64>); 7],
658 path: &str,
659 out: &mut Report,
660) {
661 let mut previous: Option<(&str, f64)> = None;
662 for (name, value) in bands {
663 let Some(value) = *value else { continue };
664 check_finite(value, &child(path, name), out);
665 if let Some((previous_name, previous_value)) = previous
666 && value.is_finite()
667 && previous_value.is_finite()
668 && value < previous_value
669 {
670 out.push(
671 rules::PERCENTILE_ORDER,
672 &child(path, name),
673 format!("{name} ({value}) is below {previous_name} ({previous_value})"),
674 );
675 }
676 if value.is_finite() {
677 previous = Some((name, value));
678 }
679 }
680}
681
682pub(crate) const SCHEDULING_HORIZON: Duration = Duration::from_secs(365 * 86_400);
688
689pub(crate) fn check_observed(at: Timestamp, path: &str, ctx: &Context<'_>, out: &mut Report) {
701 let Some(now) = ctx.now else { return };
702 let ahead = at.saturating_duration_since(now);
703 if ahead > ctx.skew_tolerance {
704 out.push(
705 rules::TIMESTAMP_SKEW,
706 path,
707 format!(
708 "{at} says something has already happened, but it is {} ms ahead of \
709 the local clock ({now}), which tolerates {} ms of skew",
710 ahead.as_millis(),
711 ctx.skew_tolerance.as_millis()
712 ),
713 );
714 }
715}
716
717pub(crate) fn check_scheduled(at: Timestamp, path: &str, ctx: &Context<'_>, out: &mut Report) {
719 let Some(now) = ctx.now else { return };
720 let ahead = at.saturating_duration_since(now);
721 if ahead > SCHEDULING_HORIZON {
722 out.push(
723 rules::TIMESTAMP_SKEW,
724 path,
725 format!("{at} is more than a year ahead of the local clock ({now})"),
726 );
727 }
728}
729
730pub(crate) fn check_transitions(
732 transitions: &[crate::types::common::Transition],
733 mode_ids: &[Id],
734 timer_ids: &[Id],
735 rule: RuleId,
736 path: &str,
737 out: &mut Report,
738) {
739 for (i, transition) in transitions.iter().enumerate() {
740 let at = index(path, i);
741 for (field, id) in [("from", &transition.from), ("to", &transition.to)] {
742 if !mode_ids.contains(id) {
743 out.push_related(
744 rule,
745 &child(&at, field),
746 format!("{id} is not an operation mode of this description"),
747 [*id],
748 );
749 }
750 }
751 for (field, ids) in [
752 ("start_timers", &transition.start_timers),
753 ("blocking_timers", &transition.blocking_timers),
754 ] {
755 for id in ids {
756 if !timer_ids.contains(id) {
757 out.push_related(
758 rule,
759 &child(&at, field),
760 format!("{id} is not a timer of this description"),
761 [*id],
762 );
763 }
764 }
765 }
766 if let Some(cost) = transition.transition_costs {
767 check_finite(cost, &child(&at, "transition_costs"), out);
768 }
769 }
770}
771
772pub(crate) struct ModeCheck<'a> {
775 pub actuator: Option<&'a Id>,
776 pub mode: &'a Id,
777 pub abnormal_condition: bool,
778 pub abnormal_only: bool,
779 pub transitions: &'a [crate::types::common::Transition],
780 pub timers: &'a [crate::types::common::Timer],
781}
782
783pub(crate) fn check_instruction_context(
784 check: &ModeCheck<'_>,
785 path: &str,
786 ctx: &Context<'_>,
787 out: &mut Report,
788) {
789 if check.abnormal_only && !check.abnormal_condition {
790 out.push_related(
791 rules::ABNORMAL_ONLY,
792 path,
793 format!(
794 "{} may only be used during an abnormal condition, \
795 and abnormal_condition is false",
796 check.mode
797 ),
798 [*check.mode],
799 );
800 }
801
802 let actuator = check.actuator.copied().unwrap_or(Id::NIL);
803 let Some(active) = ctx.active_mode_of(&actuator) else {
804 return;
805 };
806 if active == *check.mode {
807 return;
812 }
813
814 let Some(transition) = check
815 .transitions
816 .iter()
817 .find(|t| t.from == active && t.to == *check.mode)
818 else {
819 out.push_related(
820 rules::NO_SUCH_TRANSITION,
821 path,
822 format!("no transition is described from {active} to {}", check.mode),
823 [active, *check.mode],
824 );
825 return;
826 };
827
828 if transition.abnormal_condition_only && !check.abnormal_condition {
829 out.push_related(
830 rules::ABNORMAL_ONLY,
831 path,
832 format!(
833 "transition {} may only be used during an abnormal condition",
834 transition.id
835 ),
836 [transition.id],
837 );
838 }
839
840 if let Some(now) = ctx.now {
841 for timer_id in &transition.blocking_timers {
842 if let Some(finished_at) = ctx.timer_finished_at(&actuator, timer_id)
846 && finished_at > now
847 {
848 let label = check
849 .timers
850 .iter()
851 .find(|t| t.id == *timer_id)
852 .and_then(|t| t.diagnostic_label.as_deref())
853 .unwrap_or("timer");
854 out.push_related(
855 rules::BLOCKED_BY_TIMER,
856 path,
857 format!("{label} {timer_id} does not finish until {finished_at}"),
858 [*timer_id],
859 );
860 }
861 }
862 }
863}
864
865pub(crate) fn check_envelope(
867 kind: MessageKind,
868 message_id: Option<Id>,
869 ctx: &Context<'_>,
870 out: &mut Report,
871) {
872 if let Some(sender) = ctx.sender {
873 match state::allowed(ctx.phase, sender, kind) {
874 Allowance::Yes => {}
875 Allowance::WrongState => out.push(
876 rules::NOT_ALLOWED_IN_STATE,
877 "",
878 format!(
879 "{kind} is not allowed while the session is {}",
880 ctx.phase.label()
881 ),
882 ),
883 Allowance::WrongRole => out.push(
884 rules::NOT_ALLOWED_FOR_ROLE,
885 "",
886 format!("{kind} is not sent by a {sender:?}"),
887 ),
888 }
889 }
890
891 if ctx.s2_connect
892 && matches!(
893 kind,
894 MessageKind::Handshake | MessageKind::HandshakeResponse
895 )
896 {
897 out.push(
898 rules::HANDSHAKE_UNDER_CONNECT,
899 "",
900 "under S2 Connect the version is negotiated during session initiation, \
901 and handshake messages are redundant",
902 );
903 }
904
905 if let Some(id) = message_id
906 && ctx.seen_message_ids.contains(&id)
907 {
908 out.push_related(
909 rules::DUPLICATE_MESSAGE_ID,
910 "/message_id",
911 format!("{id} has already been used on this session"),
912 [id],
913 );
914 }
915}
916
917#[cfg(test)]
918mod tests {
919 use super::*;
920
921 #[test]
922 fn a_report_is_ok_until_an_error_is_recorded() {
923 let mut report = Report::new();
924 assert!(report.is_empty());
925 assert_eq!(report.reception_status(), ReceptionStatusValues::Ok);
926
927 report.push(rules::PHASE_EXCLUSIVITY, "/values", "mixed phases");
928 assert!(!report.is_empty());
929 assert!(!report.has_errors(), "a warning does not refuse a message");
930 assert_eq!(report.reception_status(), ReceptionStatusValues::Ok);
931 assert_eq!(report.diagnostic_label(), None);
932
933 report.push(rules::FACTOR_RANGE, "/operation_mode_factor", "1.3");
934 assert!(report.has_errors());
935 assert_eq!(
936 report.reception_status(),
937 ReceptionStatusValues::InvalidContent
938 );
939 assert_eq!(
940 report.diagnostic_label().unwrap(),
941 "S2-NUM-004 at /operation_mode_factor: 1.3"
942 );
943 }
944
945 #[test]
946 fn severity_comes_from_the_catalogue_not_the_call_site() {
947 let mut report = Report::new();
948 report.push(rules::PERCENTILE_ORDER, "", "x");
949 report.push(rules::NON_FINITE, "", "y");
950 assert_eq!(report.violations()[0].severity, Severity::Warning);
951 assert_eq!(report.violations()[1].severity, Severity::Error);
952 }
953
954 #[test]
955 fn contiguity_tolerates_arithmetic_but_not_a_gap() {
956 let third = 100.0 / 3.0;
960 let computed = 100.0 - (100.0 / 3.0) - (100.0 / 3.0);
961 let mut out = Report::new();
962 check_contiguous(
963 &[
964 NumberRange::new(0.0, third),
965 NumberRange::new(100.0 - third - computed, 100.0),
966 ],
967 rules::FRBC_ELEMENTS_CONTIGUOUS,
968 "bands",
969 "/elements",
970 &mut out,
971 );
972 assert!(out.is_empty(), "{out}");
973
974 let mut out = Report::new();
976 check_contiguous(
977 &[NumberRange::new(0.0, 50.0), NumberRange::new(50.001, 100.0)],
978 rules::FRBC_ELEMENTS_CONTIGUOUS,
979 "bands",
980 "/elements",
981 &mut out,
982 );
983 assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
984 }
985
986 #[test]
987 fn contiguity_accepts_touching_bands_and_rejects_gaps_and_overlaps() {
988 let mut out = Report::new();
989 check_contiguous(
990 &[NumberRange::new(0.0, 50.0), NumberRange::new(50.0, 100.0)],
991 rules::FRBC_ELEMENTS_CONTIGUOUS,
992 "bands",
993 "/elements",
994 &mut out,
995 );
996 assert!(out.is_empty(), "{out}");
997
998 let mut out = Report::new();
999 check_contiguous(
1000 &[NumberRange::new(0.0, 40.0), NumberRange::new(50.0, 100.0)],
1001 rules::FRBC_ELEMENTS_CONTIGUOUS,
1002 "bands",
1003 "/elements",
1004 &mut out,
1005 );
1006 assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
1007 assert_eq!(out.violations()[0].path, "/elements/1");
1008
1009 let mut out = Report::new();
1010 check_contiguous(
1011 &[NumberRange::new(0.0, 60.0), NumberRange::new(50.0, 100.0)],
1012 rules::FRBC_ELEMENTS_CONTIGUOUS,
1013 "bands",
1014 "/elements",
1015 &mut out,
1016 );
1017 assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
1018 }
1019
1020 #[test]
1021 fn array_bounds_come_from_the_generated_table() {
1022 let mut out = Report::new();
1023 check_array("PowerForecast", "elements", 0, "", &mut out);
1024 assert!(out.contains(rules::ARRAY_BOUNDS));
1025 assert!(out.violations()[0].message.contains("1..=288"));
1026
1027 let mut out = Report::new();
1028 check_array("PowerForecast", "elements", 288, "", &mut out);
1029 assert!(out.is_empty());
1030
1031 let mut out = Report::new();
1032 check_array("PowerForecast", "elements", 289, "", &mut out);
1033 assert!(out.contains(rules::ARRAY_BOUNDS));
1034 }
1035
1036 #[test]
1037 fn percentiles_must_ascend() {
1038 let mut out = Report::new();
1039 check_percentiles(
1040 &[
1041 ("lower_limit", Some(0.0)),
1042 ("lower_95", Some(1.0)),
1043 ("lower_68", None),
1044 ("expected", Some(2.0)),
1045 ("upper_68", None),
1046 ("upper_95", Some(3.0)),
1047 ("upper_limit", Some(4.0)),
1048 ],
1049 "/v",
1050 &mut out,
1051 );
1052 assert!(out.is_empty(), "{out}");
1053
1054 let mut out = Report::new();
1055 check_percentiles(
1056 &[
1057 ("lower_limit", Some(0.0)),
1058 ("lower_95", None),
1059 ("lower_68", None),
1060 ("expected", Some(2.0)),
1061 ("upper_68", Some(1.0)),
1062 ("upper_95", None),
1063 ("upper_limit", None),
1064 ],
1065 "/v",
1066 &mut out,
1067 );
1068 assert!(out.contains(rules::PERCENTILE_ORDER));
1069 assert_eq!(out.violations()[0].path, "/v/upper_68");
1070 }
1071
1072 #[test]
1073 fn skew_is_about_the_past_and_the_horizon_is_about_the_future() {
1074 use crate::types::common::{PowerMeasurement, PowerValue};
1075 use alloc::vec;
1076
1077 let now: Timestamp = "2024-01-01T12:00:00Z".parse().expect("a timestamp");
1078 let ctx = Context {
1079 now: Some(now),
1080 skew_tolerance: Duration::from_secs(30),
1081 ..Context::empty()
1082 };
1083 let measured_at = |at: &str| PowerMeasurement {
1084 message_id: Id::new_const("m1"),
1085 measurement_timestamp: at.parse().expect("a timestamp"),
1086 values: vec![PowerValue::new(CommodityQuantity::ElectricPowerL1, 1.0)],
1087 };
1088
1089 assert!(
1092 measured_at("2024-01-01T12:00:29Z")
1093 .validate(&ctx)
1094 .is_empty()
1095 );
1096 assert!(
1097 measured_at("2024-01-01T12:01:00Z")
1098 .validate(&ctx)
1099 .contains(rules::TIMESTAMP_SKEW)
1100 );
1101 assert!(
1103 measured_at("2020-01-01T00:00:00Z")
1104 .validate(&ctx)
1105 .is_empty()
1106 );
1107 let patient = Context {
1109 skew_tolerance: Duration::from_secs(3600),
1110 ..ctx
1111 };
1112 assert!(
1113 measured_at("2024-01-01T12:01:00Z")
1114 .validate(&patient)
1115 .is_empty()
1116 );
1117
1118 let mut out = Report::new();
1121 check_scheduled(
1122 "2024-06-01T00:00:00Z".parse().expect("a timestamp"),
1123 "/valid_from",
1124 &ctx,
1125 &mut out,
1126 );
1127 assert!(out.is_empty(), "five months ahead is a plan, not a fault");
1128 let mut out = Report::new();
1129 check_scheduled(
1130 "2030-01-01T00:00:00Z".parse().expect("a timestamp"),
1131 "/valid_from",
1132 &ctx,
1133 &mut out,
1134 );
1135 assert!(out.contains(rules::TIMESTAMP_SKEW));
1136 }
1137
1138 #[test]
1139 fn mixing_phase_conventions_is_reported_once() {
1140 let mut out = Report::new();
1141 check_unique_quantities(
1142 [
1143 CommodityQuantity::ElectricPowerL1,
1144 CommodityQuantity::ElectricPower3PhaseSymmetric,
1145 ],
1146 "/values",
1147 &mut out,
1148 );
1149 assert!(out.contains(rules::PHASE_EXCLUSIVITY));
1150 assert!(!out.has_errors(), "E12 is undocumented, so it is a warning");
1151 }
1152
1153 #[test]
1154 fn a_repeated_quantity_is_an_error() {
1155 let mut out = Report::new();
1156 check_unique_quantities(
1157 [
1158 CommodityQuantity::ElectricPowerL1,
1159 CommodityQuantity::ElectricPowerL1,
1160 ],
1161 "/values",
1162 &mut out,
1163 );
1164 assert!(out.contains(rules::ONE_VALUE_PER_QUANTITY));
1165 assert!(out.has_errors());
1166 }
1167}