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, 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    /// The control type that is active, if any.
295    pub active_control_type: Option<ControlType>,
296    /// Whether the session is running under S2 Connect, where the handshake messages
297    /// must not appear.
298    pub s2_connect: bool,
299    /// The resource's details, once it has sent them.
300    pub details: Option<&'a ResourceManagerDetails>,
301    /// The effective FRBC system description.
302    pub frbc: Option<&'a frbc::SystemDescription>,
303    /// The effective OMBC system description.
304    pub ombc: Option<&'a ombc::SystemDescription>,
305    /// The effective DDBC system description.
306    pub ddbc: Option<&'a ddbc::SystemDescription>,
307    /// Power constraints currently published.
308    pub pebc_constraints: &'a [pebc::PowerConstraints],
309    /// Power profiles currently published.
310    pub ppbc_profiles: &'a [ppbc::PowerProfileDefinition],
311    /// Instruction identifiers the CEM has already used.
312    pub instructions: &'a [Id],
313    /// The latest status of each instruction.
314    pub instruction_statuses: &'a [(Id, InstructionStatus)],
315    /// Message identifiers already seen this session.
316    pub seen_message_ids: &'a [Id],
317    /// Objects published this session, and so revokable.
318    pub published: &'a [(RevokableObjects, Id)],
319    /// The operation mode each actuator is in, keyed by actuator (`Id::NIL` for OMBC,
320    /// which has a single machine).
321    pub active_modes: &'a [(Id, Id)],
322    /// When each actuator's timers finish.
323    pub timers: &'a [TimerState],
324    /// The present fill level, once the storage has reported one.
325    pub fill_level: Option<f64>,
326    /// The local clock, for the skew rule.
327    pub now: Option<Timestamp>,
328    /// How far a peer's clock may differ before it is worth reporting.
329    pub skew_tolerance: Duration,
330}
331
332impl<'a> Context<'a> {
333    /// A context that knows nothing, so only the intra-message rules run.
334    #[must_use]
335    pub fn empty() -> Self {
336        Self {
337            skew_tolerance: Duration::from_secs(30),
338            ..Self::default()
339        }
340    }
341
342    /// With the resource's details, which several rules need.
343    #[must_use]
344    pub fn with_details(mut self, details: &'a ResourceManagerDetails) -> Self {
345        self.details = Some(details);
346        self
347    }
348
349    /// With a clock, which the timer and skew rules need.
350    #[must_use]
351    pub fn at(mut self, now: Timestamp) -> Self {
352        self.now = Some(now);
353        self
354    }
355
356    /// With the role that sent the message, which the state rules need.
357    #[must_use]
358    pub fn sent_by(mut self, sender: EnergyManagementRole) -> Self {
359        self.sender = Some(sender);
360        self
361    }
362
363    /// With a control type active, which the state rules need.
364    #[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    /// Whether cross-message rules can run at all.
371    #[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
391/// Something that can be checked against the standard's semantics.
392pub trait Validate {
393    /// Check, recording everything wrong at `path` and below.
394    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report);
395
396    /// Check, returning a fresh report.
397    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/// The rule catalogue as Markdown, for the documentation site and `s2-kit rules`.
405///
406/// Generated rather than written, so the document and the code cannot disagree about
407/// which rules exist or how severe they are.
408#[must_use]
409#[allow(clippy::format_push_string)] // a few dozen rows; clarity beats the allocation
410pub 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
446// ---------------------------------------------------------------------------
447// Shared checks
448// ---------------------------------------------------------------------------
449
450pub(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
458/// A number that cannot be encoded is not a number S2 can carry.
459pub(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
469/// A range whose ends are a *factor-0 value* and a *factor-1 value*, not a low and a
470/// high.
471///
472/// `S2J schemas/FRBC.OperationModeElement.fill_rate`: "The lower_boundary of the
473/// NumberRange is associated with an operation_mode_factor of 0, the upper_boundary is
474/// associated with an operation_mode_factor of 1." Nothing says the first is the
475/// smaller, and for a discharging battery it is not: its fill rate runs from 0 down to
476/// −0.0025, and its power from 0 down to −5000 W. Only finiteness is checked here.
477pub(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
482/// A range whose start must not be after its end, where the standard says so.
483pub(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
498/// A band whose start must be *strictly* below its end, as fill-level bands are.
499pub(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
525/// Checks an array against the `minItems`/`maxItems` the schema gives it.
526pub(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
554/// "at most one item per commodity_quantity", which appears on every power array.
555pub(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
585/// Identifiers must be unique within the scope the standard names.
586pub(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
605/// Bands must tile their range with no gap and no overlap.
606pub(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        // A few ULPs rather than one: a boundary a Resource Manager *computed* — 100/3,
619        // a kWh converted from Wh — lands a bit or two either side of the same boundary
620        // written out by hand, and a rule that calls that a gap reports arithmetic rather
621        // than a defect. A real gap in a fill-level band is a whole unit, not a bit.
622        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
637/// Confidence bands run from the lower limit up to the upper.
638pub(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
664/// How far ahead a *scheduled* instant may be before it reads as a mistake.
665///
666/// A year. `valid_from`, `start_time` and `execution_time` are allowed to be in the
667/// future — that is what they are for — so the only thing worth saying about one is that
668/// it is so far away that nothing will still be running when it arrives.
669pub(crate) const SCHEDULING_HORIZON: Duration = Duration::from_secs(365 * 86_400);
670
671/// A timestamp that says when something *happened*, checked against the local clock.
672///
673/// `measurement_timestamp`, `transition_timestamp` and an `InstructionStatusUpdate`'s
674/// `timestamp` all describe the past. One of them in the future means the two clocks
675/// disagree, and by how much is exactly what
676/// [`skew_tolerance`](Context::skew_tolerance) is for — the knob would be decoration if
677/// this were the fixed horizon the scheduled instants need.
678///
679/// Nothing is ever reported for a timestamp in the *past*: the standard says plainly that
680/// one means "already" (`S2J messages/FRBC.TimerStatus.finished_at`), and a device whose
681/// clock is a minute slow is a device, not a fault.
682pub(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
698/// A timestamp that says when something *will* happen, checked for plausibility only.
699pub(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
711/// Transitions may only name modes and timers of their own scope.
712pub(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
753/// The shared part of every instruction check: does the mode exist, is it allowed now,
754/// and is the move it asks for blocked?
755pub(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        // the S2 documentation, *Operation modes*: "A CEM is also always allowed to request the
789        // RM to go the same Operation Mode as the currently active one, but with a
790        // different factor. It is not necessary for the RM to define a Transition from
791        // that Operation Mode to itself."
792        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            // A timer nobody has reported on is not a finished timer: the standard says
824            // an unstarted timer carries "an arbitrary DateTimeStamp in the past", which
825            // means silence tells us nothing either way.
826            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
846/// Rules that apply to every message, whatever it is.
847pub(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        // A boundary computed rather than written: 100/3 from one side, the sum of two
939        // thirds from the other. They are the same number to any reader and a few bits
940        // apart to a machine, and a rule that calls that a gap reports floating point.
941        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        // A gap of a thousandth of a unit is still a gap.
957        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        // A measurement says something has already happened, so half a minute of skew is
1072        // tolerated and a minute is not — which is what the knob is for.
1073        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        // The past is never skew: "in the past means already".
1084        assert!(
1085            measured_at("2020-01-01T00:00:00Z")
1086                .validate(&ctx)
1087                .is_empty()
1088        );
1089        // And the knob really is one.
1090        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        // A *scheduled* instant is allowed to be in the future — that is what it is for —
1101        // and only an absurd one is worth a word.
1102        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}