Skip to main content

s2_kit/validate/
mod.rs

1//! The semantic validator: everything JSON Schema cannot say.
2//!
3//! A message can satisfy the schema completely and still be wrong. An operation mode
4//! whose fill-level bands leave a gap, an envelope outside the bounds the Resource
5//! Manager published, an instruction naming an actuator that does not exist, a
6//! percentile band below the one beneath it — all of these are schema-valid, and all of
7//! them are what `INVALID_CONTENT` exists for: "Message contents is invalid (e.g.
8//! contains a non-existing ID). Somewhat equivalent to BAD_REQUEST in HTTP."
9//!
10//! # Three layers, never collapsed
11//!
12//! | Layer | Answered by | A failure becomes |
13//! |---|---|---|
14//! | Is it JSON, and does it match the schema? | [`crate::codec`] | `INVALID_DATA` / `INVALID_MESSAGE` |
15//! | Is it internally consistent? | this module, with [`Context::empty`] | `INVALID_CONTENT` |
16//! | Is it consistent with the session? | this module, with a full [`Context`] | `INVALID_CONTENT` |
17//!
18//! The types accept whatever the schema accepts — a factor of 1.3 is representable —
19//! because a proxy has to be able to carry a message it would refuse to send, and
20//! because answering `INVALID_CONTENT` requires having decoded the message first.
21//!
22//! # Severity
23//!
24//! An [`Error`](Severity::Error) is a requirement the standard states plainly. A
25//! [`Warning`](Severity::Warning) is one it leaves ambiguous — and there are more of
26//! those than anyone would like, each citing its `[s2-json #n]` issue or its `E` number
27//! as errata. Warnings never refuse traffic: another conforming
28//! implementation is entitled to read the same silence differently.
29//!
30//! ```
31//! use s2_kit::prelude::*;
32//! use s2_kit::validate::{Context, Validate, rules};
33//!
34//! let message = decode(
35//!     r#"{"message_type":"FRBC.Instruction","message_id":"m1","id":"i1",
36//!         "actuator_id":"a1","operation_mode":"om1","operation_mode_factor":1.3,
37//!         "execution_time":"2019-08-24T14:15:22Z","abnormal_condition":false}"#,
38//! )?;
39//!
40//! let report = message.validate(&Context::empty());
41//! assert!(report.has_errors());
42//! assert_eq!(report.first_error().unwrap().rule, rules::FACTOR_RANGE);
43//! // The rule identifier is what travels in the reception status we send back.
44//! assert!(report.diagnostic_label().unwrap().starts_with("S2-NUM-004"));
45//! # Ok::<(), s2_kit::DecodeError>(())
46//! ```
47
48pub 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/// A stable rule identifier, such as `S2-FRBC-004`.
69///
70/// Identifiers never change meaning. They are printed in the
71/// `diagnostic_label` of every failing reception status this crate sends, and listed in
72/// the published [rule catalogue](https://hupe1980.github.io/s2-kit/reference/rules/).
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
74pub struct RuleId(pub &'static str);
75
76impl RuleId {
77    /// The identifier as a string.
78    #[must_use]
79    pub const fn as_str(self) -> &'static str {
80        self.0
81    }
82
83    /// The catalogue entry, if this is a known rule.
84    #[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/// Whether breaking a rule makes a message invalid, or merely suspect.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub enum Severity {
99    /// The standard states the requirement plainly.
100    Error,
101    /// The standard is ambiguous, silent or self-contradictory here.
102    Warning,
103}
104
105/// One thing that is wrong with a message.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Violation {
108    /// Which rule was broken.
109    pub rule: RuleId,
110    /// How seriously.
111    pub severity: Severity,
112    /// A JSON pointer to the offending value, `""` for the message as a whole.
113    pub path: String,
114    /// What is wrong, in a sentence.
115    pub message: String,
116    /// The identifiers involved, so a tool can link them.
117    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/// Everything wrong with one message.
131#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct Report {
133    violations: Vec<Violation>,
134}
135
136impl Report {
137    /// An empty report.
138    #[must_use]
139    pub const fn new() -> Self {
140        Self {
141            violations: Vec::new(),
142        }
143    }
144
145    /// Record a violation. The severity comes from the catalogue.
146    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    /// Record a violation that involves particular identifiers.
158    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    /// Every violation, errors and warnings alike.
172    #[must_use]
173    pub fn violations(&self) -> &[Violation] {
174        &self.violations
175    }
176
177    /// Only the errors.
178    pub fn errors(&self) -> impl Iterator<Item = &Violation> {
179        self.violations
180            .iter()
181            .filter(|v| v.severity == Severity::Error)
182    }
183
184    /// Only the warnings.
185    pub fn warnings(&self) -> impl Iterator<Item = &Violation> {
186        self.violations
187            .iter()
188            .filter(|v| v.severity == Severity::Warning)
189    }
190
191    /// Whether anything at all was reported.
192    #[must_use]
193    pub fn is_empty(&self) -> bool {
194        self.violations.is_empty()
195    }
196
197    /// Whether the message should be refused.
198    #[must_use]
199    pub fn has_errors(&self) -> bool {
200        self.errors().next().is_some()
201    }
202
203    /// The first error, which is the one worth telling the peer about.
204    #[must_use]
205    pub fn first_error(&self) -> Option<&Violation> {
206        self.errors().next()
207    }
208
209    /// Whether a particular rule fired.
210    #[must_use]
211    pub fn contains(&self, rule: RuleId) -> bool {
212        self.violations.iter().any(|v| v.rule == rule)
213    }
214
215    /// Every rule that fired, in order.
216    pub fn fired(&self) -> impl Iterator<Item = RuleId> + '_ {
217        self.violations.iter().map(|v| v.rule)
218    }
219
220    /// The reception status a receiver should answer with.
221    #[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    /// The `diagnostic_label` for that reception status: the first error, rule
231    /// identifier first, so that errors are greppable across a fleet.
232    #[must_use]
233    pub fn diagnostic_label(&self) -> Option<String> {
234        self.first_error().map(ToString::to_string)
235    }
236
237    /// Fold another report into this one.
238    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/// When one timer of one actuator finishes.
256///
257/// A three-field struct rather than a `(Id, Timestamp)` pair because timer identifiers
258/// are **not** unique on their own. `S2J schemas/Timer.id`: "Must be unique in the scope
259/// of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in
260/// which it is used" — so an FRBC system with two actuators may legally call a timer
261/// `timer1` on each, and a table keyed by the identifier alone would let one actuator's
262/// running timer block the other's transition.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub struct TimerState {
265    /// The actuator whose timer this is.
266    ///
267    /// [`Id::NIL`] for OMBC, whose timers belong to the `OMBC.SystemDescription` itself
268    /// rather than to an actuator — the same stand-in
269    /// [`Context::active_modes`] uses for OMBC's single state machine.
270    pub actuator: Id,
271    /// The timer.
272    pub timer: Id,
273    /// When it finishes. In the past means it has finished; "if the timer was never
274    /// started, the value can be an arbitrary DateTimeStamp in the past", so a timer
275    /// nobody has reported on is not the same as a finished one.
276    pub finished_at: Timestamp,
277}
278
279/// What the cross-message rules need to know.
280///
281/// [`Context::empty`] runs the rules that need nothing but the message in front of them,
282/// which is what makes the validator usable on a lone JSON file. A session fills in the
283/// rest.
284/// Fields are public and the struct is deliberately **not** `#[non_exhaustive]`: a
285/// proxy, an analyzer or a test builds one with `Context { frbc: Some(&system),
286/// ..Context::empty() }`, and a marker that forbids struct-update syntax would take that
287/// away for the sake of a guarantee this crate does not need before 1.0.
288#[derive(Debug, Clone, Copy, Default)]
289pub struct Context<'a> {
290    /// The negotiated wire profile.
291    pub profile: WireProfile,
292    /// Which role sent the message being validated.
293    pub sender: Option<EnergyManagementRole>,
294    /// Where the session has got to: negotiating, connected, or a control type active.
295    ///
296    /// The row of `S2C §State of communication` this message is being judged against.
297    pub phase: Phase,
298    /// Whether the session is running under S2 Connect, where the handshake messages
299    /// must not appear.
300    pub s2_connect: bool,
301    /// The resource's details, once it has sent them.
302    pub details: Option<&'a ResourceManagerDetails>,
303    /// The effective FRBC system description.
304    pub frbc: Option<&'a frbc::SystemDescription>,
305    /// The effective OMBC system description.
306    pub ombc: Option<&'a ombc::SystemDescription>,
307    /// The effective DDBC system description.
308    pub ddbc: Option<&'a ddbc::SystemDescription>,
309    /// Power constraints currently published.
310    pub pebc_constraints: &'a [pebc::PowerConstraints],
311    /// Power profiles currently published.
312    pub ppbc_profiles: &'a [ppbc::PowerProfileDefinition],
313    /// Instruction identifiers the CEM has already used.
314    pub instructions: &'a [Id],
315    /// `(message_id, instruction_id)` for each of them, so that a status update naming
316    /// the wrong one of the two can say which mistake was made.
317    pub instruction_messages: &'a [(Id, Id)],
318    /// The latest status of each instruction.
319    pub instruction_statuses: &'a [(Id, InstructionStatus)],
320    /// Message identifiers already seen this session.
321    pub seen_message_ids: &'a [Id],
322    /// Objects published this session, and so revokable.
323    pub published: &'a [(RevokableObjects, Id)],
324    /// The operation mode each actuator is in, keyed by actuator (`Id::NIL` for OMBC,
325    /// which has a single machine).
326    pub active_modes: &'a [(Id, Id)],
327    /// When each actuator's timers finish.
328    pub timers: &'a [TimerState],
329    /// The present fill level, once the storage has reported one.
330    pub fill_level: Option<f64>,
331    /// The local clock, for the skew rule.
332    pub now: Option<Timestamp>,
333    /// How far a peer's clock may differ before it is worth reporting.
334    pub skew_tolerance: Duration,
335}
336
337impl<'a> Context<'a> {
338    /// A context that knows nothing, so only the intra-message rules run.
339    #[must_use]
340    pub fn empty() -> Self {
341        Self {
342            skew_tolerance: Duration::from_secs(30),
343            ..Self::default()
344        }
345    }
346
347    /// With the resource's details, which several rules need.
348    #[must_use]
349    pub fn with_details(mut self, details: &'a ResourceManagerDetails) -> Self {
350        self.details = Some(details);
351        self
352    }
353
354    /// With a clock, which the timer and skew rules need.
355    #[must_use]
356    pub fn at(mut self, now: Timestamp) -> Self {
357        self.now = Some(now);
358        self
359    }
360
361    /// With the role that sent the message, which the state rules need.
362    #[must_use]
363    pub fn sent_by(mut self, sender: EnergyManagementRole) -> Self {
364        self.sender = Some(sender);
365        self
366    }
367
368    /// With a control type active, which the state rules need.
369    #[must_use]
370    pub fn active(mut self, control_type: ControlType) -> Self {
371        self.phase = Phase::selected(control_type);
372        self
373    }
374
375    /// With the session in a particular phase, which the state rules need.
376    #[must_use]
377    pub const fn in_phase(mut self, phase: Phase) -> Self {
378        self.phase = phase;
379        self
380    }
381
382    /// The control type that is active, if one that can be instructed is.
383    #[must_use]
384    pub const fn active_control_type(&self) -> Option<ControlType> {
385        self.phase.active_control_type()
386    }
387
388    /// Whether cross-message rules can run at all.
389    #[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
409/// Something that can be checked against the standard's semantics.
410pub trait Validate {
411    /// Check, recording everything wrong at `path` and below.
412    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report);
413
414    /// Check, returning a fresh report.
415    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/// The rule catalogue as Markdown, for the documentation site and `s2-kit rules`.
423///
424/// Generated rather than written, so the document and the code cannot disagree about
425/// which rules exist or how severe they are.
426#[must_use]
427#[allow(clippy::format_push_string)] // a few dozen rows; clarity beats the allocation
428pub 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
464// ---------------------------------------------------------------------------
465// Shared checks
466// ---------------------------------------------------------------------------
467
468pub(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
476/// A number that cannot be encoded is not a number S2 can carry.
477pub(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
487/// A range whose ends are a *factor-0 value* and a *factor-1 value*, not a low and a
488/// high.
489///
490/// `S2J schemas/FRBC.OperationModeElement.fill_rate`: "The lower_boundary of the
491/// NumberRange is associated with an operation_mode_factor of 0, the upper_boundary is
492/// associated with an operation_mode_factor of 1." Nothing says the first is the
493/// smaller, and for a discharging battery it is not: its fill rate runs from 0 down to
494/// −0.0025, and its power from 0 down to −5000 W. Only finiteness is checked here.
495pub(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
500/// A range whose start must not be after its end, where the standard says so.
501pub(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
516/// A band whose start must be *strictly* below its end, as fill-level bands are.
517pub(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
543/// Checks an array against the `minItems`/`maxItems` the schema gives it.
544pub(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
572/// "at most one item per commodity_quantity", which appears on every power array.
573pub(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
603/// Identifiers must be unique within the scope the standard names.
604pub(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
623/// Bands must tile their range with no gap and no overlap.
624pub(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        // A few ULPs rather than one: a boundary a Resource Manager *computed* — 100/3,
637        // a kWh converted from Wh — lands a bit or two either side of the same boundary
638        // written out by hand, and a rule that calls that a gap reports arithmetic rather
639        // than a defect. A real gap in a fill-level band is a whole unit, not a bit.
640        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
655/// Confidence bands run from the lower limit up to the upper.
656pub(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
682/// How far ahead a *scheduled* instant may be before it reads as a mistake.
683///
684/// A year. `valid_from`, `start_time` and `execution_time` are allowed to be in the
685/// future — that is what they are for — so the only thing worth saying about one is that
686/// it is so far away that nothing will still be running when it arrives.
687pub(crate) const SCHEDULING_HORIZON: Duration = Duration::from_secs(365 * 86_400);
688
689/// A timestamp that says when something *happened*, checked against the local clock.
690///
691/// `measurement_timestamp`, `transition_timestamp` and an `InstructionStatusUpdate`'s
692/// `timestamp` all describe the past. One of them in the future means the two clocks
693/// disagree, and by how much is exactly what
694/// [`skew_tolerance`](Context::skew_tolerance) is for — the knob would be decoration if
695/// this were the fixed horizon the scheduled instants need.
696///
697/// Nothing is ever reported for a timestamp in the *past*: the standard says plainly that
698/// one means "already" (`S2J messages/FRBC.TimerStatus.finished_at`), and a device whose
699/// clock is a minute slow is a device, not a fault.
700pub(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
717/// A timestamp that says when something *will* happen, checked for plausibility only.
718pub(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
730/// Transitions may only name modes and timers of their own scope.
731pub(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
772/// The shared part of every instruction check: does the mode exist, is it allowed now,
773/// and is the move it asks for blocked?
774pub(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        // the S2 documentation, *Operation modes*: "A CEM is also always allowed to request the
808        // RM to go the same Operation Mode as the currently active one, but with a
809        // different factor. It is not necessary for the RM to define a Transition from
810        // that Operation Mode to itself."
811        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            // A timer nobody has reported on is not a finished timer: the standard says
843            // an unstarted timer carries "an arbitrary DateTimeStamp in the past", which
844            // means silence tells us nothing either way.
845            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
865/// Rules that apply to every message, whatever it is.
866pub(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        // A boundary computed rather than written: 100/3 from one side, the sum of two
957        // thirds from the other. They are the same number to any reader and a few bits
958        // apart to a machine, and a rule that calls that a gap reports floating point.
959        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        // A gap of a thousandth of a unit is still a gap.
975        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        // A measurement says something has already happened, so half a minute of skew is
1090        // tolerated and a minute is not — which is what the knob is for.
1091        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        // The past is never skew: "in the past means already".
1102        assert!(
1103            measured_at("2020-01-01T00:00:00Z")
1104                .validate(&ctx)
1105                .is_empty()
1106        );
1107        // And the knob really is one.
1108        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        // A *scheduled* instant is allowed to be in the future — that is what it is for —
1119        // and only an absurd one is worth a word.
1120        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}