Skip to main content

s2_kit/validate/
messages.rs

1//! [`Validate`] for every message and component.
2//!
3//! One function per message, each checking the rules
4//! §"Semantic rules" that apply to it. Rules that need nothing but the message run with
5//! an empty [`Context`]; rules that need the session run only when it supplies one, so
6//! the same code validates a lone JSON file and a live conversation.
7
8use alloc::format;
9use alloc::vec::Vec;
10
11use super::{
12    Context, ModeCheck, Report, Validate, check_array, check_band, check_envelope, check_factor,
13    check_finite, check_instruction_context, check_interpolated, check_observed, check_percentiles,
14    check_range, check_scheduled, check_transitions, check_unique_ids, check_unique_quantities,
15    child, index, rules,
16};
17use crate::message::Message;
18use crate::types::common::{
19    Commodity, CommodityQuantity, ControlType, EnergyManagementRole, Handshake, HandshakeResponse,
20    InstructionStatusUpdate, NumberRange, PowerForecast, PowerForecastValue, PowerMeasurement,
21    PowerRange, ReceptionStatus, ResourceManagerDetails, RevokeObject, Role, SelectControlType,
22    SessionRequest,
23};
24use crate::types::{Id, ddbc, frbc, ombc, pebc, ppbc};
25
26impl Validate for Message {
27    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
28        check_envelope(self.kind(), self.id(), ctx, out);
29        match self {
30            Message::Handshake(m) => m.validate_at(path, ctx, out),
31            Message::HandshakeResponse(m) => m.validate_at(path, ctx, out),
32            Message::ResourceManagerDetails(m) => m.validate_at(path, ctx, out),
33            Message::SelectControlType(m) => m.validate_at(path, ctx, out),
34            Message::SessionRequest(m) => m.validate_at(path, ctx, out),
35            Message::ReceptionStatus(m) => m.validate_at(path, ctx, out),
36            Message::InstructionStatusUpdate(m) => m.validate_at(path, ctx, out),
37            Message::PowerMeasurement(m) => m.validate_at(path, ctx, out),
38            Message::PowerForecast(m) => m.validate_at(path, ctx, out),
39            Message::RevokeObject(m) => m.validate_at(path, ctx, out),
40            Message::PebcPowerConstraints(m) => m.validate_at(path, ctx, out),
41            Message::PebcEnergyConstraint(m) => m.validate_at(path, ctx, out),
42            Message::PebcInstruction(m) => m.validate_at(path, ctx, out),
43            Message::PpbcPowerProfileDefinition(m) => m.validate_at(path, ctx, out),
44            Message::PpbcPowerProfileStatus(m) => m.validate_at(path, ctx, out),
45            Message::PpbcScheduleInstruction(m) => m.validate_at(path, ctx, out),
46            Message::PpbcStartInterruptionInstruction(m) => m.validate_at(path, ctx, out),
47            Message::PpbcEndInterruptionInstruction(m) => m.validate_at(path, ctx, out),
48            Message::OmbcSystemDescription(m) => m.validate_at(path, ctx, out),
49            Message::OmbcStatus(m) => m.validate_at(path, ctx, out),
50            Message::OmbcTimerStatus(m) => m.validate_at(path, ctx, out),
51            Message::OmbcInstruction(m) => m.validate_at(path, ctx, out),
52            Message::FrbcSystemDescription(m) => m.validate_at(path, ctx, out),
53            Message::FrbcStorageStatus(m) => m.validate_at(path, ctx, out),
54            Message::FrbcActuatorStatus(m) => m.validate_at(path, ctx, out),
55            Message::FrbcTimerStatus(m) => m.validate_at(path, ctx, out),
56            Message::FrbcLeakageBehaviour(m) => m.validate_at(path, ctx, out),
57            Message::FrbcUsageForecast(m) => m.validate_at(path, ctx, out),
58            Message::FrbcFillLevelTargetProfile(m) => m.validate_at(path, ctx, out),
59            Message::FrbcInstruction(m) => m.validate_at(path, ctx, out),
60            Message::DdbcSystemDescription(m) => m.validate_at(path, ctx, out),
61            Message::DdbcActuatorStatus(m) => m.validate_at(path, ctx, out),
62            Message::DdbcTimerStatus(m) => m.validate_at(path, ctx, out),
63            Message::DdbcAverageDemandRateForecast(m) => m.validate_at(path, ctx, out),
64            Message::DdbcPresentDemandStatus(m) => m.validate_at(path, ctx, out),
65            Message::DdbcInstruction(m) => m.validate_at(path, ctx, out),
66        }
67    }
68}
69
70// ---------------------------------------------------------------------------
71// Shared pieces
72// ---------------------------------------------------------------------------
73
74fn check_power_ranges(ranges: &[PowerRange], owner: &str, path: &str, out: &mut Report) {
75    let at = child(path, "power_ranges");
76    check_array(owner, "power_ranges", ranges.len(), path, out);
77    check_unique_quantities(ranges.iter().map(|r| r.commodity_quantity), &at, out);
78    for (i, range) in ranges.iter().enumerate() {
79        let element = index(&at, i);
80        check_finite(
81            range.start_of_range,
82            &child(&element, "start_of_range"),
83            out,
84        );
85        check_finite(range.end_of_range, &child(&element, "end_of_range"), out);
86    }
87}
88
89fn check_forecast_values(values: &[PowerForecastValue], owner: &str, path: &str, out: &mut Report) {
90    let at = child(path, "power_values");
91    check_array(owner, "power_values", values.len(), path, out);
92    check_unique_quantities(values.iter().map(|v| v.commodity_quantity), &at, out);
93    for (i, value) in values.iter().enumerate() {
94        check_percentiles(&value.bands_ascending(), &index(&at, i), out);
95    }
96}
97
98/// `S2J messages/ResourceManagerDetails.currency`: "Mandatory if cost information is
99/// published."
100fn check_currency(publishes_costs: bool, path: &str, ctx: &Context<'_>, out: &mut Report) {
101    if publishes_costs
102        && let Some(details) = ctx.details
103        && details.currency.is_none()
104    {
105        out.push(
106            rules::CURRENCY_REQUIRED,
107            path,
108            "costs are published but the ResourceManagerDetails declared no currency",
109        );
110    }
111}
112
113fn running_costs_present(ranges: &[Option<NumberRange>]) -> bool {
114    ranges.iter().any(Option::is_some)
115}
116
117/// An actuator should not name the same commodity twice.
118fn check_supported_commodities(
119    commodities: &[Commodity],
120    property: &str,
121    path: &str,
122    out: &mut Report,
123) {
124    let at = child(path, property);
125    for (i, commodity) in commodities.iter().enumerate() {
126        if commodities
127            .get(..i)
128            .is_some_and(|seen| seen.contains(commodity))
129        {
130            out.push(
131                rules::DUPLICATE_SUPPORTED_COMMODITY,
132                &index(&at, i),
133                format!("{commodity:?} is already in this actuator's supported commodities"),
134            );
135        }
136    }
137}
138
139/// Every commodity the actuator supports should appear in the power ranges of every
140/// operation mode, or a CEM has no way to work out that commodity's power.
141///
142/// Not a schema requirement, but `s2-python` refuses a description without it — see
143/// [`rules::COMMODITY_WITHOUT_POWER_RANGE`]. The converse check `s2-python` also makes,
144/// that a commodity appears at *most* once, is deliberately **not** implemented here: a
145/// three-phase asymmetric actuator legitimately publishes `ELECTRIC.POWER.L1`, `L2` and
146/// `L3`, which are three quantities of one commodity. `S2-PM-001` already enforces the
147/// rule the schema does state — at most one range per *quantity*.
148fn check_commodity_coverage(
149    supported: &[Commodity],
150    ranges: &[PowerRange],
151    path: &str,
152    out: &mut Report,
153) {
154    for commodity in supported {
155        if !ranges
156            .iter()
157            .any(|r| r.commodity_quantity.commodity() == *commodity)
158        {
159            out.push(
160                rules::COMMODITY_WITHOUT_POWER_RANGE,
161                &child(path, "power_ranges"),
162                format!(
163                    "the actuator supports {commodity:?} but this operation mode \
164                     publishes no power range for it"
165                ),
166            );
167        }
168    }
169}
170
171// ---------------------------------------------------------------------------
172// Common messages
173// ---------------------------------------------------------------------------
174
175impl Validate for Handshake {
176    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
177        if let Some(versions) = &self.supported_protocol_versions {
178            check_array(
179                "Handshake",
180                "supported_protocol_versions",
181                versions.len(),
182                path,
183                out,
184            );
185        } else if self.role == EnergyManagementRole::Rm {
186            // "This field is mandatory for the RM, but optional for the CEM."
187            out.push(
188                rules::ROLE_REQUIRED_FIELD,
189                &child(path, "supported_protocol_versions"),
190                "a Resource Manager must list the protocol versions it supports; \
191                 the field is optional only for a CEM",
192            );
193        }
194        let _ = ctx;
195    }
196}
197
198impl Validate for HandshakeResponse {
199    fn validate_at(&self, _path: &str, _ctx: &Context<'_>, _out: &mut Report) {}
200}
201
202impl Validate for SessionRequest {
203    fn validate_at(&self, _path: &str, _ctx: &Context<'_>, _out: &mut Report) {}
204}
205
206impl Validate for ReceptionStatus {
207    fn validate_at(&self, _path: &str, _ctx: &Context<'_>, _out: &mut Report) {}
208}
209
210impl Validate for ResourceManagerDetails {
211    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
212        check_array(
213            "ResourceManagerDetails",
214            "roles",
215            self.roles.len(),
216            path,
217            out,
218        );
219        check_array(
220            "ResourceManagerDetails",
221            "available_control_types",
222            self.available_control_types.len(),
223            path,
224            out,
225        );
226        check_array(
227            "ResourceManagerDetails",
228            "provides_power_measurement_types",
229            self.provides_power_measurement_types.len(),
230            path,
231            out,
232        );
233
234        // The `(role, commodity)` pair, not the commodity alone: `roles` is capped at
235        // three, there are three `RoleType`s and four `Commodity`s, so the cap counts
236        // role types and a resource may be storage, load and generator for one commodity
237        // (S2-RMD-003, erratum E30). Only the repeated pair says nothing.
238        let mut seen: Vec<Role> = Vec::new();
239        for (i, role) in self.roles.iter().enumerate() {
240            if seen.contains(role) {
241                out.push(
242                    rules::DUPLICATE_ROLE,
243                    &index(&child(path, "roles"), i),
244                    format!(
245                        "{:?} is already declared for {:?} in this resource",
246                        role.role, role.commodity
247                    ),
248                );
249            } else {
250                seen.push(*role);
251            }
252        }
253
254        if self
255            .available_control_types
256            .contains(&ControlType::NoSelection)
257        {
258            out.push(
259                rules::NO_SELECTION_OFFERED,
260                &child(path, "available_control_types"),
261                "NO_SELECTION is the absence of a control type, not one a resource can offer",
262            );
263        }
264
265        check_unique_quantities(
266            self.provides_power_measurement_types.iter().copied(),
267            &child(path, "provides_power_measurement_types"),
268            out,
269        );
270        let _ = ctx;
271    }
272}
273
274impl Validate for SelectControlType {
275    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
276        if let Some(details) = ctx.details
277            && self.control_type != ControlType::NoSelection
278            && !details.available_control_types.contains(&self.control_type)
279        {
280            out.push(
281                rules::CONTROL_TYPE_NOT_OFFERED,
282                &child(path, "control_type"),
283                format!(
284                    "{:?} is not one of the control types this resource offers",
285                    self.control_type
286                ),
287            );
288        }
289    }
290}
291
292impl Validate for PowerMeasurement {
293    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
294        check_array("PowerMeasurement", "values", self.values.len(), path, out);
295        let at = child(path, "values");
296        check_unique_quantities(self.values.iter().map(|v| v.commodity_quantity), &at, out);
297        for (i, value) in self.values.iter().enumerate() {
298            check_finite(value.value, &child(&index(&at, i), "value"), out);
299        }
300        check_observed(
301            self.measurement_timestamp,
302            &child(path, "measurement_timestamp"),
303            ctx,
304            out,
305        );
306
307        if let Some(details) = ctx.details {
308            for (i, value) in self.values.iter().enumerate() {
309                if !details
310                    .provides_power_measurement_types
311                    .contains(&value.commodity_quantity)
312                {
313                    out.push(
314                        rules::MEASUREMENT_NOT_OFFERED,
315                        &child(&index(&at, i), "commodity_quantity"),
316                        format!(
317                            "{:?} is not among the quantities this resource said it measures",
318                            value.commodity_quantity
319                        ),
320                    );
321                }
322            }
323        }
324    }
325}
326
327impl Validate for PowerForecast {
328    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
329        check_array("PowerForecast", "elements", self.elements.len(), path, out);
330        let at = child(path, "elements");
331        for (i, element) in self.elements.iter().enumerate() {
332            check_forecast_values(
333                &element.power_values,
334                "PowerForecastElement",
335                &index(&at, i),
336                out,
337            );
338        }
339        check_scheduled(self.start_time, &child(path, "start_time"), ctx, out);
340
341        if let Some(details) = ctx.details
342            && !details.provides_forecast
343        {
344            out.push(
345                rules::FORECAST_NOT_OFFERED,
346                path,
347                "this resource said provides_forecast is false",
348            );
349        }
350    }
351}
352
353impl Validate for InstructionStatusUpdate {
354    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
355        check_observed(self.timestamp, &child(path, "timestamp"), ctx, out);
356
357        if !ctx.instructions.is_empty() && !ctx.instructions.contains(&self.instruction_id) {
358            // An instruction carries two identifiers — its `message_id` and its own `id` —
359            // and `instruction_id` is "ID of this instruction (as provided by the CEM)",
360            // which is the second. Echoing the first is the commonest mistake there is
361            // here, and it is worth naming: the peer sees a rule id and a sentence that
362            // tells it exactly which field to change, rather than a `ReceptionStatus` it
363            // has to reverse-engineer.
364            let echoed = ctx
365                .instruction_messages
366                .iter()
367                .find(|(message_id, _)| *message_id == self.instruction_id);
368            let message = match echoed {
369                Some((_, instruction)) => format!(
370                    "{} is the message_id of the instruction whose id is {instruction}; \
371                     instruction_id must be the instruction's own id",
372                    self.instruction_id
373                ),
374                None => format!("{} was never sent on this session", self.instruction_id),
375            };
376            out.push_related(
377                rules::UNKNOWN_INSTRUCTION,
378                &child(path, "instruction_id"),
379                message,
380                [self.instruction_id],
381            );
382        }
383
384        if let Some((_, previous)) = ctx
385            .instruction_statuses
386            .iter()
387            .find(|(id, _)| *id == self.instruction_id)
388            && self.status_type.progress_rank() < previous.progress_rank()
389        {
390            out.push_related(
391                rules::STATUS_REGRESSION,
392                &child(path, "status_type"),
393                format!(
394                    "{:?} comes after {:?}, which is already terminal or further along",
395                    self.status_type, previous
396                ),
397                [self.instruction_id],
398            );
399        }
400    }
401}
402
403impl Validate for RevokeObject {
404    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
405        if let Some(sender) = ctx.sender
406            && self.object_type.owner() != sender
407        {
408            out.push(
409                rules::REVOKE_ROLE_MISMATCH,
410                &child(path, "object_type"),
411                format!(
412                    "{:?} is published by the {:?}, not by the {sender:?}",
413                    self.object_type,
414                    self.object_type.owner()
415                ),
416            );
417        }
418
419        if !ctx.published.is_empty()
420            && !ctx
421                .published
422                .iter()
423                .any(|(t, id)| *t == self.object_type && *id == self.object_id)
424        {
425            out.push_related(
426                rules::REVOKE_UNKNOWN,
427                path,
428                format!(
429                    "no {:?} with identifier {} was published on this session",
430                    self.object_type, self.object_id
431                ),
432                [self.object_id],
433            );
434        }
435    }
436}
437
438// ---------------------------------------------------------------------------
439// FRBC
440// ---------------------------------------------------------------------------
441
442impl Validate for frbc::SystemDescription {
443    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
444        check_array(
445            "FRBC.SystemDescription",
446            "actuators",
447            self.actuators.len(),
448            path,
449            out,
450        );
451        check_scheduled(self.valid_from, &child(path, "valid_from"), ctx, out);
452        check_unique_ids(
453            self.actuators.iter().map(|a| &a.id),
454            "the Resource Manager",
455            &child(path, "actuators"),
456            out,
457        );
458
459        let at = child(path, "actuators");
460        let mut publishes_costs = false;
461        for (i, actuator) in self.actuators.iter().enumerate() {
462            let actuator_path = index(&at, i);
463            check_array(
464                "FRBC.ActuatorDescription",
465                "operation_modes",
466                actuator.operation_modes.len(),
467                &actuator_path,
468                out,
469            );
470            check_array(
471                "FRBC.ActuatorDescription",
472                "supported_commodities",
473                actuator.supported_commodities.len(),
474                &actuator_path,
475                out,
476            );
477            check_supported_commodities(
478                &actuator.supported_commodities,
479                "supported_commodities",
480                &actuator_path,
481                out,
482            );
483            check_unique_ids(
484                actuator.operation_modes.iter().map(|m| &m.id),
485                "this actuator",
486                &child(&actuator_path, "operation_modes"),
487                out,
488            );
489            check_unique_ids(
490                actuator.timers.iter().map(|t| &t.id),
491                "this actuator",
492                &child(&actuator_path, "timers"),
493                out,
494            );
495            check_unique_ids(
496                actuator.transitions.iter().map(|t| &t.id),
497                "this actuator",
498                &child(&actuator_path, "transitions"),
499                out,
500            );
501
502            let modes = child(&actuator_path, "operation_modes");
503            for (j, mode) in actuator.operation_modes.iter().enumerate() {
504                let mode_path = index(&modes, j);
505                check_array(
506                    "FRBC.OperationMode",
507                    "elements",
508                    mode.elements.len(),
509                    &mode_path,
510                    out,
511                );
512                let elements = child(&mode_path, "elements");
513                for (k, element) in mode.elements.iter().enumerate() {
514                    let element_path = index(&elements, k);
515                    check_band(
516                        element.fill_level_range,
517                        &child(&element_path, "fill_level_range"),
518                        out,
519                    );
520                    check_interpolated(element.fill_rate, &child(&element_path, "fill_rate"), out);
521                    check_power_ranges(
522                        &element.power_ranges,
523                        "FRBC.OperationModeElement",
524                        &element_path,
525                        out,
526                    );
527                    if let Some(costs) = element.running_costs {
528                        check_interpolated(costs, &child(&element_path, "running_costs"), out);
529                    }
530                    check_commodity_coverage(
531                        &actuator.supported_commodities,
532                        &element.power_ranges,
533                        &element_path,
534                        out,
535                    );
536                    publishes_costs |= element.running_costs.is_some();
537                }
538                let bands: Vec<NumberRange> =
539                    mode.elements.iter().map(|e| e.fill_level_range).collect();
540                super::check_contiguous(
541                    &bands,
542                    rules::FRBC_ELEMENTS_CONTIGUOUS,
543                    "operation mode fill level bands",
544                    &elements,
545                    out,
546                );
547            }
548
549            let mode_ids: Vec<Id> = actuator.operation_modes.iter().map(|m| m.id).collect();
550            let timer_ids: Vec<Id> = actuator.timers.iter().map(|t| t.id).collect();
551            check_transitions(
552                &actuator.transitions,
553                &mode_ids,
554                &timer_ids,
555                rules::FRBC_TRANSITION_REFERENCES,
556                &child(&actuator_path, "transitions"),
557                out,
558            );
559            publishes_costs |= actuator
560                .transitions
561                .iter()
562                .any(|t| t.transition_costs.is_some());
563        }
564
565        check_band(
566            self.storage.fill_level_range,
567            &child(&child(path, "storage"), "fill_level_range"),
568            out,
569        );
570        check_currency(publishes_costs, path, ctx, out);
571    }
572}
573
574impl Validate for frbc::StorageStatus {
575    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
576        let at = child(path, "present_fill_level");
577        check_finite(self.present_fill_level, &at, out);
578        if let Some(system) = ctx.frbc
579            && self.present_fill_level.is_finite()
580            && !system
581                .storage
582                .fill_level_range
583                .contains(self.present_fill_level)
584        {
585            out.push(
586                rules::FRBC_FILL_LEVEL_OUT_OF_RANGE,
587                &at,
588                format!(
589                    "{} is outside the storage's range {}..{}; \
590                     the Resource Manager may ignore instructions until it is back inside",
591                    self.present_fill_level,
592                    system.storage.fill_level_range.start_of_range,
593                    system.storage.fill_level_range.end_of_range
594                ),
595            );
596        }
597    }
598}
599
600impl Validate for frbc::ActuatorStatus {
601    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
602        check_factor(
603            self.operation_mode_factor,
604            &child(path, "operation_mode_factor"),
605            out,
606        );
607        if let Some(at) = self.transition_timestamp {
608            check_observed(at, &child(path, "transition_timestamp"), ctx, out);
609        }
610        // Per actuator, not per session: an FRBC system may describe up to ten actuators,
611        // and the first status of the second one is still a first status.
612        if ctx.active_mode_of(&self.actuator_id).is_some()
613            && self.previous_operation_mode_id.is_none()
614        {
615            out.push_related(
616                rules::PREVIOUS_MODE_MISSING,
617                path,
618                format!(
619                    "this is not the first status for actuator {}, so the previous \
620                     operation mode and the transition timestamp should be present",
621                    self.actuator_id
622                ),
623                [self.actuator_id],
624            );
625        }
626        if let Some(system) = ctx.frbc {
627            match system.actuator(&self.actuator_id) {
628                None => out.push_related(
629                    rules::FRBC_UNKNOWN_ACTUATOR,
630                    &child(path, "actuator_id"),
631                    format!("{} is not an actuator of this system", self.actuator_id),
632                    [self.actuator_id],
633                ),
634                Some(actuator) => {
635                    if actuator
636                        .operation_mode(&self.active_operation_mode_id)
637                        .is_none()
638                    {
639                        out.push_related(
640                            rules::FRBC_UNKNOWN_MODE,
641                            &child(path, "active_operation_mode_id"),
642                            format!(
643                                "{} is not an operation mode of actuator {}",
644                                self.active_operation_mode_id, self.actuator_id
645                            ),
646                            [self.active_operation_mode_id],
647                        );
648                    }
649                }
650            }
651        }
652    }
653}
654
655impl Validate for frbc::TimerStatus {
656    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
657        if let Some(system) = ctx.frbc {
658            match system.actuator(&self.actuator_id) {
659                None => out.push_related(
660                    rules::FRBC_UNKNOWN_ACTUATOR,
661                    &child(path, "actuator_id"),
662                    format!("{} is not an actuator of this system", self.actuator_id),
663                    [self.actuator_id],
664                ),
665                Some(actuator) if actuator.timer(&self.timer_id).is_none() => out.push_related(
666                    rules::UNKNOWN_TIMER,
667                    &child(path, "timer_id"),
668                    format!(
669                        "{} is not a timer of actuator {}",
670                        self.timer_id, self.actuator_id
671                    ),
672                    [self.timer_id],
673                ),
674                Some(_) => {}
675            }
676        }
677    }
678}
679
680impl Validate for frbc::LeakageBehaviour {
681    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
682        check_array(
683            "FRBC.LeakageBehaviour",
684            "elements",
685            self.elements.len(),
686            path,
687            out,
688        );
689        check_scheduled(self.valid_from, &child(path, "valid_from"), ctx, out);
690        let at = child(path, "elements");
691        for (i, element) in self.elements.iter().enumerate() {
692            let element_path = index(&at, i);
693            check_band(
694                element.fill_level_range,
695                &child(&element_path, "fill_level_range"),
696                out,
697            );
698            check_finite(
699                element.leakage_rate,
700                &child(&element_path, "leakage_rate"),
701                out,
702            );
703        }
704        let bands: Vec<NumberRange> = self.elements.iter().map(|e| e.fill_level_range).collect();
705        super::check_contiguous(
706            &bands,
707            rules::FRBC_LEAKAGE_CONTIGUOUS,
708            "leakage bands",
709            &at,
710            out,
711        );
712
713        if let Some(system) = ctx.frbc
714            && !system.storage.provides_leakage_behaviour
715        {
716            out.push(
717                rules::FRBC_NOT_OFFERED,
718                path,
719                "the storage description said provides_leakage_behaviour is false",
720            );
721        }
722    }
723}
724
725impl Validate for frbc::UsageForecast {
726    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
727        check_array(
728            "FRBC.UsageForecast",
729            "elements",
730            self.elements.len(),
731            path,
732            out,
733        );
734        check_scheduled(self.start_time, &child(path, "start_time"), ctx, out);
735        let at = child(path, "elements");
736        for (i, element) in self.elements.iter().enumerate() {
737            check_percentiles(&element.bands_ascending(), &index(&at, i), out);
738        }
739        if let Some(system) = ctx.frbc
740            && !system.storage.provides_usage_forecast
741        {
742            out.push(
743                rules::FRBC_NOT_OFFERED,
744                path,
745                "the storage description said provides_usage_forecast is false",
746            );
747        }
748    }
749}
750
751impl Validate for frbc::FillLevelTargetProfile {
752    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
753        check_array(
754            "FRBC.FillLevelTargetProfile",
755            "elements",
756            self.elements.len(),
757            path,
758            out,
759        );
760        check_scheduled(self.start_time, &child(path, "start_time"), ctx, out);
761        let at = child(path, "elements");
762        for (i, element) in self.elements.iter().enumerate() {
763            // A target band may be a single point — "The start of the range must be
764            // smaller or equal to the end of the range" — unlike an operation mode's.
765            check_range(
766                element.fill_level_range,
767                &child(&index(&at, i), "fill_level_range"),
768                out,
769            );
770        }
771        if let Some(system) = ctx.frbc
772            && !system.storage.provides_fill_level_target_profile
773        {
774            out.push(
775                rules::FRBC_NOT_OFFERED,
776                path,
777                "the storage description said provides_fill_level_target_profile is false",
778            );
779        }
780    }
781}
782
783impl Validate for frbc::Instruction {
784    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
785        check_factor(
786            self.operation_mode_factor,
787            &child(path, "operation_mode_factor"),
788            out,
789        );
790        check_scheduled(
791            self.execution_time,
792            &child(path, "execution_time"),
793            ctx,
794            out,
795        );
796        check_duplicate_instruction(self.id, path, ctx, out);
797
798        let Some(system) = ctx.frbc else { return };
799        let Some(actuator) = system.actuator(&self.actuator_id) else {
800            out.push_related(
801                rules::FRBC_UNKNOWN_ACTUATOR,
802                &child(path, "actuator_id"),
803                format!("{} is not an actuator of this system", self.actuator_id),
804                [self.actuator_id],
805            );
806            return;
807        };
808        let Some(mode) = actuator.operation_mode(&self.operation_mode) else {
809            out.push_related(
810                rules::FRBC_UNKNOWN_MODE,
811                &child(path, "operation_mode"),
812                format!(
813                    "{} is not an operation mode of actuator {}",
814                    self.operation_mode, self.actuator_id
815                ),
816                [self.operation_mode],
817            );
818            return;
819        };
820        check_instruction_context(
821            &ModeCheck {
822                actuator: Some(&self.actuator_id),
823                mode: &self.operation_mode,
824                abnormal_condition: self.abnormal_condition,
825                abnormal_only: mode.abnormal_condition_only,
826                transitions: &actuator.transitions,
827                timers: &actuator.timers,
828            },
829            path,
830            ctx,
831            out,
832        );
833    }
834}
835
836// ---------------------------------------------------------------------------
837// OMBC
838// ---------------------------------------------------------------------------
839
840impl Validate for ombc::SystemDescription {
841    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
842        check_array(
843            "OMBC.SystemDescription",
844            "operation_modes",
845            self.operation_modes.len(),
846            path,
847            out,
848        );
849        check_scheduled(self.valid_from, &child(path, "valid_from"), ctx, out);
850        check_unique_ids(
851            self.operation_modes.iter().map(|m| &m.id),
852            "the Resource Manager",
853            &child(path, "operation_modes"),
854            out,
855        );
856        check_unique_ids(
857            self.timers.iter().map(|t| &t.id),
858            "this description",
859            &child(path, "timers"),
860            out,
861        );
862        check_unique_ids(
863            self.transitions.iter().map(|t| &t.id),
864            "this description",
865            &child(path, "transitions"),
866            out,
867        );
868
869        let modes = child(path, "operation_modes");
870        let mut costs = Vec::new();
871        for (i, mode) in self.operation_modes.iter().enumerate() {
872            let mode_path = index(&modes, i);
873            check_power_ranges(&mode.power_ranges, "OMBC.OperationMode", &mode_path, out);
874            if let Some(running) = mode.running_costs {
875                check_interpolated(running, &child(&mode_path, "running_costs"), out);
876            }
877            costs.push(mode.running_costs);
878        }
879
880        let mode_ids: Vec<Id> = self.operation_modes.iter().map(|m| m.id).collect();
881        let timer_ids: Vec<Id> = self.timers.iter().map(|t| t.id).collect();
882        check_transitions(
883            &self.transitions,
884            &mode_ids,
885            &timer_ids,
886            rules::OMBC_TRANSITION_REFERENCES,
887            &child(path, "transitions"),
888            out,
889        );
890
891        let publishes_costs = running_costs_present(&costs)
892            || self
893                .transitions
894                .iter()
895                .any(|t| t.transition_costs.is_some());
896        check_currency(publishes_costs, path, ctx, out);
897    }
898}
899
900impl Validate for ombc::Status {
901    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
902        check_factor(
903            self.operation_mode_factor,
904            &child(path, "operation_mode_factor"),
905            out,
906        );
907        if let Some(at) = self.transition_timestamp {
908            check_observed(at, &child(path, "transition_timestamp"), ctx, out);
909        }
910        // OMBC has one state machine rather than actuators, so `Id::NIL` is its key in
911        // `active_modes` — the same stand-in the registry uses.
912        if ctx.active_mode_of(&Id::NIL).is_some() && self.previous_operation_mode_id.is_none() {
913            out.push(
914                rules::PREVIOUS_MODE_MISSING,
915                path,
916                "this is not the first status, so the previous operation mode and the \
917                 transition timestamp should be present",
918            );
919        }
920        if let Some(system) = ctx.ombc
921            && system
922                .operation_mode(&self.active_operation_mode_id)
923                .is_none()
924        {
925            out.push_related(
926                rules::OMBC_UNKNOWN_MODE,
927                &child(path, "active_operation_mode_id"),
928                format!(
929                    "{} is not an operation mode of this system",
930                    self.active_operation_mode_id
931                ),
932                [self.active_operation_mode_id],
933            );
934        }
935    }
936}
937
938impl Validate for ombc::TimerStatus {
939    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
940        if let Some(system) = ctx.ombc
941            && system.timer(&self.timer_id).is_none()
942        {
943            out.push_related(
944                rules::UNKNOWN_TIMER,
945                &child(path, "timer_id"),
946                format!("{} is not a timer of this system", self.timer_id),
947                [self.timer_id],
948            );
949        }
950    }
951}
952
953impl Validate for ombc::Instruction {
954    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
955        check_factor(
956            self.operation_mode_factor,
957            &child(path, "operation_mode_factor"),
958            out,
959        );
960        check_scheduled(
961            self.execution_time,
962            &child(path, "execution_time"),
963            ctx,
964            out,
965        );
966        check_duplicate_instruction(self.id, path, ctx, out);
967
968        let Some(system) = ctx.ombc else { return };
969        let Some(mode) = system.operation_mode(&self.operation_mode_id) else {
970            out.push_related(
971                rules::OMBC_UNKNOWN_MODE,
972                &child(path, "operation_mode_id"),
973                format!(
974                    "{} is not an operation mode of this system",
975                    self.operation_mode_id
976                ),
977                [self.operation_mode_id],
978            );
979            return;
980        };
981        check_instruction_context(
982            &ModeCheck {
983                actuator: None,
984                mode: &self.operation_mode_id,
985                abnormal_condition: self.abnormal_condition,
986                abnormal_only: mode.abnormal_condition_only,
987                transitions: &system.transitions,
988                timers: &system.timers,
989            },
990            path,
991            ctx,
992            out,
993        );
994    }
995}
996
997// ---------------------------------------------------------------------------
998// DDBC
999// ---------------------------------------------------------------------------
1000
1001impl Validate for ddbc::SystemDescription {
1002    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1003        check_array(
1004            "DDBC.SystemDescription",
1005            "actuators",
1006            self.actuators.len(),
1007            path,
1008            out,
1009        );
1010        check_scheduled(self.valid_from, &child(path, "valid_from"), ctx, out);
1011        check_unique_ids(
1012            self.actuators.iter().map(|a| &a.id),
1013            "the Resource Manager",
1014            &child(path, "actuators"),
1015            out,
1016        );
1017        if let Some(rate) = self.present_demand_rate {
1018            check_range(rate, &child(path, "present_demand_rate"), out);
1019        }
1020        // The one field the two tagged versions of S2 JSON disagree about. The codec
1021        // enforces it on the way in; this is the same rule on the way out, so an
1022        // endpoint learns at its own call site rather than from a peer's refusal (E13).
1023        let carries = ctx.profile.ddbc_system_description_carries_demand_rate();
1024        match (carries, self.present_demand_rate.is_some()) {
1025            (true, false) => out.push(
1026                rules::PROFILE_FIELD,
1027                &child(path, "present_demand_rate"),
1028                format!("present_demand_rate is required in S2 JSON {}", ctx.profile),
1029            ),
1030            (false, true) => out.push(
1031                rules::PROFILE_FIELD,
1032                &child(path, "present_demand_rate"),
1033                format!(
1034                    "present_demand_rate was removed in S2 JSON {}; \
1035                     send DDBC.PresentDemandStatus instead",
1036                    ctx.profile
1037                ),
1038            ),
1039            _ => {}
1040        }
1041
1042        let at = child(path, "actuators");
1043        let mut publishes_costs = false;
1044        for (i, actuator) in self.actuators.iter().enumerate() {
1045            let actuator_path = index(&at, i);
1046            check_array(
1047                "DDBC.ActuatorDescription",
1048                "operation_modes",
1049                actuator.operation_modes.len(),
1050                &actuator_path,
1051                out,
1052            );
1053            check_array(
1054                "DDBC.ActuatorDescription",
1055                "supported_commodites",
1056                actuator.supported_commodities.len(),
1057                &actuator_path,
1058                out,
1059            );
1060            check_supported_commodities(
1061                &actuator.supported_commodities,
1062                // The wire spells it without the second `i` (erratum E5), and a JSON
1063                // pointer names the wire.
1064                "supported_commodites",
1065                &actuator_path,
1066                out,
1067            );
1068            check_unique_ids(
1069                actuator.operation_modes.iter().map(|m| &m.id),
1070                "this actuator",
1071                &child(&actuator_path, "operation_modes"),
1072                out,
1073            );
1074            // FRBC checks these; DDBC declares the same `timers` and `transitions` under
1075            // the same uniqueness sentence, so it checks them too.
1076            check_unique_ids(
1077                actuator.timers.iter().map(|t| &t.id),
1078                "this actuator",
1079                &child(&actuator_path, "timers"),
1080                out,
1081            );
1082            check_unique_ids(
1083                actuator.transitions.iter().map(|t| &t.id),
1084                "this actuator",
1085                &child(&actuator_path, "transitions"),
1086                out,
1087            );
1088
1089            let modes = child(&actuator_path, "operation_modes");
1090            for (j, mode) in actuator.operation_modes.iter().enumerate() {
1091                let mode_path = index(&modes, j);
1092                check_power_ranges(&mode.power_ranges, "DDBC.OperationMode", &mode_path, out);
1093                check_commodity_coverage(
1094                    &actuator.supported_commodities,
1095                    &mode.power_ranges,
1096                    &mode_path,
1097                    out,
1098                );
1099                check_interpolated(mode.supply_range, &child(&mode_path, "supply_range"), out);
1100                if let Some(running) = mode.running_costs {
1101                    check_interpolated(running, &child(&mode_path, "running_costs"), out);
1102                }
1103                publishes_costs |= mode.running_costs.is_some();
1104            }
1105
1106            let mode_ids: Vec<Id> = actuator.operation_modes.iter().map(|m| m.id).collect();
1107            let timer_ids: Vec<Id> = actuator.timers.iter().map(|t| t.id).collect();
1108            check_transitions(
1109                &actuator.transitions,
1110                &mode_ids,
1111                &timer_ids,
1112                rules::DDBC_TRANSITION_REFERENCES,
1113                &child(&actuator_path, "transitions"),
1114                out,
1115            );
1116            publishes_costs |= actuator
1117                .transitions
1118                .iter()
1119                .any(|t| t.transition_costs.is_some());
1120        }
1121        check_currency(publishes_costs, path, ctx, out);
1122    }
1123}
1124
1125impl Validate for ddbc::PresentDemandStatus {
1126    fn validate_at(&self, path: &str, _ctx: &Context<'_>, out: &mut Report) {
1127        check_range(
1128            self.present_demand_rate,
1129            &child(path, "present_demand_rate"),
1130            out,
1131        );
1132    }
1133}
1134
1135impl Validate for ddbc::ActuatorStatus {
1136    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1137        check_factor(
1138            self.operation_mode_factor,
1139            &child(path, "operation_mode_factor"),
1140            out,
1141        );
1142        if let Some(at) = self.transition_timestamp {
1143            check_observed(at, &child(path, "transition_timestamp"), ctx, out);
1144        }
1145        // Per actuator, not per session: an FRBC system may describe up to ten actuators,
1146        // and the first status of the second one is still a first status.
1147        if ctx.active_mode_of(&self.actuator_id).is_some()
1148            && self.previous_operation_mode_id.is_none()
1149        {
1150            out.push_related(
1151                rules::PREVIOUS_MODE_MISSING,
1152                path,
1153                format!(
1154                    "this is not the first status for actuator {}, so the previous \
1155                     operation mode and the transition timestamp should be present",
1156                    self.actuator_id
1157                ),
1158                [self.actuator_id],
1159            );
1160        }
1161        if let Some(system) = ctx.ddbc {
1162            match system.actuator(&self.actuator_id) {
1163                None => out.push_related(
1164                    rules::DDBC_UNKNOWN_ACTUATOR,
1165                    &child(path, "actuator_id"),
1166                    format!("{} is not an actuator of this system", self.actuator_id),
1167                    [self.actuator_id],
1168                ),
1169                Some(actuator)
1170                    if actuator
1171                        .operation_mode(&self.active_operation_mode_id)
1172                        .is_none() =>
1173                {
1174                    out.push_related(
1175                        rules::DDBC_UNKNOWN_MODE,
1176                        &child(path, "active_operation_mode_id"),
1177                        format!(
1178                            "{} is not an operation mode of actuator {}",
1179                            self.active_operation_mode_id, self.actuator_id
1180                        ),
1181                        [self.active_operation_mode_id],
1182                    );
1183                }
1184                Some(_) => {}
1185            }
1186        }
1187    }
1188}
1189
1190impl Validate for ddbc::TimerStatus {
1191    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1192        if let Some(system) = ctx.ddbc {
1193            match system.actuator(&self.actuator_id) {
1194                None => out.push_related(
1195                    rules::DDBC_UNKNOWN_ACTUATOR,
1196                    &child(path, "actuator_id"),
1197                    format!("{} is not an actuator of this system", self.actuator_id),
1198                    [self.actuator_id],
1199                ),
1200                Some(actuator) if actuator.timer(&self.timer_id).is_none() => out.push_related(
1201                    rules::UNKNOWN_TIMER,
1202                    &child(path, "timer_id"),
1203                    format!(
1204                        "{} is not a timer of actuator {}",
1205                        self.timer_id, self.actuator_id
1206                    ),
1207                    [self.timer_id],
1208                ),
1209                Some(_) => {}
1210            }
1211        }
1212    }
1213}
1214
1215impl Validate for ddbc::AverageDemandRateForecast {
1216    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1217        check_array(
1218            "DDBC.AverageDemandRateForecast",
1219            "elements",
1220            self.elements.len(),
1221            path,
1222            out,
1223        );
1224        check_scheduled(self.start_time, &child(path, "start_time"), ctx, out);
1225        let at = child(path, "elements");
1226        for (i, element) in self.elements.iter().enumerate() {
1227            check_percentiles(&element.bands_ascending(), &index(&at, i), out);
1228        }
1229        if let Some(system) = ctx.ddbc
1230            && !system.provides_average_demand_rate_forecast
1231        {
1232            out.push(
1233                rules::DDBC_FORECAST_NOT_OFFERED,
1234                path,
1235                "the system description said provides_average_demand_rate_forecast is false",
1236            );
1237        }
1238    }
1239}
1240
1241impl Validate for ddbc::Instruction {
1242    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1243        check_factor(
1244            self.operation_mode_factor,
1245            &child(path, "operation_mode_factor"),
1246            out,
1247        );
1248        check_scheduled(
1249            self.execution_time,
1250            &child(path, "execution_time"),
1251            ctx,
1252            out,
1253        );
1254        check_duplicate_instruction(self.id, path, ctx, out);
1255
1256        let Some(system) = ctx.ddbc else { return };
1257        let Some(actuator) = system.actuator(&self.actuator_id) else {
1258            out.push_related(
1259                rules::DDBC_UNKNOWN_ACTUATOR,
1260                &child(path, "actuator_id"),
1261                format!("{} is not an actuator of this system", self.actuator_id),
1262                [self.actuator_id],
1263            );
1264            return;
1265        };
1266        let Some(mode) = actuator.operation_mode(&self.operation_mode_id) else {
1267            out.push_related(
1268                rules::DDBC_UNKNOWN_MODE,
1269                &child(path, "operation_mode_id"),
1270                format!(
1271                    "{} is not an operation mode of actuator {}",
1272                    self.operation_mode_id, self.actuator_id
1273                ),
1274                [self.operation_mode_id],
1275            );
1276            return;
1277        };
1278        check_instruction_context(
1279            &ModeCheck {
1280                actuator: Some(&self.actuator_id),
1281                mode: &self.operation_mode_id,
1282                abnormal_condition: self.abnormal_condition,
1283                abnormal_only: mode.abnormal_condition_only,
1284                transitions: &actuator.transitions,
1285                timers: &actuator.timers,
1286            },
1287            path,
1288            ctx,
1289            out,
1290        );
1291    }
1292}
1293
1294// ---------------------------------------------------------------------------
1295// PEBC
1296// ---------------------------------------------------------------------------
1297
1298impl Validate for pebc::PowerConstraints {
1299    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1300        check_array(
1301            "PEBC.PowerConstraints",
1302            "allowed_limit_ranges",
1303            self.allowed_limit_ranges.len(),
1304            path,
1305            out,
1306        );
1307        check_scheduled(self.valid_from, &child(path, "valid_from"), ctx, out);
1308
1309        if let Some(until) = self.valid_until
1310            && until < self.valid_from
1311        {
1312            out.push(
1313                rules::PEBC_VALIDITY_WINDOW,
1314                &child(path, "valid_until"),
1315                format!("{until} is before valid_from {}", self.valid_from),
1316            );
1317        }
1318
1319        let at = child(path, "allowed_limit_ranges");
1320        for (i, range) in self.allowed_limit_ranges.iter().enumerate() {
1321            check_range(
1322                range.range_boundary,
1323                &child(&index(&at, i), "range_boundary"),
1324                out,
1325            );
1326        }
1327
1328        let has_upper = self
1329            .allowed_limit_ranges
1330            .iter()
1331            .any(|r| r.limit_type == pebc::PowerEnvelopeLimitType::UpperLimit);
1332        let has_lower = self
1333            .allowed_limit_ranges
1334            .iter()
1335            .any(|r| r.limit_type == pebc::PowerEnvelopeLimitType::LowerLimit);
1336        if !has_upper || !has_lower {
1337            out.push(
1338                rules::PEBC_BOTH_LIMITS,
1339                &at,
1340                "there must be at least one UPPER_LIMIT range and at least one LOWER_LIMIT range",
1341            );
1342        }
1343    }
1344}
1345
1346impl Validate for pebc::EnergyConstraint {
1347    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1348        check_finite(
1349            self.upper_average_power,
1350            &child(path, "upper_average_power"),
1351            out,
1352        );
1353        check_finite(
1354            self.lower_average_power,
1355            &child(path, "lower_average_power"),
1356            out,
1357        );
1358        check_scheduled(self.valid_from, &child(path, "valid_from"), ctx, out);
1359
1360        if self.valid_until < self.valid_from {
1361            out.push(
1362                rules::PEBC_VALIDITY_WINDOW,
1363                &child(path, "valid_until"),
1364                format!(
1365                    "{} is before valid_from {}",
1366                    self.valid_until, self.valid_from
1367                ),
1368            );
1369        }
1370        if self.lower_average_power.is_finite()
1371            && self.upper_average_power.is_finite()
1372            && self.lower_average_power > self.upper_average_power
1373        {
1374            out.push(
1375                rules::PEBC_ENERGY_ORDER,
1376                path,
1377                format!(
1378                    "lower_average_power {} is above upper_average_power {}",
1379                    self.lower_average_power, self.upper_average_power
1380                ),
1381            );
1382        }
1383    }
1384}
1385
1386impl Validate for pebc::Instruction {
1387    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1388        check_array(
1389            "PEBC.Instruction",
1390            "power_envelopes",
1391            self.power_envelopes.len(),
1392            path,
1393            out,
1394        );
1395        check_scheduled(
1396            self.execution_time,
1397            &child(path, "execution_time"),
1398            ctx,
1399            out,
1400        );
1401        check_duplicate_instruction(self.id, path, ctx, out);
1402
1403        let at = child(path, "power_envelopes");
1404        let mut seen: Vec<CommodityQuantity> = Vec::new();
1405        for (i, envelope) in self.power_envelopes.iter().enumerate() {
1406            let envelope_path = index(&at, i);
1407            if seen.contains(&envelope.commodity_quantity) {
1408                out.push(
1409                    rules::PEBC_ONE_ENVELOPE_PER_QUANTITY,
1410                    &child(&envelope_path, "commodity_quantity"),
1411                    format!(
1412                        "{:?} already has an envelope in this instruction",
1413                        envelope.commodity_quantity
1414                    ),
1415                );
1416            } else {
1417                seen.push(envelope.commodity_quantity);
1418            }
1419            check_array(
1420                "PEBC.PowerEnvelope",
1421                "power_envelope_elements",
1422                envelope.power_envelope_elements.len(),
1423                &envelope_path,
1424                out,
1425            );
1426            let elements = child(&envelope_path, "power_envelope_elements");
1427            for (j, element) in envelope.power_envelope_elements.iter().enumerate() {
1428                let element_path = index(&elements, j);
1429                check_finite(
1430                    element.lower_limit,
1431                    &child(&element_path, "lower_limit"),
1432                    out,
1433                );
1434                check_finite(
1435                    element.upper_limit,
1436                    &child(&element_path, "upper_limit"),
1437                    out,
1438                );
1439                if element.lower_limit.is_finite()
1440                    && element.upper_limit.is_finite()
1441                    && element.lower_limit > element.upper_limit
1442                {
1443                    out.push(
1444                        rules::PEBC_ENVELOPE_LIMIT_ORDER,
1445                        &element_path,
1446                        format!(
1447                            "lower_limit {} is above upper_limit {}",
1448                            element.lower_limit, element.upper_limit
1449                        ),
1450                    );
1451                }
1452            }
1453        }
1454
1455        let Some(constraints) = ctx
1456            .pebc_constraints
1457            .iter()
1458            .find(|c| c.id == self.power_constraints_id)
1459        else {
1460            if !ctx.pebc_constraints.is_empty() {
1461                out.push_related(
1462                    rules::PEBC_UNKNOWN_CONSTRAINTS,
1463                    &child(path, "power_constraints_id"),
1464                    format!(
1465                        "{} names no PEBC.PowerConstraints published on this session",
1466                        self.power_constraints_id
1467                    ),
1468                    [self.power_constraints_id],
1469                );
1470            }
1471            return;
1472        };
1473
1474        if let Some(now) = ctx.now
1475            && !constraints.is_valid_at(now)
1476        {
1477            out.push_related(
1478                rules::PEBC_UNKNOWN_CONSTRAINTS,
1479                &child(path, "power_constraints_id"),
1480                format!("{} is not in force at {now}", constraints.id),
1481                [constraints.id],
1482            );
1483        }
1484
1485        for (i, envelope) in self.power_envelopes.iter().enumerate() {
1486            let elements = child(&index(&at, i), "power_envelope_elements");
1487            for (j, element) in envelope.power_envelope_elements.iter().enumerate() {
1488                let element_path = index(&elements, j);
1489                check_within_allowed(
1490                    constraints,
1491                    envelope.commodity_quantity,
1492                    pebc::PowerEnvelopeLimitType::UpperLimit,
1493                    element.upper_limit,
1494                    self.abnormal_condition,
1495                    &child(&element_path, "upper_limit"),
1496                    out,
1497                );
1498                check_within_allowed(
1499                    constraints,
1500                    envelope.commodity_quantity,
1501                    pebc::PowerEnvelopeLimitType::LowerLimit,
1502                    element.lower_limit,
1503                    self.abnormal_condition,
1504                    &child(&element_path, "lower_limit"),
1505                    out,
1506                );
1507            }
1508        }
1509    }
1510}
1511
1512fn check_within_allowed(
1513    constraints: &pebc::PowerConstraints,
1514    quantity: CommodityQuantity,
1515    limit_type: pebc::PowerEnvelopeLimitType,
1516    value: f64,
1517    abnormal_condition: bool,
1518    path: &str,
1519    out: &mut Report,
1520) {
1521    if !value.is_finite() {
1522        return;
1523    }
1524    let mut any = false;
1525    let mut fits = false;
1526    let mut needs_abnormal = false;
1527    for range in constraints.ranges_for(quantity, limit_type) {
1528        any = true;
1529        if range.range_boundary.contains(value) {
1530            if range.abnormal_condition_only && !abnormal_condition {
1531                needs_abnormal = true;
1532            } else {
1533                fits = true;
1534            }
1535        }
1536    }
1537    if !any {
1538        out.push(
1539            rules::PEBC_OUTSIDE_ALLOWED,
1540            path,
1541            format!(
1542                "the constraints allow no {limit_type:?} for {}",
1543                quantity.as_str()
1544            ),
1545        );
1546    } else if !fits {
1547        if needs_abnormal {
1548            out.push(
1549                rules::ABNORMAL_ONLY,
1550                path,
1551                format!(
1552                    "{value} is only allowed by a range marked abnormal_condition_only, \
1553                     and this instruction is not one"
1554                ),
1555            );
1556        } else {
1557            out.push(
1558                rules::PEBC_OUTSIDE_ALLOWED,
1559                path,
1560                format!(
1561                    "{value} is outside every allowed {limit_type:?} range for {}",
1562                    quantity.as_str()
1563                ),
1564            );
1565        }
1566    }
1567}
1568
1569// ---------------------------------------------------------------------------
1570// PPBC
1571// ---------------------------------------------------------------------------
1572
1573impl Validate for ppbc::PowerProfileDefinition {
1574    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1575        check_array(
1576            "PPBC.PowerProfileDefinition",
1577            "power_sequences_containers",
1578            self.power_sequence_containers.len(),
1579            path,
1580            out,
1581        );
1582        check_scheduled(self.start_time, &child(path, "start_time"), ctx, out);
1583
1584        if self.end_time < self.start_time {
1585            out.push(
1586                rules::PPBC_WINDOW,
1587                &child(path, "end_time"),
1588                format!("{} is before start_time {}", self.end_time, self.start_time),
1589            );
1590        }
1591
1592        check_unique_ids(
1593            self.power_sequence_containers.iter().map(|c| &c.id),
1594            "this profile",
1595            &child(path, "power_sequences_containers"),
1596            out,
1597        );
1598
1599        let at = child(path, "power_sequences_containers");
1600        let window = self
1601            .end_time
1602            .checked_duration_since(self.start_time)
1603            .unwrap_or(crate::types::Duration::ZERO);
1604        // The best case for the whole task: the shortest sequence of every container,
1605        // run back to back. `None` once anything overflows or a container is empty.
1606        let mut shortest_total = Some(crate::types::Duration::ZERO);
1607        for (i, container) in self.power_sequence_containers.iter().enumerate() {
1608            let container_path = index(&at, i);
1609            check_array(
1610                "PPBC.PowerSequenceContainer",
1611                "power_sequences",
1612                container.power_sequences.len(),
1613                &container_path,
1614                out,
1615            );
1616            check_unique_ids(
1617                container.power_sequences.iter().map(|s| &s.id),
1618                "this container",
1619                &child(&container_path, "power_sequences"),
1620                out,
1621            );
1622
1623            let sequences = child(&container_path, "power_sequences");
1624            let mut shortest: Option<crate::types::Duration> = None;
1625            for (j, sequence) in container.power_sequences.iter().enumerate() {
1626                let sequence_path = index(&sequences, j);
1627                check_array(
1628                    "PPBC.PowerSequence",
1629                    "elements",
1630                    sequence.elements.len(),
1631                    &sequence_path,
1632                    out,
1633                );
1634                let elements = child(&sequence_path, "elements");
1635                for (k, element) in sequence.elements.iter().enumerate() {
1636                    check_forecast_values(
1637                        &element.power_values,
1638                        "PPBC.PowerSequenceElement",
1639                        &index(&elements, k),
1640                        out,
1641                    );
1642                }
1643                let total = sequence.total_duration();
1644                shortest = Some(shortest.map_or(total, |s| if total < s { total } else { s }));
1645            }
1646            if let Some(shortest) = shortest
1647                && shortest.as_millis() > window.as_millis()
1648            {
1649                out.push(
1650                    rules::PPBC_WINDOW_TOO_SHORT,
1651                    &container_path,
1652                    format!(
1653                        "the shortest sequence takes {shortest} but the window is only {window}"
1654                    ),
1655                );
1656            }
1657            shortest_total = shortest_total
1658                .zip(shortest)
1659                .and_then(|(total, s)| total.checked_add(s));
1660        }
1661
1662        // Containers run **in the order the profile lists them**
1663        // (`S2J messages/PPBC.PowerProfileDefinition.power_sequences_containers`), so the
1664        // window has to hold all of them end to end, not merely the longest one. Three
1665        // one-hour containers in a two-hour window is a task no CEM can schedule, and
1666        // checking each container against the whole window sees nothing wrong with it —
1667        // which is the same mistake `model::schedule` exists to avoid (D32).
1668        if let Some(total) = shortest_total
1669            && total.as_millis() > window.as_millis()
1670            && self.power_sequence_containers.len() > 1
1671        {
1672            out.push(
1673                rules::PPBC_WINDOW_TOO_SHORT,
1674                &at,
1675                format!(
1676                    "the containers run in order, so the shortest way to run all {} takes \
1677                     {total}, but the window is only {window}",
1678                    self.power_sequence_containers.len()
1679                ),
1680            );
1681        }
1682    }
1683}
1684
1685impl Validate for ppbc::PowerProfileStatus {
1686    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1687        check_array(
1688            "PPBC.PowerProfileStatus",
1689            "sequence_container_status",
1690            self.sequence_container_status.len(),
1691            path,
1692            out,
1693        );
1694        let at = child(path, "sequence_container_status");
1695        for (i, status) in self.sequence_container_status.iter().enumerate() {
1696            let status_path = index(&at, i);
1697            // Three separate conditions, three separate identifiers. The standard states
1698            // one of them plainly, infers the second and states the third the other way
1699            // round, so they cannot share a severity — nor a number a fleet counts (D28).
1700            let started = status.status.has_started();
1701            match (started, status.progress) {
1702                (true, None) => out.push(
1703                    rules::PPBC_PROGRESS,
1704                    &status_path,
1705                    format!(
1706                        "{:?} means the selected sequence has started, so progress must be present",
1707                        status.status
1708                    ),
1709                ),
1710                // "must be provided, unless …" permits omission; it does not forbid
1711                // presence. A warning, so a conforming peer is not refused (D4).
1712                (false, Some(_)) => out.push(
1713                    rules::PPBC_PROGRESS_UNEXPECTED,
1714                    &child(&status_path, "progress"),
1715                    format!(
1716                        "{:?} means nothing has started yet, so progress says nothing",
1717                        status.status
1718                    ),
1719                ),
1720                _ => {}
1721            }
1722            if status.status.has_selection() && status.selected_sequence_id.is_none() {
1723                out.push(
1724                    rules::PPBC_SEQUENCE_NOT_NAMED,
1725                    &status_path,
1726                    format!(
1727                        "{:?} means a sequence was chosen, so selected_sequence_id must be present",
1728                        status.status
1729                    ),
1730                );
1731            }
1732        }
1733
1734        // "Array with status information for all PPBC.PowerSequenceContainers".
1735        for profile in ctx.ppbc_profiles {
1736            if !self
1737                .sequence_container_status
1738                .iter()
1739                .any(|s| s.power_profile_id == profile.id)
1740            {
1741                continue;
1742            }
1743            for container in &profile.power_sequence_containers {
1744                if !self.sequence_container_status.iter().any(|s| {
1745                    s.power_profile_id == profile.id && s.sequence_container_id == container.id
1746                }) {
1747                    out.push_related(
1748                        rules::PPBC_STATUS_COVERAGE,
1749                        &at,
1750                        format!(
1751                            "container {} of profile {} has no status",
1752                            container.id, profile.id
1753                        ),
1754                        [container.id],
1755                    );
1756                }
1757            }
1758        }
1759    }
1760}
1761
1762/// The three PPBC instructions differ only in what they do to the sequence they name.
1763#[allow(clippy::too_many_arguments)] // three identifiers, a flag, a path, a context and a report
1764fn check_ppbc_instruction(
1765    id: Id,
1766    profile_id: Id,
1767    container_id: Id,
1768    sequence_id: Id,
1769    needs_interruptible: bool,
1770    path: &str,
1771    ctx: &Context<'_>,
1772    out: &mut Report,
1773) {
1774    check_duplicate_instruction(id, path, ctx, out);
1775
1776    if ctx.ppbc_profiles.is_empty() {
1777        return;
1778    }
1779    let Some(profile) = ctx.ppbc_profiles.iter().find(|p| p.id == profile_id) else {
1780        out.push_related(
1781            rules::PPBC_UNKNOWN_SEQUENCE,
1782            &child(path, "power_profile_id"),
1783            format!("{profile_id} names no profile published on this session"),
1784            [profile_id],
1785        );
1786        return;
1787    };
1788    let Some((_, sequence)) = profile.resolve(&container_id, &sequence_id) else {
1789        out.push_related(
1790            rules::PPBC_UNKNOWN_SEQUENCE,
1791            path,
1792            format!(
1793                "profile {profile_id} has no sequence {sequence_id} in container {container_id}"
1794            ),
1795            [container_id, sequence_id],
1796        );
1797        return;
1798    };
1799    if needs_interruptible && !sequence.is_interruptible {
1800        out.push_related(
1801            rules::PPBC_NOT_INTERRUPTIBLE,
1802            path,
1803            format!("sequence {sequence_id} says is_interruptible is false"),
1804            [sequence_id],
1805        );
1806    }
1807}
1808
1809impl Validate for ppbc::ScheduleInstruction {
1810    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1811        check_scheduled(
1812            self.execution_time,
1813            &child(path, "execution_time"),
1814            ctx,
1815            out,
1816        );
1817        check_ppbc_instruction(
1818            self.id,
1819            self.power_profile_id,
1820            self.sequence_container_id,
1821            self.power_sequence_id,
1822            false,
1823            path,
1824            ctx,
1825            out,
1826        );
1827    }
1828}
1829
1830impl Validate for ppbc::StartInterruptionInstruction {
1831    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1832        check_scheduled(
1833            self.execution_time,
1834            &child(path, "execution_time"),
1835            ctx,
1836            out,
1837        );
1838        check_ppbc_instruction(
1839            self.id,
1840            self.power_profile_id,
1841            self.sequence_container_id,
1842            self.power_sequence_id,
1843            true,
1844            path,
1845            ctx,
1846            out,
1847        );
1848    }
1849}
1850
1851impl Validate for ppbc::EndInterruptionInstruction {
1852    fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report) {
1853        check_scheduled(
1854            self.execution_time,
1855            &child(path, "execution_time"),
1856            ctx,
1857            out,
1858        );
1859        check_ppbc_instruction(
1860            self.id,
1861            self.power_profile_id,
1862            self.sequence_container_id,
1863            self.power_sequence_id,
1864            true,
1865            path,
1866            ctx,
1867            out,
1868        );
1869    }
1870}
1871
1872fn check_duplicate_instruction(id: Id, path: &str, ctx: &Context<'_>, out: &mut Report) {
1873    if ctx.instructions.contains(&id) {
1874        out.push_related(
1875            rules::DUPLICATE_INSTRUCTION_ID,
1876            &child(path, "id"),
1877            format!("instruction {id} has already been sent on this session"),
1878            [id],
1879        );
1880    }
1881}