Skip to main content

s2_kit/
testing.rs

1//! A harness for driving both engines against each other, on a virtual clock.
2//!
3//! Because the sessions are deterministic and take `now` as a parameter, a whole
4//! conversation — handshake, control-type selection, a description, an instruction, a
5//! lost acknowledgement, a timer expiring — is an ordinary unit test that runs in
6//! microseconds. [`Conversation`] wires a [`RmSession`] and a [`CemSession`] back to
7//! back through an in-memory pipe and records everything that crosses it.
8//!
9//! **Every message crosses the wire format on the way**, so what is under test is the
10//! encoding as well as the logic.
11//!
12//! ```
13//! use s2_kit::prelude::*;
14//! use s2_kit::testing::Conversation;
15//!
16//! let mut c = Conversation::battery();
17//! c.open();
18//! assert!(matches!(c.cem.state(), SessionState::Connected));
19//! assert!(c.cem.details().is_some(), "the resource described itself");
20//! ```
21
22use alloc::format;
23use alloc::string::{String, ToString};
24use alloc::vec::Vec;
25
26use crate::message::{Message, MessageKind};
27use crate::session::{
28    Analyzer, CemConfig, CemEvent, CemSession, Instructed, RmConfig, RmEvent, RmSession,
29};
30use crate::types::common::{
31    Commodity, CommodityQuantity, ControlType, Currency, EnergyManagementRole, Handshake,
32    HandshakeResponse, InstructionStatus, InstructionStatusUpdate, NumberRange, PowerForecast,
33    PowerForecastElement, PowerForecastValue, PowerMeasurement, PowerRange, PowerValue,
34    ReceptionStatus, ReceptionStatusValues, ResourceManagerDetails, RevokableObjects, RevokeObject,
35    Role, RoleType, SelectControlType, SessionRequest, SessionRequestType, Timer, Transition,
36};
37use crate::types::{Duration, Id, ProtocolVersion, Timestamp, ddbc, frbc, ombc, pebc, ppbc};
38use crate::validate::Severity;
39
40/// Which way a message went.
41///
42/// Ordered so that a transcript index can be sorted and binary-searched by
43/// `(direction, message_id)`; the order itself means nothing.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
45pub enum Direction {
46    /// From the Customer Energy Manager to the Resource Manager.
47    CemToRm,
48    /// From the Resource Manager to the Customer Energy Manager.
49    RmToCem,
50}
51
52impl Direction {
53    /// The other way.
54    ///
55    /// An acknowledgement always travels against the message it answers, which is the
56    /// one thing every lookup in [`replay`] needs.
57    #[must_use]
58    pub const fn other(self) -> Self {
59        match self {
60            Direction::CemToRm => Direction::RmToCem,
61            Direction::RmToCem => Direction::CemToRm,
62        }
63    }
64
65    /// The short form used in a transcript file.
66    #[must_use]
67    pub const fn as_str(self) -> &'static str {
68        match self {
69            Direction::CemToRm => "cem>rm",
70            Direction::RmToCem => "rm>cem",
71        }
72    }
73}
74
75/// One line of a `.s2log` transcript.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct TranscriptEntry {
78    /// When it was sent, on the conversation's clock.
79    pub at: Timestamp,
80    /// Which way.
81    pub direction: Direction,
82    /// What it was.
83    pub kind: MessageKind,
84    /// The bytes.
85    pub text: String,
86}
87
88impl Direction {
89    /// The role that sent a message going this way.
90    #[must_use]
91    pub const fn sender(self) -> crate::types::common::EnergyManagementRole {
92        match self {
93            Direction::CemToRm => crate::types::common::EnergyManagementRole::Cem,
94            Direction::RmToCem => crate::types::common::EnergyManagementRole::Rm,
95        }
96    }
97
98    /// The direction a transcript line's `dir` field names.
99    #[must_use]
100    pub fn parse(s: &str) -> Option<Self> {
101        match s {
102            "cem>rm" => Some(Direction::CemToRm),
103            "rm>cem" => Some(Direction::RmToCem),
104            _ => None,
105        }
106    }
107}
108
109impl TranscriptEntry {
110    /// The entry as one line of JSON Lines.
111    #[must_use]
112    pub fn to_jsonl(&self) -> String {
113        format!(
114            r#"{{"t":"{}","dir":"{}","msg":{}}}"#,
115            self.at,
116            self.direction.as_str(),
117            self.text
118        )
119    }
120
121    /// Read one line of a `.s2log` back.
122    ///
123    /// The inverse of [`to_jsonl`](Self::to_jsonl). `None` for a line that is not one — a
124    /// blank line, a comment, or a record from some other tool.
125    #[must_use]
126    pub fn from_jsonl(line: &str) -> Option<Self> {
127        let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
128        let at = value.get("t")?.as_str()?.parse().ok()?;
129        let direction = Direction::parse(value.get("dir")?.as_str()?)?;
130        let text = value.get("msg")?.to_string();
131        // The kind is derived rather than stored: a transcript records what crossed the
132        // wire, and a `message_type` the reader does not know is exactly the thing a
133        // replay must be able to report rather than refuse to load.
134        let kind = crate::codec::peek(&text).ok().and_then(|p| p.kind)?;
135        Some(Self {
136            at,
137            direction,
138            kind,
139            text,
140        })
141    }
142}
143
144/// Read a whole `.s2log`, skipping anything that is not a transcript line.
145#[must_use]
146pub fn read_s2log(text: &str) -> Vec<TranscriptEntry> {
147    text.lines()
148        .filter_map(TranscriptEntry::from_jsonl)
149        .collect()
150}
151
152/// A Resource Manager and a Customer Energy Manager, talking to each other.
153pub struct Conversation {
154    /// The resource's side.
155    pub rm: RmSession,
156    /// The manager's side.
157    pub cem: CemSession,
158    /// The virtual clock.
159    pub now: Timestamp,
160    transcript: Vec<TranscriptEntry>,
161    rm_events: Vec<RmEvent>,
162    cem_events: Vec<CemEvent>,
163}
164
165impl Conversation {
166    /// A conversation between the given two configurations.
167    #[must_use]
168    pub fn new(
169        rm_config: RmConfig,
170        details: ResourceManagerDetails,
171        cem_config: CemConfig,
172    ) -> Self {
173        Self {
174            rm: RmSession::new(rm_config, details),
175            cem: CemSession::new(cem_config),
176            now: "2024-01-01T12:00:00Z"
177                .parse()
178                .unwrap_or(Timestamp::UNIX_EPOCH),
179            transcript: Vec::new(),
180            rm_events: Vec::new(),
181            cem_events: Vec::new(),
182        }
183    }
184
185    /// A conversation with a 20 kWh home battery, the FRBC example implementation.
186    #[must_use]
187    pub fn battery() -> Self {
188        Self::new(RmConfig::default(), battery_details(), CemConfig::default())
189    }
190
191    /// A conversation with a 4 kWp curtailable PV inverter, the PEBC example.
192    #[must_use]
193    pub fn pv() -> Self {
194        Self::new(RmConfig::default(), pv_details(), CemConfig::default())
195    }
196
197    /// Open both sides and run the conversation until it goes quiet.
198    pub fn open(&mut self) {
199        self.rm.open(self.now);
200        self.cem.open(self.now);
201        self.pump();
202    }
203
204    /// Deliver everything either side wants to send, until neither has anything left.
205    ///
206    /// Bounded, so a session that answers its own answers cannot hang a test.
207    ///
208    /// # Panics
209    ///
210    /// When the conversation does not settle within a thousand rounds, which means one
211    /// of the engines is acknowledging acknowledgements.
212    #[allow(clippy::panic)] // a test harness that hangs is worse than one that fails
213    pub fn pump(&mut self) {
214        for _ in 0..1000 {
215            let mut moved = false;
216            while let Some(out) = self.rm.poll_transmit() {
217                self.record(Direction::RmToCem, out.kind, &out.text);
218                self.cem.handle_text(&out.text, self.now);
219                moved = true;
220            }
221            while let Some(out) = self.cem.poll_transmit() {
222                self.record(Direction::CemToRm, out.kind, &out.text);
223                self.rm.handle_text(&out.text, self.now);
224                moved = true;
225            }
226            self.drain_events();
227            if !moved {
228                return;
229            }
230        }
231        panic!("the conversation did not settle: a session is answering its own answers");
232    }
233
234    fn record(&mut self, direction: Direction, kind: MessageKind, text: &str) {
235        self.transcript.push(TranscriptEntry {
236            at: self.now,
237            direction,
238            kind,
239            text: text.to_string(),
240        });
241    }
242
243    fn drain_events(&mut self) {
244        while let Some(event) = self.rm.poll_event() {
245            self.rm_events.push(event);
246        }
247        while let Some(event) = self.cem.poll_event() {
248            self.cem_events.push(event);
249        }
250    }
251
252    /// Move the clock forward, letting both sides notice.
253    pub fn advance(&mut self, by: Duration) {
254        self.now = self.now.checked_add(by).unwrap_or(self.now);
255        self.rm.handle_timeout(self.now);
256        self.cem.handle_timeout(self.now);
257        self.pump();
258    }
259
260    /// Move the clock forward without delivering anything, so that a message can be
261    /// dropped on the floor.
262    pub fn advance_silently(&mut self, by: Duration) {
263        self.now = self.now.checked_add(by).unwrap_or(self.now);
264        self.rm.handle_timeout(self.now);
265        self.cem.handle_timeout(self.now);
266        self.drain_events();
267    }
268
269    /// Throw away everything the Resource Manager is trying to say, as a lost
270    /// connection would.
271    pub fn drop_rm_traffic(&mut self) {
272        while self.rm.poll_transmit().is_some() {}
273        self.drain_events();
274    }
275
276    /// Throw away everything the manager is trying to say.
277    pub fn drop_cem_traffic(&mut self) {
278        while self.cem.poll_transmit().is_some() {}
279        self.drain_events();
280    }
281
282    /// Everything that has crossed the wire.
283    #[must_use]
284    pub fn transcript(&self) -> &[TranscriptEntry] {
285        &self.transcript
286    }
287
288    /// The transcript as a `.s2log` file.
289    #[must_use]
290    pub fn to_s2log(&self) -> String {
291        let mut out = String::new();
292        for entry in &self.transcript {
293            out.push_str(&entry.to_jsonl());
294            out.push('\n');
295        }
296        out
297    }
298
299    /// Every message type that has crossed, in order.
300    #[must_use]
301    pub fn flow(&self) -> Vec<(Direction, MessageKind)> {
302        self.transcript
303            .iter()
304            .map(|e| (e.direction, e.kind))
305            .collect()
306    }
307
308    /// Every message type that has crossed, ignoring the acknowledgements.
309    #[must_use]
310    pub fn flow_without_acks(&self) -> Vec<(Direction, MessageKind)> {
311        self.flow()
312            .into_iter()
313            .filter(|(_, kind)| *kind != MessageKind::ReceptionStatus)
314            .collect()
315    }
316
317    /// Everything the Resource Manager has reported, clearing the list.
318    pub fn take_rm_events(&mut self) -> Vec<RmEvent> {
319        self.drain_events();
320        core::mem::take(&mut self.rm_events)
321    }
322
323    /// Everything the manager has reported, clearing the list.
324    pub fn take_cem_events(&mut self) -> Vec<CemEvent> {
325        self.drain_events();
326        core::mem::take(&mut self.cem_events)
327    }
328
329    /// The first instruction the Resource Manager was handed, if any.
330    pub fn first_instruction(&mut self) -> Option<Instructed> {
331        self.drain_events();
332        self.rm_events.iter().find_map(|e| match e {
333            RmEvent::Instruction(i) => Some((**i).clone()),
334            _ => None,
335        })
336    }
337
338    /// Whether either side refused anything.
339    #[must_use]
340    pub fn refusals(&self) -> Vec<String> {
341        let mut out = Vec::new();
342        for event in &self.rm_events {
343            if let RmEvent::Refused { report, .. } = event {
344                out.push(format!("RM refused: {report}"));
345            }
346        }
347        for event in &self.cem_events {
348            if let CemEvent::Refused { report, .. } = event {
349                out.push(format!("CEM refused: {report}"));
350            }
351        }
352        out
353    }
354
355    /// Assert that nothing was refused. The message names what was.
356    ///
357    /// # Panics
358    ///
359    /// When either side refused a message.
360    pub fn assert_no_refusals(&self) {
361        let refusals = self.refusals();
362        assert!(refusals.is_empty(), "{refusals:#?}");
363    }
364}
365
366// ---------------------------------------------------------------------------
367// Fixtures
368// ---------------------------------------------------------------------------
369
370/// The 20 kWh home battery from `s2-example-implementations`.
371#[must_use]
372pub fn battery_details() -> ResourceManagerDetails {
373    ResourceManagerDetails {
374        message_id: Id::new_const("rmd-battery"),
375        resource_id: Id::new_const("acme_battery_1"),
376        name: Some("Home battery".into()),
377        roles: alloc::vec![Role::new(RoleType::EnergyStorage, Commodity::Electricity)],
378        manufacturer: Some("ACME".into()),
379        model: Some("Powerwall-ish".into()),
380        serial_number: Some("123".into()),
381        firmware_version: Some("v1.0".into()),
382        instruction_processing_delay: Duration::from_millis(500),
383        available_control_types: alloc::vec![ControlType::FillRateBasedControl],
384        currency: None,
385        provides_forecast: false,
386        provides_power_measurement_types: alloc::vec![
387            CommodityQuantity::ElectricPower3PhaseSymmetric
388        ],
389    }
390}
391
392/// A battery's system description: charge, idle and discharge over a 0–100 % store.
393#[must_use]
394pub fn battery_system(valid_from: Timestamp) -> frbc::SystemDescription {
395    let mode =
396        |id: &'static str, label: &str, rate: NumberRange, power: PowerRange| frbc::OperationMode {
397            id: Id::new_const(id),
398            diagnostic_label: Some(label.to_string()),
399            elements: alloc::vec![frbc::OperationModeElement {
400                fill_level_range: NumberRange::new(0.0, 100.0),
401                fill_rate: rate,
402                power_ranges: alloc::vec![power],
403                running_costs: None,
404            }],
405            abnormal_condition_only: false,
406        };
407    let q = CommodityQuantity::ElectricPower3PhaseSymmetric;
408    frbc::SystemDescription {
409        message_id: Id::new_const("frbc-system-1"),
410        valid_from,
411        actuators: alloc::vec![frbc::ActuatorDescription {
412            id: Id::new_const("actuator1"),
413            diagnostic_label: Some("Battery inverter".into()),
414            supported_commodities: alloc::vec![Commodity::Electricity],
415            operation_modes: alloc::vec![
416                mode(
417                    "idle",
418                    "Idle",
419                    NumberRange::exactly(0.0),
420                    PowerRange::exactly(0.0, q)
421                ),
422                mode(
423                    "charge",
424                    "Charging",
425                    NumberRange::new(0.0, 0.0025),
426                    PowerRange::new(0.0, 5000.0, q),
427                ),
428                mode(
429                    "discharge",
430                    "Discharging",
431                    NumberRange::new(0.0, -0.0025),
432                    PowerRange::new(0.0, -5000.0, q),
433                ),
434            ],
435            transitions: alloc::vec![
436                Transition::simple(
437                    Id::new_const("t1"),
438                    Id::new_const("idle"),
439                    Id::new_const("charge")
440                ),
441                Transition::simple(
442                    Id::new_const("t2"),
443                    Id::new_const("charge"),
444                    Id::new_const("idle")
445                ),
446                Transition::simple(
447                    Id::new_const("t3"),
448                    Id::new_const("idle"),
449                    Id::new_const("discharge")
450                ),
451                Transition {
452                    id: Id::new_const("t4"),
453                    from: Id::new_const("discharge"),
454                    to: Id::new_const("idle"),
455                    start_timers: alloc::vec![],
456                    blocking_timers: alloc::vec![Id::new_const("cooldown")],
457                    transition_costs: None,
458                    transition_duration: None,
459                    abnormal_condition_only: false,
460                },
461            ],
462            timers: alloc::vec![Timer {
463                id: Id::new_const("cooldown"),
464                diagnostic_label: Some("Minimum discharge time".into()),
465                duration: Duration::from_secs(600),
466            }],
467        }],
468        storage: frbc::StorageDescription {
469            diagnostic_label: Some("Battery".into()),
470            fill_level_label: Some("percentage state of charge".into()),
471            provides_leakage_behaviour: false,
472            provides_fill_level_target_profile: false,
473            provides_usage_forecast: false,
474            fill_level_range: NumberRange::new(0.0, 100.0),
475        },
476    }
477}
478
479/// The 2 kWp curtailable PV installation from `s2-example-implementations`.
480#[must_use]
481pub fn pv_details() -> ResourceManagerDetails {
482    ResourceManagerDetails {
483        message_id: Id::new_const("rmd-pv"),
484        resource_id: Id::new_const("acme_pv_installation"),
485        name: Some("Solar panels on roof".into()),
486        roles: alloc::vec![Role::new(RoleType::EnergyProducer, Commodity::Electricity)],
487        manufacturer: Some("ACME".into()),
488        model: Some("InverterType2024".into()),
489        serial_number: Some("123".into()),
490        firmware_version: Some("v1.0".into()),
491        instruction_processing_delay: Duration::from_millis(5000),
492        available_control_types: alloc::vec![ControlType::PowerEnvelopeBasedControl],
493        currency: None,
494        provides_forecast: true,
495        provides_power_measurement_types: alloc::vec![CommodityQuantity::ElectricPowerL1],
496    }
497}
498
499/// The PV installation's constraints: curtail freely between −4 kW and zero.
500#[must_use]
501pub fn pv_constraints(valid_from: Timestamp) -> pebc::PowerConstraints {
502    pebc::PowerConstraints {
503        message_id: Id::new_const("pebc-constraints-1"),
504        id: Id::new_const("powerConstraint1"),
505        valid_from,
506        valid_until: None,
507        consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
508        allowed_limit_ranges: alloc::vec![
509            pebc::AllowedLimitRange {
510                commodity_quantity: CommodityQuantity::ElectricPowerL1,
511                limit_type: pebc::PowerEnvelopeLimitType::LowerLimit,
512                range_boundary: NumberRange::new(-4000.0, 0.0),
513                abnormal_condition_only: false,
514            },
515            pebc::AllowedLimitRange {
516                commodity_quantity: CommodityQuantity::ElectricPowerL1,
517                limit_type: pebc::PowerEnvelopeLimitType::UpperLimit,
518                range_boundary: NumberRange::new(0.0, 0.0),
519                abnormal_condition_only: false,
520            },
521        ],
522    }
523}
524
525/// An FRBC instruction for the battery fixture.
526#[must_use]
527pub fn charge(id: &'static str, factor: f64, at: Timestamp) -> frbc::Instruction {
528    frbc::Instruction {
529        message_id: Id::new_const("frbc-instr-msg"),
530        id: Id::new_const(id),
531        actuator_id: Id::new_const("actuator1"),
532        operation_mode: Id::new_const("charge"),
533        operation_mode_factor: factor,
534        execution_time: at,
535        abnormal_condition: false,
536    }
537}
538
539// ---------------------------------------------------------------------------
540// Replaying a recorded conversation
541// ---------------------------------------------------------------------------
542
543/// Something a recorded conversation did that this crate would not have done.
544#[derive(Debug, Clone, PartialEq)]
545#[non_exhaustive]
546pub enum Finding {
547    /// A rule fired on a message the transcript carries.
548    Violation {
549        /// Which line of the transcript, counting from one.
550        line: usize,
551        /// Which way it went.
552        direction: Direction,
553        /// What it was.
554        kind: MessageKind,
555        /// What was wrong with it.
556        violation: crate::validate::Violation,
557    },
558    /// The peer answered with a different `ReceptionStatus` than this crate would have.
559    ///
560    /// The interop finding: two readings of the standard, in one line, with the rule that
561    /// produced this side's named.
562    StatusDiffers {
563        /// Which line carried the message that was answered.
564        line: usize,
565        /// Which way that message went.
566        direction: Direction,
567        /// What it was.
568        kind: MessageKind,
569        /// What the transcript records the peer answering.
570        recorded: ReceptionStatusValues,
571        /// What this crate would answer.
572        expected: ReceptionStatusValues,
573        /// Why — the first error, rule identifier first. `None` when this crate would
574        /// have accepted the message and the peer did not.
575        because: Option<String>,
576    },
577    /// A message that must be answered was never answered.
578    ///
579    /// `S2J` requires a `ReceptionStatus` for every message except a `ReceptionStatus`;
580    /// forgetting one is the deadlock `[s2-json #22]` describes, and a transcript is the
581    /// only place it shows.
582    Unanswered {
583        /// Which line.
584        line: usize,
585        /// Which way it went.
586        direction: Direction,
587        /// What it was.
588        kind: MessageKind,
589        /// Its identifier, which the missing answer should have named.
590        message_id: Id,
591    },
592    /// A `ReceptionStatus` answering a message the transcript does not contain.
593    ///
594    /// Either the recording is incomplete or the peer answered something nobody sent.
595    UnmatchedAnswer {
596        /// Which line.
597        line: usize,
598        /// Which way it went.
599        direction: Direction,
600        /// What it claimed to answer.
601        subject: Id,
602    },
603}
604
605impl Finding {
606    /// Which line of the transcript this is about.
607    #[must_use]
608    pub const fn line(&self) -> usize {
609        match self {
610            Finding::Violation { line, .. }
611            | Finding::StatusDiffers { line, .. }
612            | Finding::Unanswered { line, .. }
613            | Finding::UnmatchedAnswer { line, .. } => *line,
614        }
615    }
616
617    /// Whether this finding means the conversation was not conforming.
618    ///
619    /// A warning-severity violation is not: the standard is ambiguous there, and another
620    /// implementation is entitled to read the silence differently.
621    #[must_use]
622    pub fn is_error(&self) -> bool {
623        match self {
624            Finding::Violation { violation, .. } => violation.severity == Severity::Error,
625            _ => true,
626        }
627    }
628}
629
630impl core::fmt::Display for Finding {
631    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
632        match self {
633            Finding::Violation {
634                line,
635                direction,
636                kind,
637                violation,
638            } => write!(f, "{line:>4} {} {kind}: {violation}", direction.as_str()),
639            Finding::StatusDiffers {
640                line,
641                direction,
642                kind,
643                recorded,
644                expected,
645                because,
646            } => {
647                write!(
648                    f,
649                    "{line:>4} {} {kind}: answered {recorded:?}, s2-kit would answer {expected:?}",
650                    direction.as_str()
651                )?;
652                match because {
653                    Some(why) => write!(f, " ({why})"),
654                    None => Ok(()),
655                }
656            }
657            Finding::Unanswered {
658                line,
659                direction,
660                kind,
661                message_id,
662            } => write!(
663                f,
664                "{line:>4} {} {kind}: never answered; no ReceptionStatus names {message_id}",
665                direction.as_str()
666            ),
667            Finding::UnmatchedAnswer {
668                line,
669                direction,
670                subject,
671            } => write!(
672                f,
673                "{line:>4} {} ReceptionStatus: answers {subject}, which no line sent",
674                direction.as_str()
675            ),
676        }
677    }
678}
679
680/// What a replay found, and what it saw.
681#[derive(Debug, Clone, Default)]
682pub struct ReplayReport {
683    /// Everything worth saying, in transcript order.
684    pub findings: Vec<Finding>,
685    /// How many lines were read.
686    pub lines: usize,
687    /// How many of them needed an answer and got one.
688    pub answered: usize,
689}
690
691impl ReplayReport {
692    /// Whether the conversation conformed.
693    #[must_use]
694    pub fn is_conforming(&self) -> bool {
695        !self.findings.iter().any(Finding::is_error)
696    }
697}
698
699impl core::fmt::Display for ReplayReport {
700    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
701        for finding in &self.findings {
702            writeln!(f, "{finding}")?;
703        }
704        write!(
705            f,
706            "{} line(s), {} answered: {}",
707            self.lines,
708            self.answered,
709            if self.is_conforming() { "ok" } else { "FAILED" }
710        )
711    }
712}
713
714/// Replay a recorded conversation and say where it departs from the standard.
715///
716/// Three questions, and only the first is one a message-at-a-time validator can answer:
717///
718/// 1. **Is each message legal, given everything before it?** An [`Analyzer`] keeps one
719///    registry fed from both directions, so an instruction naming an actuator nobody
720///    described is a finding rather than a blind spot.
721/// 2. **Did the peer answer as this crate would?** A disagreement is the interop report.
722/// 3. **Was every message answered at all?**
723///
724/// The clock is the transcript's own, so a validity window or a timer is replayed where it
725/// actually fell.
726///
727/// ```
728/// use s2_kit::testing::{read_s2log, replay};
729///
730/// let log = "\
731/// {\"t\":\"2024-01-01T12:00:00Z\",\"dir\":\"rm>cem\",\"msg\":{\"message_type\":\"FRBC.StorageStatus\",\"message_id\":\"m1\",\"present_fill_level\":52.0}}\n";
732/// let report = replay(&read_s2log(log));
733/// // Nobody answered it — the kind of thing only a transcript shows.
734/// assert_eq!(report.lines, 1);
735/// assert!(!report.is_conforming());
736/// ```
737#[must_use]
738pub fn replay(entries: &[TranscriptEntry]) -> ReplayReport {
739    replay_with(entries, Analyzer::new())
740}
741
742/// As [`replay`], with the observer configured — a different wire profile, strict
743/// decoding, an S2 Connect session where a handshake would be redundant.
744#[must_use]
745pub fn replay_with(entries: &[TranscriptEntry], mut analyzer: Analyzer) -> ReplayReport {
746    let mut report = ReplayReport {
747        lines: entries.len(),
748        ..ReplayReport::default()
749    };
750
751    // Two indexes, both built in one pass, because the alternative is quadratic and this
752    // is the tool a field capture is fed to. A transcript of a hundred thousand lines is
753    // an ordinary thing to be handed after a week of trouble.
754    //
755    // * what each side answered, by the identifier it named — an answer may legitimately
756    //   arrive several lines after the message it is about;
757    // * which identifiers were actually *sent*, and in which direction, so that an answer
758    //   naming a message nobody sent can be spotted without re-peeking every other line.
759    let mut answers: Vec<(Direction, Id, ReceptionStatusValues)> = Vec::new();
760    let mut sent: Vec<(Direction, Id)> = Vec::new();
761    for entry in entries {
762        if entry.kind == MessageKind::ReceptionStatus {
763            if let Ok(Message::ReceptionStatus(status)) = crate::codec::decode(&entry.text) {
764                answers.push((entry.direction, status.subject_message_id, status.status));
765            }
766            continue;
767        }
768        if let Ok(Some(id)) = crate::codec::peek(&entry.text).map(|p| p.message_id) {
769            sent.push((entry.direction, id));
770        }
771    }
772    answers.sort_unstable_by_key(|(direction, subject, _)| (*direction, *subject));
773    sent.sort_unstable();
774
775    for (index, entry) in entries.iter().enumerate() {
776        let line = index + 1;
777        let observed = analyzer.observe(entry.direction.sender(), &entry.text, entry.at);
778
779        for violation in observed.report.violations() {
780            report.findings.push(Finding::Violation {
781                line,
782                direction: entry.direction,
783                kind: entry.kind,
784                violation: violation.clone(),
785            });
786        }
787
788        let Some(message) = &observed.message else {
789            continue;
790        };
791
792        if let Message::ReceptionStatus(status) = message {
793            // An answer to a message this transcript does not contain: either the
794            // recording is incomplete, or the peer answered something nobody sent. The
795            // nil identifier is the one exception — it is what the ecosystem sends when
796            // the message had no readable id at all (erratum E10).
797            let was_sent = sent
798                .binary_search(&(entry.direction.other(), status.subject_message_id))
799                .is_ok();
800            if !was_sent && status.subject_message_id != Id::NIL {
801                report.findings.push(Finding::UnmatchedAnswer {
802                    line,
803                    direction: entry.direction,
804                    subject: status.subject_message_id,
805                });
806            }
807            continue;
808        }
809
810        let Some(message_id) = message.id() else {
811            continue;
812        };
813        // The answer must come back the other way.
814        let recorded = answers
815            .binary_search_by_key(&(entry.direction.other(), message_id), |(d, s, _)| (*d, *s))
816            .ok()
817            .and_then(|i| answers.get(i))
818            .map(|(_, _, status)| *status);
819
820        match recorded {
821            None => report.findings.push(Finding::Unanswered {
822                line,
823                direction: entry.direction,
824                kind: entry.kind,
825                message_id,
826            }),
827            Some(recorded) => {
828                report.answered += 1;
829                // `TEMPORARY_ERROR` and `PERMANENT_ERROR` are about the *receiver* — a
830                // storage that was unavailable, a device that was offline — and no
831                // observer can know that. They are never a disagreement.
832                let receiver_specific = matches!(
833                    recorded,
834                    ReceptionStatusValues::TemporaryError | ReceptionStatusValues::PermanentError
835                );
836                if recorded != observed.status && !receiver_specific {
837                    report.findings.push(Finding::StatusDiffers {
838                        line,
839                        direction: entry.direction,
840                        kind: entry.kind,
841                        recorded,
842                        expected: observed.status,
843                        because: observed.diagnostic_label(),
844                    });
845                }
846            }
847        }
848    }
849
850    report.findings.sort_by_key(Finding::line);
851    report
852}
853
854// ---------------------------------------------------------------------------
855// One of everything, with every optional field populated
856// ---------------------------------------------------------------------------
857
858fn id(s: &str) -> Id {
859    Id::parse(s).unwrap_or(Id::NIL)
860}
861
862fn at() -> Timestamp {
863    Timestamp::from_unix(1_724_508_922, 0)
864}
865
866fn q() -> CommodityQuantity {
867    CommodityQuantity::ElectricPowerL1
868}
869
870fn number_range() -> NumberRange {
871    NumberRange::new(0.0, 100.0)
872}
873
874fn power_range() -> PowerRange {
875    PowerRange::new(0.0, 2000.0, q())
876}
877
878fn forecast_value() -> PowerForecastValue {
879    PowerForecastValue {
880        value_upper_limit: Some(1000.0),
881        value_upper_95ppr: Some(960.0),
882        value_upper_68ppr: Some(800.0),
883        value_expected: 545.1,
884        value_lower_68ppr: Some(340.0),
885        value_lower_95ppr: Some(100.0),
886        value_lower_limit: Some(0.0),
887        commodity_quantity: q(),
888    }
889}
890
891fn timer() -> Timer {
892    Timer {
893        id: id("timer0"),
894        diagnostic_label: Some("Minimum run time".into()),
895        duration: Duration::from_secs(7200),
896    }
897}
898
899fn transition(from: &str, to: &str) -> Transition {
900    Transition {
901        id: id("trans0"),
902        from: id(from),
903        to: id(to),
904        start_timers: vec![id("timer0")],
905        blocking_timers: vec![id("timer0")],
906        transition_costs: Some(0.0),
907        transition_duration: Some(Duration::from_secs(3)),
908        abnormal_condition_only: false,
909    }
910}
911
912fn frbc_actuator() -> frbc::ActuatorDescription {
913    frbc::ActuatorDescription {
914        id: id("actuator1"),
915        diagnostic_label: Some("heat pump".into()),
916        supported_commodities: vec![Commodity::Electricity],
917        operation_modes: vec![
918            frbc::OperationMode {
919                id: id("om0"),
920                diagnostic_label: Some("running".into()),
921                elements: vec![frbc::OperationModeElement {
922                    fill_level_range: number_range(),
923                    fill_rate: NumberRange::new(0.002_09, 0.008_35),
924                    power_ranges: vec![power_range()],
925                    running_costs: Some(NumberRange::new(0.0, 0.0)),
926                }],
927                abnormal_condition_only: false,
928            },
929            frbc::OperationMode {
930                id: id("om1"),
931                diagnostic_label: Some("Off".into()),
932                elements: vec![frbc::OperationModeElement {
933                    fill_level_range: number_range(),
934                    fill_rate: NumberRange::exactly(0.0),
935                    power_ranges: vec![PowerRange::exactly(0.0, q())],
936                    running_costs: None,
937                }],
938                abnormal_condition_only: false,
939            },
940        ],
941        transitions: vec![transition("om0", "om1")],
942        timers: vec![timer()],
943    }
944}
945
946fn ddbc_actuator() -> ddbc::ActuatorDescription {
947    ddbc::ActuatorDescription {
948        id: id("actuator1"),
949        diagnostic_label: Some("hybrid heat pump".into()),
950        supported_commodities: vec![Commodity::Electricity, Commodity::Gas],
951        operation_modes: vec![ddbc::OperationMode {
952            id: id("om0"),
953            diagnostic_label: Some("electric".into()),
954            power_ranges: vec![power_range()],
955            supply_range: NumberRange::new(0.0, 6000.0),
956            running_costs: Some(NumberRange::new(0.0, 0.0)),
957            abnormal_condition_only: false,
958        }],
959        transitions: vec![transition("om0", "om0")],
960        timers: vec![timer()],
961    }
962}
963
964/// One of every message, with **every optional field set**.
965///
966/// The corpus three different checks are run over, and the reason it lives here rather
967/// than in one of them: it is the answer to "show me every message this crate can
968/// produce", which is a thing a consumer writing its own tests wants as much as this
969/// crate does.
970///
971/// * `tests/model_matches_schema.rs` validates each one against the official JSON schema
972///   and requires every component the schema defines to be reachable from one of them;
973/// * `tests/interop_s2energy.rs` requires an independent implementation to read them;
974/// * a consumer can use it to exercise its own handler over the whole message space.
975///
976/// Identifiers are short and readable (`actuator1`, `om0`) rather than UUIDs, exactly as
977/// the standard's own worked examples write them — `S2J schemas/ID` is a pattern, not a
978/// UUID (erratum E1).
979#[must_use]
980pub fn every_message() -> Vec<Message> {
981    let versions = vec![ProtocolVersion::new("1.0.0")];
982    vec![
983        Handshake {
984            message_id: id("m1"),
985            role: EnergyManagementRole::Rm,
986            supported_protocol_versions: Some(versions),
987        }
988        .into(),
989        HandshakeResponse {
990            message_id: id("m1"),
991            selected_protocol_version: ProtocolVersion::new("1.0.0"),
992        }
993        .into(),
994        ResourceManagerDetails {
995            message_id: id("m1"),
996            resource_id: id("acme_heat_pump"),
997            name: Some("my_heat_pump".into()),
998            roles: vec![Role::new(RoleType::EnergyConsumer, Commodity::Electricity)],
999            manufacturer: Some("ACME".into()),
1000            model: Some("HeatPump2000".into()),
1001            serial_number: Some("123".into()),
1002            firmware_version: Some("v1.0".into()),
1003            instruction_processing_delay: Duration::from_millis(10_000),
1004            available_control_types: vec![ControlType::FillRateBasedControl],
1005            currency: Some(Currency::Eur),
1006            provides_forecast: true,
1007            provides_power_measurement_types: vec![q()],
1008        }
1009        .into(),
1010        SelectControlType {
1011            message_id: id("m1"),
1012            control_type: ControlType::FillRateBasedControl,
1013        }
1014        .into(),
1015        SessionRequest {
1016            message_id: id("m1"),
1017            request: SessionRequestType::Terminate,
1018            diagnostic_label: Some("shutting down".into()),
1019        }
1020        .into(),
1021        ReceptionStatus {
1022            subject_message_id: id("m1"),
1023            status: ReceptionStatusValues::Ok,
1024            diagnostic_label: Some("Processed okay.".into()),
1025        }
1026        .into(),
1027        InstructionStatusUpdate {
1028            message_id: id("m1"),
1029            instruction_id: id("instr0"),
1030            status_type: InstructionStatus::Succeeded,
1031            timestamp: at(),
1032        }
1033        .into(),
1034        PowerMeasurement {
1035            message_id: id("m1"),
1036            measurement_timestamp: at(),
1037            values: vec![PowerValue::new(q(), 510.6)],
1038        }
1039        .into(),
1040        PowerForecast {
1041            message_id: id("m1"),
1042            start_time: at(),
1043            elements: vec![PowerForecastElement {
1044                duration: Duration::from_millis(3_600_000),
1045                power_values: vec![forecast_value()],
1046            }],
1047        }
1048        .into(),
1049        RevokeObject {
1050            message_id: id("m1"),
1051            object_type: RevokableObjects::FrbcSystemDescription,
1052            object_id: id("sd1"),
1053        }
1054        .into(),
1055        // --- PEBC ---
1056        pebc::PowerConstraints {
1057            message_id: id("m1"),
1058            id: id("powerConstraint1"),
1059            valid_from: at(),
1060            valid_until: Some(at()),
1061            consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1062            allowed_limit_ranges: vec![
1063                pebc::AllowedLimitRange {
1064                    commodity_quantity: q(),
1065                    limit_type: pebc::PowerEnvelopeLimitType::LowerLimit,
1066                    range_boundary: NumberRange::new(-4000.0, 0.0),
1067                    abnormal_condition_only: false,
1068                },
1069                pebc::AllowedLimitRange {
1070                    commodity_quantity: q(),
1071                    limit_type: pebc::PowerEnvelopeLimitType::UpperLimit,
1072                    range_boundary: NumberRange::new(0.0, 0.0),
1073                    abnormal_condition_only: false,
1074                },
1075            ],
1076        }
1077        .into(),
1078        pebc::EnergyConstraint {
1079            message_id: id("m1"),
1080            id: id("energyconstraint1"),
1081            valid_from: at(),
1082            valid_until: at(),
1083            upper_average_power: 3000.0,
1084            lower_average_power: 1000.0,
1085            commodity_quantity: q(),
1086        }
1087        .into(),
1088        pebc::Instruction {
1089            message_id: id("m1"),
1090            id: id("envelope1"),
1091            execution_time: at(),
1092            abnormal_condition: false,
1093            power_constraints_id: id("powerConstraint1"),
1094            power_envelopes: vec![pebc::PowerEnvelope {
1095                id: id("pe_xxx"),
1096                commodity_quantity: q(),
1097                power_envelope_elements: vec![pebc::PowerEnvelopeElement::new(
1098                    Duration::from_millis(3_600_000),
1099                    -2000.0,
1100                    0.0,
1101                )],
1102            }],
1103        }
1104        .into(),
1105        // --- PPBC ---
1106        ppbc::PowerProfileDefinition {
1107            message_id: id("m1"),
1108            id: id("profile1"),
1109            start_time: at(),
1110            end_time: at(),
1111            power_sequence_containers: vec![ppbc::PowerSequenceContainer {
1112                id: id("c1"),
1113                power_sequences: vec![ppbc::PowerSequence {
1114                    id: id("s1"),
1115                    elements: vec![ppbc::PowerSequenceElement {
1116                        duration: Duration::from_secs(600),
1117                        power_values: vec![forecast_value()],
1118                    }],
1119                    is_interruptible: true,
1120                    max_pause_before: Some(Duration::from_secs(300)),
1121                    abnormal_condition_only: false,
1122                }],
1123            }],
1124        }
1125        .into(),
1126        ppbc::PowerProfileStatus {
1127            message_id: id("m1"),
1128            sequence_container_status: vec![ppbc::PowerSequenceContainerStatus {
1129                power_profile_id: id("profile1"),
1130                sequence_container_id: id("c1"),
1131                selected_sequence_id: Some(id("s1")),
1132                progress: Some(Duration::from_secs(60)),
1133                status: ppbc::PowerSequenceStatus::Executing,
1134            }],
1135        }
1136        .into(),
1137        ppbc::ScheduleInstruction {
1138            message_id: id("m1"),
1139            id: id("instr0"),
1140            power_profile_id: id("profile1"),
1141            sequence_container_id: id("c1"),
1142            power_sequence_id: id("s1"),
1143            execution_time: at(),
1144            abnormal_condition: false,
1145        }
1146        .into(),
1147        ppbc::StartInterruptionInstruction {
1148            message_id: id("m1"),
1149            id: id("instr1"),
1150            power_profile_id: id("profile1"),
1151            sequence_container_id: id("c1"),
1152            power_sequence_id: id("s1"),
1153            execution_time: at(),
1154            abnormal_condition: false,
1155        }
1156        .into(),
1157        ppbc::EndInterruptionInstruction {
1158            message_id: id("m1"),
1159            id: id("instr2"),
1160            power_profile_id: id("profile1"),
1161            sequence_container_id: id("c1"),
1162            power_sequence_id: id("s1"),
1163            execution_time: at(),
1164            abnormal_condition: false,
1165        }
1166        .into(),
1167        // --- OMBC ---
1168        ombc::SystemDescription {
1169            message_id: id("m1"),
1170            valid_from: at(),
1171            operation_modes: vec![ombc::OperationMode {
1172                id: id("om0"),
1173                diagnostic_label: Some("Off".into()),
1174                power_ranges: vec![power_range()],
1175                running_costs: Some(NumberRange::new(0.0, 0.0)),
1176                abnormal_condition_only: false,
1177            }],
1178            transitions: vec![transition("om0", "om0")],
1179            timers: vec![timer()],
1180        }
1181        .into(),
1182        ombc::Status {
1183            message_id: id("m1"),
1184            active_operation_mode_id: id("om0"),
1185            operation_mode_factor: 0.5,
1186            previous_operation_mode_id: Some(id("om1")),
1187            transition_timestamp: Some(at()),
1188        }
1189        .into(),
1190        ombc::TimerStatus {
1191            message_id: id("m1"),
1192            timer_id: id("timer0"),
1193            finished_at: at(),
1194        }
1195        .into(),
1196        ombc::Instruction {
1197            message_id: id("m1"),
1198            id: id("instr0"),
1199            execution_time: at(),
1200            operation_mode_id: id("om0"),
1201            operation_mode_factor: 1.0,
1202            abnormal_condition: false,
1203        }
1204        .into(),
1205        // --- FRBC ---
1206        frbc::SystemDescription {
1207            message_id: id("m1"),
1208            valid_from: at(),
1209            actuators: vec![frbc_actuator()],
1210            storage: frbc::StorageDescription {
1211                diagnostic_label: Some("DHW Buffer".into()),
1212                fill_level_label: Some("temperature in Celsius".into()),
1213                provides_leakage_behaviour: true,
1214                provides_fill_level_target_profile: true,
1215                provides_usage_forecast: true,
1216                fill_level_range: number_range(),
1217            },
1218        }
1219        .into(),
1220        frbc::StorageStatus {
1221            message_id: id("m1"),
1222            present_fill_level: 52.0,
1223        }
1224        .into(),
1225        frbc::ActuatorStatus {
1226            message_id: id("m1"),
1227            actuator_id: id("actuator1"),
1228            active_operation_mode_id: id("om0"),
1229            operation_mode_factor: 0.0,
1230            previous_operation_mode_id: Some(id("om1")),
1231            transition_timestamp: Some(at()),
1232        }
1233        .into(),
1234        frbc::TimerStatus {
1235            message_id: id("m1"),
1236            timer_id: id("timer0"),
1237            actuator_id: id("actuator1"),
1238            finished_at: at(),
1239        }
1240        .into(),
1241        frbc::LeakageBehaviour {
1242            message_id: id("m1"),
1243            valid_from: at(),
1244            elements: vec![frbc::LeakageBehaviourElement {
1245                fill_level_range: number_range(),
1246                leakage_rate: 0.000_05,
1247            }],
1248        }
1249        .into(),
1250        frbc::UsageForecast {
1251            message_id: id("m1"),
1252            start_time: at(),
1253            elements: vec![frbc::UsageForecastElement {
1254                duration: Duration::from_secs(900),
1255                usage_rate_upper_limit: Some(1.0),
1256                usage_rate_upper_95ppr: Some(0.9),
1257                usage_rate_upper_68ppr: Some(0.8),
1258                usage_rate_expected: 0.5,
1259                usage_rate_lower_68ppr: Some(0.4),
1260                usage_rate_lower_95ppr: Some(0.2),
1261                usage_rate_lower_limit: Some(0.0),
1262            }],
1263        }
1264        .into(),
1265        frbc::FillLevelTargetProfile {
1266            message_id: id("m1"),
1267            start_time: at(),
1268            elements: vec![frbc::FillLevelTargetProfileElement {
1269                duration: Duration::from_secs(3600),
1270                fill_level_range: number_range(),
1271            }],
1272        }
1273        .into(),
1274        frbc::Instruction {
1275            message_id: id("m1"),
1276            id: id("instr0"),
1277            actuator_id: id("actuator1"),
1278            operation_mode: id("om0"),
1279            operation_mode_factor: 1.0,
1280            execution_time: at(),
1281            abnormal_condition: false,
1282        }
1283        .into(),
1284        // --- DDBC ---
1285        ddbc::SystemDescription {
1286            message_id: id("m1"),
1287            valid_from: at(),
1288            actuators: vec![ddbc_actuator()],
1289            present_demand_rate: None,
1290            provides_average_demand_rate_forecast: true,
1291        }
1292        .into(),
1293        ddbc::ActuatorStatus {
1294            message_id: id("m1"),
1295            actuator_id: id("actuator1"),
1296            active_operation_mode_id: id("om0"),
1297            operation_mode_factor: 0.5,
1298            previous_operation_mode_id: Some(id("om1")),
1299            transition_timestamp: Some(at()),
1300        }
1301        .into(),
1302        ddbc::TimerStatus {
1303            message_id: id("m1"),
1304            timer_id: id("timer0"),
1305            actuator_id: id("actuator1"),
1306            finished_at: at(),
1307        }
1308        .into(),
1309        ddbc::AverageDemandRateForecast {
1310            message_id: id("m1"),
1311            start_time: at(),
1312            elements: vec![ddbc::AverageDemandRateForecastElement {
1313                duration: Duration::from_secs(900),
1314                demand_rate_upper_limit: Some(1.0),
1315                demand_rate_upper_95ppr: Some(0.9),
1316                demand_rate_upper_68ppr: Some(0.8),
1317                demand_rate_expected: 0.5,
1318                demand_rate_lower_68ppr: Some(0.4),
1319                demand_rate_lower_95ppr: Some(0.2),
1320                demand_rate_lower_limit: Some(0.0),
1321            }],
1322        }
1323        .into(),
1324        ddbc::PresentDemandStatus {
1325            message_id: id("m1"),
1326            present_demand_rate: NumberRange::new(0.0, 6000.0),
1327        }
1328        .into(),
1329        ddbc::Instruction {
1330            message_id: id("m1"),
1331            id: id("instr0"),
1332            execution_time: at(),
1333            abnormal_condition: false,
1334            actuator_id: id("actuator1"),
1335            operation_mode_id: id("om0"),
1336            operation_mode_factor: 1.0,
1337        }
1338        .into(),
1339    ]
1340}