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, 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 active_control_type: Option<ControlType>,
296 pub s2_connect: bool,
299 pub details: Option<&'a ResourceManagerDetails>,
301 pub frbc: Option<&'a frbc::SystemDescription>,
303 pub ombc: Option<&'a ombc::SystemDescription>,
305 pub ddbc: Option<&'a ddbc::SystemDescription>,
307 pub pebc_constraints: &'a [pebc::PowerConstraints],
309 pub ppbc_profiles: &'a [ppbc::PowerProfileDefinition],
311 pub instructions: &'a [Id],
313 pub instruction_statuses: &'a [(Id, InstructionStatus)],
315 pub seen_message_ids: &'a [Id],
317 pub published: &'a [(RevokableObjects, Id)],
319 pub active_modes: &'a [(Id, Id)],
322 pub timers: &'a [TimerState],
324 pub fill_level: Option<f64>,
326 pub now: Option<Timestamp>,
328 pub skew_tolerance: Duration,
330}
331
332impl<'a> Context<'a> {
333 #[must_use]
335 pub fn empty() -> Self {
336 Self {
337 skew_tolerance: Duration::from_secs(30),
338 ..Self::default()
339 }
340 }
341
342 #[must_use]
344 pub fn with_details(mut self, details: &'a ResourceManagerDetails) -> Self {
345 self.details = Some(details);
346 self
347 }
348
349 #[must_use]
351 pub fn at(mut self, now: Timestamp) -> Self {
352 self.now = Some(now);
353 self
354 }
355
356 #[must_use]
358 pub fn sent_by(mut self, sender: EnergyManagementRole) -> Self {
359 self.sender = Some(sender);
360 self
361 }
362
363 #[must_use]
365 pub fn active(mut self, control_type: ControlType) -> Self {
366 self.active_control_type = Some(control_type);
367 self
368 }
369
370 #[must_use]
372 pub fn is_empty(&self) -> bool {
373 self.sender.is_none() && self.details.is_none() && self.active_control_type.is_none()
374 }
375
376 fn timer_finished_at(&self, actuator: &Id, timer: &Id) -> Option<Timestamp> {
377 self.timers
378 .iter()
379 .find(|t| t.actuator == *actuator && t.timer == *timer)
380 .map(|t| t.finished_at)
381 }
382
383 fn active_mode_of(&self, actuator: &Id) -> Option<Id> {
384 self.active_modes
385 .iter()
386 .find(|(a, _)| a == actuator)
387 .map(|(_, m)| *m)
388 }
389}
390
391pub trait Validate {
393 fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report);
395
396 fn validate(&self, ctx: &Context<'_>) -> Report {
398 let mut report = Report::new();
399 self.validate_at("", ctx, &mut report);
400 report
401 }
402}
403
404#[must_use]
409#[allow(clippy::format_push_string)] pub fn rules_markdown() -> String {
411 let mut out = String::from(
412 "# Rule catalogue\n\n\
413 Generated from `s2_kit::validate::rules::RULES` — do not edit.\n\n\
414 Every rule quotes the sentence it implements. An **error** is a requirement the\n\
415 standard states plainly; a **warning** is one it leaves ambiguous, silent or\n\
416 self-contradictory, and never refuses traffic. The identifier travels in the\n\
417 `diagnostic_label` of every failing `ReceptionStatus` this crate sends.\n\n",
418 );
419 let errors = rules::RULES
420 .iter()
421 .filter(|r| r.severity == Severity::Error)
422 .count();
423 out.push_str(&format!(
424 "{} rules: {} errors, {} warnings.\n\n",
425 rules::RULES.len(),
426 errors,
427 rules::RULES.len() - errors
428 ));
429 out.push_str("| Rule | Severity | Needs session | Checks | Source |\n|---|---|---|---|---|\n");
430 for rule in rules::RULES {
431 out.push_str(&format!(
432 "| `{}` | {} | {} | {} | {} |\n",
433 rule.id,
434 match rule.severity {
435 Severity::Error => "error",
436 Severity::Warning => "warning",
437 },
438 if rule.needs_context { "yes" } else { "no" },
439 rule.summary,
440 rule.source.replace('|', "\\|")
441 ));
442 }
443 out
444}
445
446pub(crate) fn child(path: &str, name: &str) -> String {
451 format!("{path}/{name}")
452}
453
454pub(crate) fn index(path: &str, i: usize) -> String {
455 format!("{path}/{i}")
456}
457
458pub(crate) fn check_finite(value: f64, path: &str, out: &mut Report) {
460 if !value.is_finite() {
461 out.push(
462 rules::NON_FINITE,
463 path,
464 format!("{value} cannot be represented in JSON"),
465 );
466 }
467}
468
469pub(crate) fn check_interpolated(range: NumberRange, path: &str, out: &mut Report) {
478 check_finite(range.start_of_range, &child(path, "start_of_range"), out);
479 check_finite(range.end_of_range, &child(path, "end_of_range"), out);
480}
481
482pub(crate) fn check_range(range: NumberRange, path: &str, out: &mut Report) {
484 check_finite(range.start_of_range, &child(path, "start_of_range"), out);
485 check_finite(range.end_of_range, &child(path, "end_of_range"), out);
486 if range.is_finite() && range.start_of_range > range.end_of_range {
487 out.push(
488 rules::RANGE_ORDER,
489 path,
490 format!(
491 "start_of_range {} is after end_of_range {}",
492 range.start_of_range, range.end_of_range
493 ),
494 );
495 }
496}
497
498pub(crate) fn check_band(range: NumberRange, path: &str, out: &mut Report) {
500 check_finite(range.start_of_range, &child(path, "start_of_range"), out);
501 check_finite(range.end_of_range, &child(path, "end_of_range"), out);
502 if range.is_finite() && range.start_of_range >= range.end_of_range {
503 out.push(
504 rules::RANGE_STRICT_ORDER,
505 path,
506 format!(
507 "fill level band {}..{} is empty; the start must be below the end",
508 range.start_of_range, range.end_of_range
509 ),
510 );
511 }
512}
513
514pub(crate) fn check_factor(factor: f64, path: &str, out: &mut Report) {
515 check_finite(factor, path, out);
516 if factor.is_finite() && !(0.0..=1.0).contains(&factor) {
517 out.push(
518 rules::FACTOR_RANGE,
519 path,
520 format!("operation mode factor {factor} is outside [0, 1]"),
521 );
522 }
523}
524
525pub(crate) fn check_array(
527 type_name: &str,
528 property: &str,
529 len: usize,
530 path: &str,
531 out: &mut Report,
532) {
533 let Some(bounds) = schema::type_spec(type_name)
534 .and_then(|t| t.property(property))
535 .and_then(|p| p.kind.bounds())
536 else {
537 return;
538 };
539 if !bounds.accepts(len as u64) {
540 out.push(
541 rules::ARRAY_BOUNDS,
542 &child(path, property),
543 format!(
544 "{len} items, but the schema allows {}..={}",
545 bounds.min.unwrap_or(0),
546 bounds
547 .max
548 .map_or_else(|| "unbounded".to_string(), |m| m.to_string())
549 ),
550 );
551 }
552}
553
554pub(crate) fn check_unique_quantities<I>(quantities: I, path: &str, out: &mut Report)
556where
557 I: IntoIterator<Item = CommodityQuantity>,
558{
559 let mut seen: Vec<CommodityQuantity> = Vec::new();
560 let mut per_phase = false;
561 let mut symmetric = false;
562 for q in quantities {
563 if seen.contains(&q) {
564 out.push(
565 rules::ONE_VALUE_PER_QUANTITY,
566 path,
567 format!("{q:?} appears more than once"),
568 );
569 } else {
570 seen.push(q);
571 }
572 per_phase |= q.is_per_phase_electric();
573 symmetric |= q == CommodityQuantity::ElectricPower3PhaseSymmetric;
574 }
575 if per_phase && symmetric {
576 out.push(
577 rules::PHASE_EXCLUSIVITY,
578 path,
579 "per-phase and three-phase-symmetric electric power are both present; \
580 a CEM cannot tell whether to add them or choose between them",
581 );
582 }
583}
584
585pub(crate) fn check_unique_ids<'i, I>(ids: I, scope: &str, path: &str, out: &mut Report)
587where
588 I: IntoIterator<Item = &'i Id>,
589{
590 let mut seen: Vec<&Id> = Vec::new();
591 for id in ids {
592 if seen.contains(&id) {
593 out.push_related(
594 rules::DUPLICATE_ID,
595 path,
596 format!("{id} appears more than once within {scope}"),
597 [*id],
598 );
599 } else {
600 seen.push(id);
601 }
602 }
603}
604
605pub(crate) fn check_contiguous(
607 ranges: &[NumberRange],
608 rule: RuleId,
609 what: &str,
610 path: &str,
611 out: &mut Report,
612) {
613 for (i, pair) in ranges.windows(2).enumerate() {
614 let [a, b] = pair else { continue };
615 if !a.is_finite() || !b.is_finite() {
616 continue;
617 }
618 let tolerance =
623 4.0 * f64::EPSILON * a.end_of_range.abs().max(b.start_of_range.abs()).max(1.0);
624 if (a.end_of_range - b.start_of_range).abs() > tolerance {
625 out.push(
626 rule,
627 &index(path, i + 1),
628 format!(
629 "{what} are not contiguous: the previous band ends at {} and this one starts at {}",
630 a.end_of_range, b.start_of_range
631 ),
632 );
633 }
634 }
635}
636
637pub(crate) fn check_percentiles(
639 bands: &[(&'static str, Option<f64>); 7],
640 path: &str,
641 out: &mut Report,
642) {
643 let mut previous: Option<(&str, f64)> = None;
644 for (name, value) in bands {
645 let Some(value) = *value else { continue };
646 check_finite(value, &child(path, name), out);
647 if let Some((previous_name, previous_value)) = previous
648 && value.is_finite()
649 && previous_value.is_finite()
650 && value < previous_value
651 {
652 out.push(
653 rules::PERCENTILE_ORDER,
654 &child(path, name),
655 format!("{name} ({value}) is below {previous_name} ({previous_value})"),
656 );
657 }
658 if value.is_finite() {
659 previous = Some((name, value));
660 }
661 }
662}
663
664pub(crate) const SCHEDULING_HORIZON: Duration = Duration::from_secs(365 * 86_400);
670
671pub(crate) fn check_observed(at: Timestamp, path: &str, ctx: &Context<'_>, out: &mut Report) {
683 let Some(now) = ctx.now else { return };
684 let ahead = at.saturating_duration_since(now);
685 if ahead > ctx.skew_tolerance {
686 out.push(
687 rules::TIMESTAMP_SKEW,
688 path,
689 format!(
690 "{at} says something has already happened, but it is {} ms ahead of the local clock ({now}), which tolerates {} ms of skew",
691 ahead.as_millis(),
692 ctx.skew_tolerance.as_millis()
693 ),
694 );
695 }
696}
697
698pub(crate) fn check_scheduled(at: Timestamp, path: &str, ctx: &Context<'_>, out: &mut Report) {
700 let Some(now) = ctx.now else { return };
701 let ahead = at.saturating_duration_since(now);
702 if ahead > SCHEDULING_HORIZON {
703 out.push(
704 rules::TIMESTAMP_SKEW,
705 path,
706 format!("{at} is more than a year ahead of the local clock ({now})"),
707 );
708 }
709}
710
711pub(crate) fn check_transitions(
713 transitions: &[crate::types::common::Transition],
714 mode_ids: &[Id],
715 timer_ids: &[Id],
716 rule: RuleId,
717 path: &str,
718 out: &mut Report,
719) {
720 for (i, transition) in transitions.iter().enumerate() {
721 let at = index(path, i);
722 for (field, id) in [("from", &transition.from), ("to", &transition.to)] {
723 if !mode_ids.contains(id) {
724 out.push_related(
725 rule,
726 &child(&at, field),
727 format!("{id} is not an operation mode of this description"),
728 [*id],
729 );
730 }
731 }
732 for (field, ids) in [
733 ("start_timers", &transition.start_timers),
734 ("blocking_timers", &transition.blocking_timers),
735 ] {
736 for id in ids {
737 if !timer_ids.contains(id) {
738 out.push_related(
739 rule,
740 &child(&at, field),
741 format!("{id} is not a timer of this description"),
742 [*id],
743 );
744 }
745 }
746 }
747 if let Some(cost) = transition.transition_costs {
748 check_finite(cost, &child(&at, "transition_costs"), out);
749 }
750 }
751}
752
753pub(crate) struct ModeCheck<'a> {
756 pub actuator: Option<&'a Id>,
757 pub mode: &'a Id,
758 pub abnormal_condition: bool,
759 pub abnormal_only: bool,
760 pub transitions: &'a [crate::types::common::Transition],
761 pub timers: &'a [crate::types::common::Timer],
762}
763
764pub(crate) fn check_instruction_context(
765 check: &ModeCheck<'_>,
766 path: &str,
767 ctx: &Context<'_>,
768 out: &mut Report,
769) {
770 if check.abnormal_only && !check.abnormal_condition {
771 out.push_related(
772 rules::ABNORMAL_ONLY,
773 path,
774 format!(
775 "{} may only be used during an abnormal condition, \
776 and abnormal_condition is false",
777 check.mode
778 ),
779 [*check.mode],
780 );
781 }
782
783 let actuator = check.actuator.copied().unwrap_or(Id::NIL);
784 let Some(active) = ctx.active_mode_of(&actuator) else {
785 return;
786 };
787 if active == *check.mode {
788 return;
793 }
794
795 let Some(transition) = check
796 .transitions
797 .iter()
798 .find(|t| t.from == active && t.to == *check.mode)
799 else {
800 out.push_related(
801 rules::NO_SUCH_TRANSITION,
802 path,
803 format!("no transition is described from {active} to {}", check.mode),
804 [active, *check.mode],
805 );
806 return;
807 };
808
809 if transition.abnormal_condition_only && !check.abnormal_condition {
810 out.push_related(
811 rules::ABNORMAL_ONLY,
812 path,
813 format!(
814 "transition {} may only be used during an abnormal condition",
815 transition.id
816 ),
817 [transition.id],
818 );
819 }
820
821 if let Some(now) = ctx.now {
822 for timer_id in &transition.blocking_timers {
823 if let Some(finished_at) = ctx.timer_finished_at(&actuator, timer_id)
827 && finished_at > now
828 {
829 let label = check
830 .timers
831 .iter()
832 .find(|t| t.id == *timer_id)
833 .and_then(|t| t.diagnostic_label.as_deref())
834 .unwrap_or("timer");
835 out.push_related(
836 rules::BLOCKED_BY_TIMER,
837 path,
838 format!("{label} {timer_id} does not finish until {finished_at}"),
839 [*timer_id],
840 );
841 }
842 }
843 }
844}
845
846pub(crate) fn check_envelope(
848 kind: MessageKind,
849 message_id: Option<Id>,
850 ctx: &Context<'_>,
851 out: &mut Report,
852) {
853 if let Some(sender) = ctx.sender {
854 match state::allowed(ctx.active_control_type, sender, kind) {
855 Allowance::Yes => {}
856 Allowance::WrongState => out.push(
857 rules::NOT_ALLOWED_IN_STATE,
858 "",
859 format!(
860 "{kind} is not allowed while the active control type is {}",
861 ctx.active_control_type
862 .map_or("none", |c| c.abbreviation().unwrap_or("none"))
863 ),
864 ),
865 Allowance::WrongRole => out.push(
866 rules::NOT_ALLOWED_FOR_ROLE,
867 "",
868 format!("{kind} is not sent by a {sender:?}"),
869 ),
870 }
871 }
872
873 if ctx.s2_connect
874 && matches!(
875 kind,
876 MessageKind::Handshake | MessageKind::HandshakeResponse
877 )
878 {
879 out.push(
880 rules::HANDSHAKE_UNDER_CONNECT,
881 "",
882 "under S2 Connect the version is negotiated during session initiation, \
883 and handshake messages are redundant",
884 );
885 }
886
887 if let Some(id) = message_id
888 && ctx.seen_message_ids.contains(&id)
889 {
890 out.push_related(
891 rules::DUPLICATE_MESSAGE_ID,
892 "/message_id",
893 format!("{id} has already been used on this session"),
894 [id],
895 );
896 }
897}
898
899#[cfg(test)]
900mod tests {
901 use super::*;
902
903 #[test]
904 fn a_report_is_ok_until_an_error_is_recorded() {
905 let mut report = Report::new();
906 assert!(report.is_empty());
907 assert_eq!(report.reception_status(), ReceptionStatusValues::Ok);
908
909 report.push(rules::PHASE_EXCLUSIVITY, "/values", "mixed phases");
910 assert!(!report.is_empty());
911 assert!(!report.has_errors(), "a warning does not refuse a message");
912 assert_eq!(report.reception_status(), ReceptionStatusValues::Ok);
913 assert_eq!(report.diagnostic_label(), None);
914
915 report.push(rules::FACTOR_RANGE, "/operation_mode_factor", "1.3");
916 assert!(report.has_errors());
917 assert_eq!(
918 report.reception_status(),
919 ReceptionStatusValues::InvalidContent
920 );
921 assert_eq!(
922 report.diagnostic_label().unwrap(),
923 "S2-NUM-004 at /operation_mode_factor: 1.3"
924 );
925 }
926
927 #[test]
928 fn severity_comes_from_the_catalogue_not_the_call_site() {
929 let mut report = Report::new();
930 report.push(rules::PERCENTILE_ORDER, "", "x");
931 report.push(rules::NON_FINITE, "", "y");
932 assert_eq!(report.violations()[0].severity, Severity::Warning);
933 assert_eq!(report.violations()[1].severity, Severity::Error);
934 }
935
936 #[test]
937 fn contiguity_tolerates_arithmetic_but_not_a_gap() {
938 let third = 100.0 / 3.0;
942 let computed = 100.0 - (100.0 / 3.0) - (100.0 / 3.0);
943 let mut out = Report::new();
944 check_contiguous(
945 &[
946 NumberRange::new(0.0, third),
947 NumberRange::new(100.0 - third - computed, 100.0),
948 ],
949 rules::FRBC_ELEMENTS_CONTIGUOUS,
950 "bands",
951 "/elements",
952 &mut out,
953 );
954 assert!(out.is_empty(), "{out}");
955
956 let mut out = Report::new();
958 check_contiguous(
959 &[NumberRange::new(0.0, 50.0), NumberRange::new(50.001, 100.0)],
960 rules::FRBC_ELEMENTS_CONTIGUOUS,
961 "bands",
962 "/elements",
963 &mut out,
964 );
965 assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
966 }
967
968 #[test]
969 fn contiguity_accepts_touching_bands_and_rejects_gaps_and_overlaps() {
970 let mut out = Report::new();
971 check_contiguous(
972 &[NumberRange::new(0.0, 50.0), NumberRange::new(50.0, 100.0)],
973 rules::FRBC_ELEMENTS_CONTIGUOUS,
974 "bands",
975 "/elements",
976 &mut out,
977 );
978 assert!(out.is_empty(), "{out}");
979
980 let mut out = Report::new();
981 check_contiguous(
982 &[NumberRange::new(0.0, 40.0), NumberRange::new(50.0, 100.0)],
983 rules::FRBC_ELEMENTS_CONTIGUOUS,
984 "bands",
985 "/elements",
986 &mut out,
987 );
988 assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
989 assert_eq!(out.violations()[0].path, "/elements/1");
990
991 let mut out = Report::new();
992 check_contiguous(
993 &[NumberRange::new(0.0, 60.0), NumberRange::new(50.0, 100.0)],
994 rules::FRBC_ELEMENTS_CONTIGUOUS,
995 "bands",
996 "/elements",
997 &mut out,
998 );
999 assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
1000 }
1001
1002 #[test]
1003 fn array_bounds_come_from_the_generated_table() {
1004 let mut out = Report::new();
1005 check_array("PowerForecast", "elements", 0, "", &mut out);
1006 assert!(out.contains(rules::ARRAY_BOUNDS));
1007 assert!(out.violations()[0].message.contains("1..=288"));
1008
1009 let mut out = Report::new();
1010 check_array("PowerForecast", "elements", 288, "", &mut out);
1011 assert!(out.is_empty());
1012
1013 let mut out = Report::new();
1014 check_array("PowerForecast", "elements", 289, "", &mut out);
1015 assert!(out.contains(rules::ARRAY_BOUNDS));
1016 }
1017
1018 #[test]
1019 fn percentiles_must_ascend() {
1020 let mut out = Report::new();
1021 check_percentiles(
1022 &[
1023 ("lower_limit", Some(0.0)),
1024 ("lower_95", Some(1.0)),
1025 ("lower_68", None),
1026 ("expected", Some(2.0)),
1027 ("upper_68", None),
1028 ("upper_95", Some(3.0)),
1029 ("upper_limit", Some(4.0)),
1030 ],
1031 "/v",
1032 &mut out,
1033 );
1034 assert!(out.is_empty(), "{out}");
1035
1036 let mut out = Report::new();
1037 check_percentiles(
1038 &[
1039 ("lower_limit", Some(0.0)),
1040 ("lower_95", None),
1041 ("lower_68", None),
1042 ("expected", Some(2.0)),
1043 ("upper_68", Some(1.0)),
1044 ("upper_95", None),
1045 ("upper_limit", None),
1046 ],
1047 "/v",
1048 &mut out,
1049 );
1050 assert!(out.contains(rules::PERCENTILE_ORDER));
1051 assert_eq!(out.violations()[0].path, "/v/upper_68");
1052 }
1053
1054 #[test]
1055 fn skew_is_about_the_past_and_the_horizon_is_about_the_future() {
1056 use crate::types::common::{PowerMeasurement, PowerValue};
1057 use alloc::vec;
1058
1059 let now: Timestamp = "2024-01-01T12:00:00Z".parse().expect("a timestamp");
1060 let ctx = Context {
1061 now: Some(now),
1062 skew_tolerance: Duration::from_secs(30),
1063 ..Context::empty()
1064 };
1065 let measured_at = |at: &str| PowerMeasurement {
1066 message_id: Id::new_const("m1"),
1067 measurement_timestamp: at.parse().expect("a timestamp"),
1068 values: vec![PowerValue::new(CommodityQuantity::ElectricPowerL1, 1.0)],
1069 };
1070
1071 assert!(
1074 measured_at("2024-01-01T12:00:29Z")
1075 .validate(&ctx)
1076 .is_empty()
1077 );
1078 assert!(
1079 measured_at("2024-01-01T12:01:00Z")
1080 .validate(&ctx)
1081 .contains(rules::TIMESTAMP_SKEW)
1082 );
1083 assert!(
1085 measured_at("2020-01-01T00:00:00Z")
1086 .validate(&ctx)
1087 .is_empty()
1088 );
1089 let patient = Context {
1091 skew_tolerance: Duration::from_secs(3600),
1092 ..ctx
1093 };
1094 assert!(
1095 measured_at("2024-01-01T12:01:00Z")
1096 .validate(&patient)
1097 .is_empty()
1098 );
1099
1100 let mut out = Report::new();
1103 check_scheduled(
1104 "2024-06-01T00:00:00Z".parse().expect("a timestamp"),
1105 "/valid_from",
1106 &ctx,
1107 &mut out,
1108 );
1109 assert!(out.is_empty(), "five months ahead is a plan, not a fault");
1110 let mut out = Report::new();
1111 check_scheduled(
1112 "2030-01-01T00:00:00Z".parse().expect("a timestamp"),
1113 "/valid_from",
1114 &ctx,
1115 &mut out,
1116 );
1117 assert!(out.contains(rules::TIMESTAMP_SKEW));
1118 }
1119
1120 #[test]
1121 fn mixing_phase_conventions_is_reported_once() {
1122 let mut out = Report::new();
1123 check_unique_quantities(
1124 [
1125 CommodityQuantity::ElectricPowerL1,
1126 CommodityQuantity::ElectricPower3PhaseSymmetric,
1127 ],
1128 "/values",
1129 &mut out,
1130 );
1131 assert!(out.contains(rules::PHASE_EXCLUSIVITY));
1132 assert!(!out.has_errors(), "E12 is undocumented, so it is a warning");
1133 }
1134
1135 #[test]
1136 fn a_repeated_quantity_is_an_error() {
1137 let mut out = Report::new();
1138 check_unique_quantities(
1139 [
1140 CommodityQuantity::ElectricPowerL1,
1141 CommodityQuantity::ElectricPowerL1,
1142 ],
1143 "/values",
1144 &mut out,
1145 );
1146 assert!(out.contains(rules::ONE_VALUE_PER_QUANTITY));
1147 assert!(out.has_errors());
1148 }
1149}