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