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, NumberRange, PowerRange, ReceptionStatusValues,
32    ResourceManagerDetails, Role, RoleType, Timer, Transition,
33};
34use crate::types::{Duration, Id, Timestamp, frbc, pebc};
35use crate::validate::Severity;
36
37/// Which way a message went.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Direction {
40    /// From the Customer Energy Manager to the Resource Manager.
41    CemToRm,
42    /// From the Resource Manager to the Customer Energy Manager.
43    RmToCem,
44}
45
46impl Direction {
47    /// The short form used in a transcript file.
48    #[must_use]
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            Direction::CemToRm => "cem>rm",
52            Direction::RmToCem => "rm>cem",
53        }
54    }
55}
56
57/// One line of a `.s2log` transcript.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct TranscriptEntry {
60    /// When it was sent, on the conversation's clock.
61    pub at: Timestamp,
62    /// Which way.
63    pub direction: Direction,
64    /// What it was.
65    pub kind: MessageKind,
66    /// The bytes.
67    pub text: String,
68}
69
70impl Direction {
71    /// The role that sent a message going this way.
72    #[must_use]
73    pub const fn sender(self) -> crate::types::common::EnergyManagementRole {
74        match self {
75            Direction::CemToRm => crate::types::common::EnergyManagementRole::Cem,
76            Direction::RmToCem => crate::types::common::EnergyManagementRole::Rm,
77        }
78    }
79
80    /// The direction a transcript line's `dir` field names.
81    #[must_use]
82    pub fn parse(s: &str) -> Option<Self> {
83        match s {
84            "cem>rm" => Some(Direction::CemToRm),
85            "rm>cem" => Some(Direction::RmToCem),
86            _ => None,
87        }
88    }
89}
90
91impl TranscriptEntry {
92    /// The entry as one line of JSON Lines.
93    #[must_use]
94    pub fn to_jsonl(&self) -> String {
95        format!(
96            r#"{{"t":"{}","dir":"{}","msg":{}}}"#,
97            self.at,
98            self.direction.as_str(),
99            self.text
100        )
101    }
102
103    /// Read one line of a `.s2log` back.
104    ///
105    /// The inverse of [`to_jsonl`](Self::to_jsonl). `None` for a line that is not one — a
106    /// blank line, a comment, or a record from some other tool.
107    #[must_use]
108    pub fn from_jsonl(line: &str) -> Option<Self> {
109        let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
110        let at = value.get("t")?.as_str()?.parse().ok()?;
111        let direction = Direction::parse(value.get("dir")?.as_str()?)?;
112        let text = value.get("msg")?.to_string();
113        // The kind is derived rather than stored: a transcript records what crossed the
114        // wire, and a `message_type` the reader does not know is exactly the thing a
115        // replay must be able to report rather than refuse to load.
116        let kind = crate::codec::peek(&text).ok().and_then(|p| p.kind)?;
117        Some(Self {
118            at,
119            direction,
120            kind,
121            text,
122        })
123    }
124}
125
126/// Read a whole `.s2log`, skipping anything that is not a transcript line.
127#[must_use]
128pub fn read_s2log(text: &str) -> Vec<TranscriptEntry> {
129    text.lines()
130        .filter_map(TranscriptEntry::from_jsonl)
131        .collect()
132}
133
134/// A Resource Manager and a Customer Energy Manager, talking to each other.
135pub struct Conversation {
136    /// The resource's side.
137    pub rm: RmSession,
138    /// The manager's side.
139    pub cem: CemSession,
140    /// The virtual clock.
141    pub now: Timestamp,
142    transcript: Vec<TranscriptEntry>,
143    rm_events: Vec<RmEvent>,
144    cem_events: Vec<CemEvent>,
145}
146
147impl Conversation {
148    /// A conversation between the given two configurations.
149    #[must_use]
150    pub fn new(
151        rm_config: RmConfig,
152        details: ResourceManagerDetails,
153        cem_config: CemConfig,
154    ) -> Self {
155        Self {
156            rm: RmSession::new(rm_config, details),
157            cem: CemSession::new(cem_config),
158            now: "2024-01-01T12:00:00Z"
159                .parse()
160                .unwrap_or(Timestamp::UNIX_EPOCH),
161            transcript: Vec::new(),
162            rm_events: Vec::new(),
163            cem_events: Vec::new(),
164        }
165    }
166
167    /// A conversation with a 20 kWh home battery, the FRBC example implementation.
168    #[must_use]
169    pub fn battery() -> Self {
170        Self::new(RmConfig::default(), battery_details(), CemConfig::default())
171    }
172
173    /// A conversation with a 4 kWp curtailable PV inverter, the PEBC example.
174    #[must_use]
175    pub fn pv() -> Self {
176        Self::new(RmConfig::default(), pv_details(), CemConfig::default())
177    }
178
179    /// Open both sides and run the conversation until it goes quiet.
180    pub fn open(&mut self) {
181        self.rm.open(self.now);
182        self.cem.open(self.now);
183        self.pump();
184    }
185
186    /// Deliver everything either side wants to send, until neither has anything left.
187    ///
188    /// Bounded, so a session that answers its own answers cannot hang a test.
189    ///
190    /// # Panics
191    ///
192    /// When the conversation does not settle within a thousand rounds, which means one
193    /// of the engines is acknowledging acknowledgements.
194    #[allow(clippy::panic)] // a test harness that hangs is worse than one that fails
195    pub fn pump(&mut self) {
196        for _ in 0..1000 {
197            let mut moved = false;
198            while let Some(out) = self.rm.poll_transmit() {
199                self.record(Direction::RmToCem, out.kind, &out.text);
200                self.cem.handle_text(&out.text, self.now);
201                moved = true;
202            }
203            while let Some(out) = self.cem.poll_transmit() {
204                self.record(Direction::CemToRm, out.kind, &out.text);
205                self.rm.handle_text(&out.text, self.now);
206                moved = true;
207            }
208            self.drain_events();
209            if !moved {
210                return;
211            }
212        }
213        panic!("the conversation did not settle: a session is answering its own answers");
214    }
215
216    fn record(&mut self, direction: Direction, kind: MessageKind, text: &str) {
217        self.transcript.push(TranscriptEntry {
218            at: self.now,
219            direction,
220            kind,
221            text: text.to_string(),
222        });
223    }
224
225    fn drain_events(&mut self) {
226        while let Some(event) = self.rm.poll_event() {
227            self.rm_events.push(event);
228        }
229        while let Some(event) = self.cem.poll_event() {
230            self.cem_events.push(event);
231        }
232    }
233
234    /// Move the clock forward, letting both sides notice.
235    pub fn advance(&mut self, by: Duration) {
236        self.now = self.now.checked_add(by).unwrap_or(self.now);
237        self.rm.handle_timeout(self.now);
238        self.cem.handle_timeout(self.now);
239        self.pump();
240    }
241
242    /// Move the clock forward without delivering anything, so that a message can be
243    /// dropped on the floor.
244    pub fn advance_silently(&mut self, by: Duration) {
245        self.now = self.now.checked_add(by).unwrap_or(self.now);
246        self.rm.handle_timeout(self.now);
247        self.cem.handle_timeout(self.now);
248        self.drain_events();
249    }
250
251    /// Throw away everything the Resource Manager is trying to say, as a lost
252    /// connection would.
253    pub fn drop_rm_traffic(&mut self) {
254        while self.rm.poll_transmit().is_some() {}
255        self.drain_events();
256    }
257
258    /// Throw away everything the manager is trying to say.
259    pub fn drop_cem_traffic(&mut self) {
260        while self.cem.poll_transmit().is_some() {}
261        self.drain_events();
262    }
263
264    /// Everything that has crossed the wire.
265    #[must_use]
266    pub fn transcript(&self) -> &[TranscriptEntry] {
267        &self.transcript
268    }
269
270    /// The transcript as a `.s2log` file.
271    #[must_use]
272    pub fn to_s2log(&self) -> String {
273        let mut out = String::new();
274        for entry in &self.transcript {
275            out.push_str(&entry.to_jsonl());
276            out.push('\n');
277        }
278        out
279    }
280
281    /// Every message type that has crossed, in order.
282    #[must_use]
283    pub fn flow(&self) -> Vec<(Direction, MessageKind)> {
284        self.transcript
285            .iter()
286            .map(|e| (e.direction, e.kind))
287            .collect()
288    }
289
290    /// Every message type that has crossed, ignoring the acknowledgements.
291    #[must_use]
292    pub fn flow_without_acks(&self) -> Vec<(Direction, MessageKind)> {
293        self.flow()
294            .into_iter()
295            .filter(|(_, kind)| *kind != MessageKind::ReceptionStatus)
296            .collect()
297    }
298
299    /// Everything the Resource Manager has reported, clearing the list.
300    pub fn take_rm_events(&mut self) -> Vec<RmEvent> {
301        self.drain_events();
302        core::mem::take(&mut self.rm_events)
303    }
304
305    /// Everything the manager has reported, clearing the list.
306    pub fn take_cem_events(&mut self) -> Vec<CemEvent> {
307        self.drain_events();
308        core::mem::take(&mut self.cem_events)
309    }
310
311    /// The first instruction the Resource Manager was handed, if any.
312    pub fn first_instruction(&mut self) -> Option<Instructed> {
313        self.drain_events();
314        self.rm_events.iter().find_map(|e| match e {
315            RmEvent::Instruction(i) => Some((**i).clone()),
316            _ => None,
317        })
318    }
319
320    /// Whether either side refused anything.
321    #[must_use]
322    pub fn refusals(&self) -> Vec<String> {
323        let mut out = Vec::new();
324        for event in &self.rm_events {
325            if let RmEvent::Refused { report, .. } = event {
326                out.push(format!("RM refused: {report}"));
327            }
328        }
329        for event in &self.cem_events {
330            if let CemEvent::Refused { report, .. } = event {
331                out.push(format!("CEM refused: {report}"));
332            }
333        }
334        out
335    }
336
337    /// Assert that nothing was refused. The message names what was.
338    ///
339    /// # Panics
340    ///
341    /// When either side refused a message.
342    pub fn assert_no_refusals(&self) {
343        let refusals = self.refusals();
344        assert!(refusals.is_empty(), "{refusals:#?}");
345    }
346}
347
348// ---------------------------------------------------------------------------
349// Fixtures
350// ---------------------------------------------------------------------------
351
352/// The 20 kWh home battery from `s2-example-implementations`.
353#[must_use]
354pub fn battery_details() -> ResourceManagerDetails {
355    ResourceManagerDetails {
356        message_id: Id::new_const("rmd-battery"),
357        resource_id: Id::new_const("acme_battery_1"),
358        name: Some("Home battery".into()),
359        roles: alloc::vec![Role::new(RoleType::EnergyStorage, Commodity::Electricity)],
360        manufacturer: Some("ACME".into()),
361        model: Some("Powerwall-ish".into()),
362        serial_number: Some("123".into()),
363        firmware_version: Some("v1.0".into()),
364        instruction_processing_delay: Duration::from_millis(500),
365        available_control_types: alloc::vec![ControlType::FillRateBasedControl],
366        currency: None,
367        provides_forecast: false,
368        provides_power_measurement_types: alloc::vec![
369            CommodityQuantity::ElectricPower3PhaseSymmetric
370        ],
371    }
372}
373
374/// A battery's system description: charge, idle and discharge over a 0–100 % store.
375#[must_use]
376pub fn battery_system(valid_from: Timestamp) -> frbc::SystemDescription {
377    let mode =
378        |id: &'static str, label: &str, rate: NumberRange, power: PowerRange| frbc::OperationMode {
379            id: Id::new_const(id),
380            diagnostic_label: Some(label.to_string()),
381            elements: alloc::vec![frbc::OperationModeElement {
382                fill_level_range: NumberRange::new(0.0, 100.0),
383                fill_rate: rate,
384                power_ranges: alloc::vec![power],
385                running_costs: None,
386            }],
387            abnormal_condition_only: false,
388        };
389    let q = CommodityQuantity::ElectricPower3PhaseSymmetric;
390    frbc::SystemDescription {
391        message_id: Id::new_const("frbc-system-1"),
392        valid_from,
393        actuators: alloc::vec![frbc::ActuatorDescription {
394            id: Id::new_const("actuator1"),
395            diagnostic_label: Some("Battery inverter".into()),
396            supported_commodities: alloc::vec![Commodity::Electricity],
397            operation_modes: alloc::vec![
398                mode(
399                    "idle",
400                    "Idle",
401                    NumberRange::exactly(0.0),
402                    PowerRange::exactly(0.0, q)
403                ),
404                mode(
405                    "charge",
406                    "Charging",
407                    NumberRange::new(0.0, 0.0025),
408                    PowerRange::new(0.0, 5000.0, q),
409                ),
410                mode(
411                    "discharge",
412                    "Discharging",
413                    NumberRange::new(0.0, -0.0025),
414                    PowerRange::new(0.0, -5000.0, q),
415                ),
416            ],
417            transitions: alloc::vec![
418                Transition::simple(
419                    Id::new_const("t1"),
420                    Id::new_const("idle"),
421                    Id::new_const("charge")
422                ),
423                Transition::simple(
424                    Id::new_const("t2"),
425                    Id::new_const("charge"),
426                    Id::new_const("idle")
427                ),
428                Transition::simple(
429                    Id::new_const("t3"),
430                    Id::new_const("idle"),
431                    Id::new_const("discharge")
432                ),
433                Transition {
434                    id: Id::new_const("t4"),
435                    from: Id::new_const("discharge"),
436                    to: Id::new_const("idle"),
437                    start_timers: alloc::vec![],
438                    blocking_timers: alloc::vec![Id::new_const("cooldown")],
439                    transition_costs: None,
440                    transition_duration: None,
441                    abnormal_condition_only: false,
442                },
443            ],
444            timers: alloc::vec![Timer {
445                id: Id::new_const("cooldown"),
446                diagnostic_label: Some("Minimum discharge time".into()),
447                duration: Duration::from_secs(600),
448            }],
449        }],
450        storage: frbc::StorageDescription {
451            diagnostic_label: Some("Battery".into()),
452            fill_level_label: Some("percentage state of charge".into()),
453            provides_leakage_behaviour: false,
454            provides_fill_level_target_profile: false,
455            provides_usage_forecast: false,
456            fill_level_range: NumberRange::new(0.0, 100.0),
457        },
458    }
459}
460
461/// The 2 kWp curtailable PV installation from `s2-example-implementations`.
462#[must_use]
463pub fn pv_details() -> ResourceManagerDetails {
464    ResourceManagerDetails {
465        message_id: Id::new_const("rmd-pv"),
466        resource_id: Id::new_const("acme_pv_installation"),
467        name: Some("Solar panels on roof".into()),
468        roles: alloc::vec![Role::new(RoleType::EnergyProducer, Commodity::Electricity)],
469        manufacturer: Some("ACME".into()),
470        model: Some("InverterType2024".into()),
471        serial_number: Some("123".into()),
472        firmware_version: Some("v1.0".into()),
473        instruction_processing_delay: Duration::from_millis(5000),
474        available_control_types: alloc::vec![ControlType::PowerEnvelopeBasedControl],
475        currency: None,
476        provides_forecast: true,
477        provides_power_measurement_types: alloc::vec![CommodityQuantity::ElectricPowerL1],
478    }
479}
480
481/// The PV installation's constraints: curtail freely between −4 kW and zero.
482#[must_use]
483pub fn pv_constraints(valid_from: Timestamp) -> pebc::PowerConstraints {
484    pebc::PowerConstraints {
485        message_id: Id::new_const("pebc-constraints-1"),
486        id: Id::new_const("powerConstraint1"),
487        valid_from,
488        valid_until: None,
489        consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
490        allowed_limit_ranges: alloc::vec![
491            pebc::AllowedLimitRange {
492                commodity_quantity: CommodityQuantity::ElectricPowerL1,
493                limit_type: pebc::PowerEnvelopeLimitType::LowerLimit,
494                range_boundary: NumberRange::new(-4000.0, 0.0),
495                abnormal_condition_only: false,
496            },
497            pebc::AllowedLimitRange {
498                commodity_quantity: CommodityQuantity::ElectricPowerL1,
499                limit_type: pebc::PowerEnvelopeLimitType::UpperLimit,
500                range_boundary: NumberRange::new(0.0, 0.0),
501                abnormal_condition_only: false,
502            },
503        ],
504    }
505}
506
507/// An FRBC instruction for the battery fixture.
508#[must_use]
509pub fn charge(id: &'static str, factor: f64, at: Timestamp) -> frbc::Instruction {
510    frbc::Instruction {
511        message_id: Id::new_const("frbc-instr-msg"),
512        id: Id::new_const(id),
513        actuator_id: Id::new_const("actuator1"),
514        operation_mode: Id::new_const("charge"),
515        operation_mode_factor: factor,
516        execution_time: at,
517        abnormal_condition: false,
518    }
519}
520
521// ---------------------------------------------------------------------------
522// Replaying a recorded conversation
523// ---------------------------------------------------------------------------
524
525/// Something a recorded conversation did that this crate would not have done.
526#[derive(Debug, Clone, PartialEq)]
527#[non_exhaustive]
528pub enum Finding {
529    /// A rule fired on a message the transcript carries.
530    Violation {
531        /// Which line of the transcript, counting from one.
532        line: usize,
533        /// Which way it went.
534        direction: Direction,
535        /// What it was.
536        kind: MessageKind,
537        /// What was wrong with it.
538        violation: crate::validate::Violation,
539    },
540    /// The peer answered with a different `ReceptionStatus` than this crate would have.
541    ///
542    /// The interop finding: two readings of the standard, in one line, with the rule that
543    /// produced this side's named.
544    StatusDiffers {
545        /// Which line carried the message that was answered.
546        line: usize,
547        /// Which way that message went.
548        direction: Direction,
549        /// What it was.
550        kind: MessageKind,
551        /// What the transcript records the peer answering.
552        recorded: ReceptionStatusValues,
553        /// What this crate would answer.
554        expected: ReceptionStatusValues,
555        /// Why — the first error, rule identifier first. `None` when this crate would
556        /// have accepted the message and the peer did not.
557        because: Option<String>,
558    },
559    /// A message that must be answered was never answered.
560    ///
561    /// `S2J` requires a `ReceptionStatus` for every message except a `ReceptionStatus`;
562    /// forgetting one is the deadlock `[s2-json #22]` describes, and a transcript is the
563    /// only place it shows.
564    Unanswered {
565        /// Which line.
566        line: usize,
567        /// Which way it went.
568        direction: Direction,
569        /// What it was.
570        kind: MessageKind,
571        /// Its identifier, which the missing answer should have named.
572        message_id: Id,
573    },
574    /// A `ReceptionStatus` answering a message the transcript does not contain.
575    ///
576    /// Either the recording is incomplete or the peer answered something nobody sent.
577    UnmatchedAnswer {
578        /// Which line.
579        line: usize,
580        /// Which way it went.
581        direction: Direction,
582        /// What it claimed to answer.
583        subject: Id,
584    },
585}
586
587impl Finding {
588    /// Which line of the transcript this is about.
589    #[must_use]
590    pub const fn line(&self) -> usize {
591        match self {
592            Finding::Violation { line, .. }
593            | Finding::StatusDiffers { line, .. }
594            | Finding::Unanswered { line, .. }
595            | Finding::UnmatchedAnswer { line, .. } => *line,
596        }
597    }
598
599    /// Whether this finding means the conversation was not conforming.
600    ///
601    /// A warning-severity violation is not: the standard is ambiguous there, and another
602    /// implementation is entitled to read the silence differently.
603    #[must_use]
604    pub fn is_error(&self) -> bool {
605        match self {
606            Finding::Violation { violation, .. } => violation.severity == Severity::Error,
607            _ => true,
608        }
609    }
610}
611
612impl core::fmt::Display for Finding {
613    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
614        match self {
615            Finding::Violation {
616                line,
617                direction,
618                kind,
619                violation,
620            } => write!(f, "{line:>4} {} {kind}: {violation}", direction.as_str()),
621            Finding::StatusDiffers {
622                line,
623                direction,
624                kind,
625                recorded,
626                expected,
627                because,
628            } => {
629                write!(
630                    f,
631                    "{line:>4} {} {kind}: answered {recorded:?}, s2-kit would answer {expected:?}",
632                    direction.as_str()
633                )?;
634                match because {
635                    Some(why) => write!(f, " ({why})"),
636                    None => Ok(()),
637                }
638            }
639            Finding::Unanswered {
640                line,
641                direction,
642                kind,
643                message_id,
644            } => write!(
645                f,
646                "{line:>4} {} {kind}: never answered; no ReceptionStatus names {message_id}",
647                direction.as_str()
648            ),
649            Finding::UnmatchedAnswer {
650                line,
651                direction,
652                subject,
653            } => write!(
654                f,
655                "{line:>4} {} ReceptionStatus: answers {subject}, which no line sent",
656                direction.as_str()
657            ),
658        }
659    }
660}
661
662/// What a replay found, and what it saw.
663#[derive(Debug, Clone, Default)]
664pub struct ReplayReport {
665    /// Everything worth saying, in transcript order.
666    pub findings: Vec<Finding>,
667    /// How many lines were read.
668    pub lines: usize,
669    /// How many of them needed an answer and got one.
670    pub answered: usize,
671}
672
673impl ReplayReport {
674    /// Whether the conversation conformed.
675    #[must_use]
676    pub fn is_conforming(&self) -> bool {
677        !self.findings.iter().any(Finding::is_error)
678    }
679}
680
681impl core::fmt::Display for ReplayReport {
682    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
683        for finding in &self.findings {
684            writeln!(f, "{finding}")?;
685        }
686        write!(
687            f,
688            "{} line(s), {} answered: {}",
689            self.lines,
690            self.answered,
691            if self.is_conforming() { "ok" } else { "FAILED" }
692        )
693    }
694}
695
696/// Replay a recorded conversation and say where it departs from the standard.
697///
698/// Three questions, and only the first is one a message-at-a-time validator can answer:
699///
700/// 1. **Is each message legal, given everything before it?** An [`Analyzer`] keeps one
701///    registry fed from both directions, so an instruction naming an actuator nobody
702///    described is a finding rather than a blind spot.
703/// 2. **Did the peer answer as this crate would?** A disagreement is the interop report.
704/// 3. **Was every message answered at all?**
705///
706/// The clock is the transcript's own, so a validity window or a timer is replayed where it
707/// actually fell.
708///
709/// ```
710/// use s2_kit::testing::{read_s2log, replay};
711///
712/// let log = "\
713/// {\"t\":\"2024-01-01T12:00:00Z\",\"dir\":\"rm>cem\",\"msg\":{\"message_type\":\"FRBC.StorageStatus\",\"message_id\":\"m1\",\"present_fill_level\":52.0}}\n";
714/// let report = replay(&read_s2log(log));
715/// // Nobody answered it — the kind of thing only a transcript shows.
716/// assert_eq!(report.lines, 1);
717/// assert!(!report.is_conforming());
718/// ```
719#[must_use]
720pub fn replay(entries: &[TranscriptEntry]) -> ReplayReport {
721    replay_with(entries, Analyzer::new())
722}
723
724/// As [`replay`], with the observer configured — a different wire profile, strict
725/// decoding, an S2 Connect session where a handshake would be redundant.
726#[must_use]
727pub fn replay_with(entries: &[TranscriptEntry], mut analyzer: Analyzer) -> ReplayReport {
728    let mut report = ReplayReport {
729        lines: entries.len(),
730        ..ReplayReport::default()
731    };
732
733    // What each side actually answered, by the identifier it named. Built first, because
734    // an answer may legitimately arrive several lines after the message it is about.
735    let mut answers: Vec<(Direction, Id, ReceptionStatusValues)> = Vec::new();
736    for entry in entries {
737        if entry.kind == MessageKind::ReceptionStatus
738            && let Ok(Message::ReceptionStatus(status)) = crate::codec::decode(&entry.text)
739        {
740            answers.push((entry.direction, status.subject_message_id, status.status));
741        }
742    }
743
744    for (index, entry) in entries.iter().enumerate() {
745        let line = index + 1;
746        let observed = analyzer.observe(entry.direction.sender(), &entry.text, entry.at);
747
748        for violation in observed.report.violations() {
749            report.findings.push(Finding::Violation {
750                line,
751                direction: entry.direction,
752                kind: entry.kind,
753                violation: violation.clone(),
754            });
755        }
756
757        let Some(message) = &observed.message else {
758            continue;
759        };
760
761        if let Message::ReceptionStatus(status) = message {
762            // An answer to a message this transcript does not contain: either the
763            // recording is incomplete, or the peer answered something nobody sent. The
764            // nil identifier is the one exception — it is what the ecosystem sends when
765            // the message had no readable id at all (erratum E10).
766            let sent = entries.iter().any(|other| {
767                other.direction != entry.direction
768                    && crate::codec::peek(&other.text)
769                        .ok()
770                        .and_then(|p| p.message_id)
771                        == Some(status.subject_message_id)
772            });
773            if !sent && status.subject_message_id != Id::NIL {
774                report.findings.push(Finding::UnmatchedAnswer {
775                    line,
776                    direction: entry.direction,
777                    subject: status.subject_message_id,
778                });
779            }
780            continue;
781        }
782
783        let Some(message_id) = message.id() else {
784            continue;
785        };
786        // The answer must come back the other way.
787        let recorded = answers
788            .iter()
789            .find(|(direction, subject, _)| *direction != entry.direction && *subject == message_id)
790            .map(|(_, _, status)| *status);
791
792        match recorded {
793            None => report.findings.push(Finding::Unanswered {
794                line,
795                direction: entry.direction,
796                kind: entry.kind,
797                message_id,
798            }),
799            Some(recorded) => {
800                report.answered += 1;
801                // `TEMPORARY_ERROR` and `PERMANENT_ERROR` are about the *receiver* — a
802                // storage that was unavailable, a device that was offline — and no
803                // observer can know that. They are never a disagreement.
804                let receiver_specific = matches!(
805                    recorded,
806                    ReceptionStatusValues::TemporaryError | ReceptionStatusValues::PermanentError
807                );
808                if recorded != observed.status && !receiver_specific {
809                    report.findings.push(Finding::StatusDiffers {
810                        line,
811                        direction: entry.direction,
812                        kind: entry.kind,
813                        recorded,
814                        expected: observed.status,
815                        because: observed.diagnostic_label(),
816                    });
817                }
818            }
819        }
820    }
821
822    report.findings.sort_by_key(Finding::line);
823    report
824}