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