Skip to main content

s2_kit/session/
analyze.rs

1//! Watching a conversation without being in it.
2//!
3//! *Is this conversation legal?* is a question neither
4//! [`Context::empty`](crate::validate::Context::empty) nor a session can answer. An empty
5//! context knows nothing of what came before; a session knows only its own half — a
6//! Resource Manager's registry holds what it *received*, so replaying a transcript
7//! through one validates the instructions and misses the descriptions they name.
8//!
9//! An observer is the third thing: one [`Registry`] fed from **both** directions, and
10//! every message judged against it.
11//!
12//! ```
13//! use s2_kit::prelude::*;
14//! use s2_kit::session::Analyzer;
15//! use s2_kit::types::common::EnergyManagementRole::{Cem, Rm};
16//! use s2_kit::validate::rules;
17//!
18//! let now = Timestamp::UNIX_EPOCH;
19//! let mut analyzer = Analyzer::new();
20//!
21//! // The manager instructs an actuator the resource never described.
22//! let observed = analyzer.observe(
23//!     Cem,
24//!     r#"{"message_type":"FRBC.Instruction","message_id":"m1","id":"i1",
25//!         "actuator_id":"nope","operation_mode":"om1","operation_mode_factor":0.5,
26//!         "execution_time":"1970-01-01T00:00:00Z","abnormal_condition":false}"#,
27//!     now,
28//! );
29//! // Nothing but a stateful observer can say this: the message is schema-perfect.
30//! assert!(observed.report.contains(rules::NOT_ALLOWED_IN_STATE));
31//! let _ = Rm;
32//! ```
33
34use alloc::string::String;
35use alloc::vec::Vec;
36
37use super::core::Registry;
38use crate::codec::{self, DecodeError, DecodeOptions, Strictness};
39use crate::message::{Message, MessageKind};
40use crate::types::common::{ControlType, EnergyManagementRole, ReceptionStatusValues};
41use crate::types::{Duration, Id, Timestamp, WireProfile};
42use crate::validate::{Phase, Report, Validate, rules};
43
44/// What an [`Analyzer`] made of one frame.
45#[derive(Debug, Clone, PartialEq)]
46#[non_exhaustive]
47pub struct Observed {
48    /// Which side sent it.
49    pub sender: EnergyManagementRole,
50    /// What it claimed to be, where that could be read at all.
51    pub kind: Option<MessageKind>,
52    /// The message, when it decoded.
53    pub message: Option<Message>,
54    /// Properties the schema does not define, removed in [`Strictness::Lenient`].
55    pub pruned: Vec<String>,
56    /// Everything wrong with it — the intra-message rules and the cross-message ones.
57    pub report: Report,
58    /// The `ReceptionStatus` a **receiver** should have answered this message with.
59    ///
60    /// The same choice [`RmSession`](super::RmSession) and
61    /// [`CemSession`](super::CemSession) make inside `handle_text`, by the same code, so a
62    /// recorded conversation can be diffed against it.
63    ///
64    /// `TEMPORARY_ERROR` and `PERMANENT_ERROR` are never produced: they are about the
65    /// receiver rather than the message, and depend on an
66    /// [`InboundPolicy`](super::InboundPolicy) an observer does not have.
67    pub status: ReceptionStatusValues,
68}
69
70impl Observed {
71    /// Whether anything at all was reported.
72    #[must_use]
73    pub fn is_clean(&self) -> bool {
74        self.report.is_empty()
75    }
76
77    /// Whether a receiver would have accepted this message.
78    #[must_use]
79    pub fn accepted(&self) -> bool {
80        self.status == ReceptionStatusValues::Ok
81    }
82
83    /// The `diagnostic_label` a refusal should carry: the first error, rule id first.
84    #[must_use]
85    pub fn diagnostic_label(&self) -> Option<String> {
86        self.report.diagnostic_label()
87    }
88}
89
90/// A stateful observer of a conversation it is not part of.
91///
92/// Feed it every frame, in order, with the role that sent it. It keeps one [`Registry`]
93/// from both sides, tracks the active control type, and validates each message with the
94/// full cross-message [`Context`](crate::validate::Context) — so `S2-FRBC-003`,
95/// `S2-STATE-001`, `S2-INST-001` and `S2-PEBC-006` fire here and nowhere else outside a
96/// live session.
97///
98/// Decoding is **lenient** by default: an analyzer that refuses a message carrying a
99/// vendor extension hides the peer's real bug behind its own strictness.
100/// [`Analyzer::strict`] is the other choice.
101#[derive(Debug, Clone)]
102pub struct Analyzer {
103    registry: Registry,
104    profile: WireProfile,
105    strictness: Strictness,
106    phase: Phase,
107    seen: Vec<Id>,
108    skew_tolerance: Duration,
109    s2_connect: bool,
110    max_message_bytes: usize,
111}
112
113impl Default for Analyzer {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119impl Analyzer {
120    /// An observer that has seen nothing yet.
121    #[must_use]
122    pub fn new() -> Self {
123        Self {
124            registry: Registry::default(),
125            profile: WireProfile::V1_0_0,
126            strictness: Strictness::Lenient,
127            // `Connected`, not `Negotiating`: a transcript may start anywhere, and an
128            // observer that assumed it had seen the beginning would invent a refusal for
129            // every message in a capture that starts mid-session. A `Handshake` is legal
130            // in this row too, so nothing real is lost.
131            phase: Phase::Connected,
132            seen: Vec::new(),
133            skew_tolerance: Duration::from_secs(30),
134            s2_connect: false,
135            max_message_bytes: DecodeOptions::DEFAULT_MAX_BYTES,
136        }
137    }
138
139    /// Decode against a particular wire profile.
140    ///
141    /// A transcript of a `0.0.2-beta` session must be read as one, or every
142    /// `DDBC.SystemDescription` in it is a profile mismatch.
143    #[must_use]
144    pub const fn profile(mut self, profile: WireProfile) -> Self {
145        self.profile = profile;
146        self
147    }
148
149    /// Refuse a message with a property the schema does not define, as an endpoint would.
150    #[must_use]
151    pub const fn strict(mut self) -> Self {
152        self.strictness = Strictness::Strict;
153        self
154    }
155
156    /// Read the conversation as one carried by S2 Connect, where a handshake is redundant.
157    #[must_use]
158    pub const fn over_s2_connect(mut self) -> Self {
159        self.s2_connect = true;
160        self
161    }
162
163    /// How far a peer's clock may differ before it is worth reporting.
164    #[must_use]
165    pub const fn skew_tolerance(mut self, tolerance: Duration) -> Self {
166        self.skew_tolerance = tolerance;
167        self
168    }
169
170    /// Everything the conversation has published, from both sides.
171    #[must_use]
172    pub const fn registry(&self) -> &Registry {
173        &self.registry
174    }
175
176    /// The control type in force, as the conversation has selected it.
177    #[must_use]
178    pub const fn active_control_type(&self) -> Option<ControlType> {
179        self.phase.active_control_type()
180    }
181
182    /// Which row of the state table the conversation is on.
183    #[must_use]
184    pub const fn phase(&self) -> Phase {
185        self.phase
186    }
187
188    /// Observe one frame.
189    ///
190    /// Total: a frame that is not JSON, not S2 or not in the profile yields a report
191    /// carrying `S2-MSG-004`, not an error — an analyzer that stops at the first bad frame
192    /// stops exactly where it was needed.
193    pub fn observe(
194        &mut self,
195        sender: EnergyManagementRole,
196        text: &str,
197        now: Timestamp,
198    ) -> Observed {
199        let options = DecodeOptions {
200            strictness: self.strictness,
201            profile: self.profile,
202            max_bytes: self.max_message_bytes,
203        };
204        // A description whose `valid_from` has arrived is in force before this message is
205        // judged against it.
206        let _ = self.registry.activate_due(now);
207
208        match codec::decode_with(text, &options) {
209            Err(error) => Self::on_decode_error(sender, &error),
210            Ok(decoded) => {
211                let mut report = Report::new();
212                for path in &decoded.pruned {
213                    report.push(
214                        rules::UNKNOWN_PROPERTY,
215                        path,
216                        "property is not defined by the schema and was removed",
217                    );
218                }
219                let kind = decoded.message.kind();
220                {
221                    let ctx = self.registry.context(
222                        self.profile,
223                        sender,
224                        self.phase,
225                        self.s2_connect,
226                        now,
227                        &self.seen,
228                        self.skew_tolerance,
229                    );
230                    report.extend(decoded.message.validate(&ctx));
231                }
232                let status = report.reception_status();
233                self.record(&decoded.message, now);
234                Observed {
235                    sender,
236                    kind: Some(kind),
237                    message: Some(decoded.message),
238                    pruned: decoded.pruned,
239                    report,
240                    status,
241                }
242            }
243        }
244    }
245
246    fn on_decode_error(sender: EnergyManagementRole, error: &DecodeError) -> Observed {
247        let mut report = Report::new();
248        report.push(
249            rules::DECODE_FAILED,
250            "",
251            alloc::string::ToString::to_string(error),
252        );
253        Observed {
254            sender,
255            kind: error.peek().and_then(|p| p.kind),
256            message: None,
257            pruned: Vec::new(),
258            report,
259            status: error.status_value(),
260        }
261    }
262
263    /// Fold a message into what is known, whichever direction it went.
264    fn record(&mut self, message: &Message, now: Timestamp) {
265        match message {
266            // A control type is active from the moment it is selected. An observer cannot
267            // wait for the acknowledgement the way a `CemSession` does: it may not have
268            // been recorded, and a transcript that starts mid-session never carries it.
269            Message::SelectControlType(select) => {
270                self.phase = Phase::selected(select.control_type);
271            }
272            Message::RevokeObject(revoke) => {
273                self.registry.revoke(revoke.object_type, revoke.object_id);
274            }
275            _ => self.registry.record(message, Some(now)),
276        }
277        if let Some(id) = message.id()
278            && !self.seen.contains(&id)
279        {
280            self.seen.push(id);
281            if self.seen.len() > Registry::MAX_TRACKED {
282                self.seen.remove(0);
283            }
284        }
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use crate::types::common::EnergyManagementRole::{Cem, Rm};
292    // Explicit because the crate is `no_std`: without `std` there is no prelude to take
293    // `.to_string()` from, and `cargo test --lib --no-default-features` is a CI job.
294    use alloc::string::ToString;
295    use alloc::vec;
296
297    fn at(s: &str) -> Timestamp {
298        s.parse().unwrap_or(Timestamp::UNIX_EPOCH)
299    }
300
301    const DETAILS: &str = r#"{"message_type":"ResourceManagerDetails","message_id":"d1",
302        "resource_id":"battery-1","roles":[{"role":"ENERGY_STORAGE","commodity":"ELECTRICITY"}],
303        "instruction_processing_delay":500,
304        "available_control_types":["FILL_RATE_BASED_CONTROL"],
305        "provides_forecast":false,
306        "provides_power_measurement_types":["ELECTRIC.POWER.3_PHASE_SYMMETRIC"]}"#;
307
308    const SYSTEM: &str = r#"{"message_type":"FRBC.SystemDescription","message_id":"s1",
309        "valid_from":"2024-01-01T00:00:00Z",
310        "actuators":[{"id":"actuator1","supported_commodities":["ELECTRICITY"],
311          "operation_modes":[{"id":"om1","elements":[{"fill_level_range":{"start_of_range":0,"end_of_range":100},
312            "fill_rate":{"start_of_range":0,"end_of_range":0.001},
313            "power_ranges":[{"start_of_range":0,"end_of_range":5000,
314              "commodity_quantity":"ELECTRIC.POWER.3_PHASE_SYMMETRIC"}]}],
315            "abnormal_condition_only":false}],
316          "transitions":[],"timers":[]}],
317        "storage":{"provides_leakage_behaviour":false,"provides_fill_level_target_profile":false,
318          "provides_usage_forecast":false,
319          "fill_level_range":{"start_of_range":0,"end_of_range":100}}}"#;
320
321    fn instruction(id: &str, actuator: &str) -> alloc::string::String {
322        alloc::format!(
323            r#"{{"message_type":"FRBC.Instruction","message_id":"{id}","id":"i-{id}",
324                "actuator_id":"{actuator}","operation_mode":"om1","operation_mode_factor":0.5,
325                "execution_time":"2024-01-01T12:00:00Z","abnormal_condition":false}}"#
326        )
327    }
328
329    /// Drive a legal opening: details, control type selected, system description.
330    fn opened() -> Analyzer {
331        let mut a = Analyzer::new();
332        let now = at("2024-01-01T12:00:00Z");
333        assert!(a.observe(Rm, DETAILS, now).is_clean());
334        assert!(
335            a.observe(
336                Cem,
337                r#"{"message_type":"SelectControlType","message_id":"c1",
338                    "control_type":"FILL_RATE_BASED_CONTROL"}"#,
339                now
340            )
341            .is_clean()
342        );
343        assert_eq!(
344            a.active_control_type(),
345            Some(ControlType::FillRateBasedControl)
346        );
347        let observed = a.observe(Rm, SYSTEM, now);
348        assert!(observed.is_clean(), "{}", observed.report);
349        a
350    }
351
352    #[test]
353    fn an_instruction_is_checked_against_a_description_the_observer_only_watched() {
354        // The whole point: neither side of this exchange is the observer, and no single
355        // session holds both halves. The `FRBC.SystemDescription` came from the resource
356        // and the instruction from the manager.
357        let mut a = opened();
358        let now = at("2024-01-01T12:00:01Z");
359
360        let good = a.observe(Cem, &instruction("m1", "actuator1"), now);
361        assert!(good.is_clean(), "{}", good.report);
362
363        let bad = a.observe(Cem, &instruction("m2", "nope"), now);
364        assert!(
365            bad.report.contains(rules::FRBC_UNKNOWN_ACTUATOR),
366            "{}",
367            bad.report
368        );
369    }
370
371    #[test]
372    fn the_state_table_applies_to_a_conversation_nobody_is_in() {
373        let mut a = Analyzer::new();
374        let now = at("2024-01-01T12:00:00Z");
375        // No control type has been selected, so an instruction is out of order.
376        let observed = a.observe(Cem, &instruction("m1", "actuator1"), now);
377        assert!(observed.report.contains(rules::NOT_ALLOWED_IN_STATE));
378
379        // And a message from the wrong side is caught too.
380        let observed = a.observe(
381            Rm,
382            r#"{"message_type":"SelectControlType","message_id":"c1",
383            "control_type":"FILL_RATE_BASED_CONTROL"}"#,
384            now,
385        );
386        assert!(observed.report.contains(rules::NOT_ALLOWED_FOR_ROLE));
387    }
388
389    #[test]
390    fn a_reused_instruction_identifier_is_seen_across_the_whole_conversation() {
391        let mut a = opened();
392        let now = at("2024-01-01T12:00:01Z");
393        let first = a.observe(Cem, &instruction("m1", "actuator1"), now);
394        assert!(first.is_clean(), "{}", first.report);
395        // Same instruction id, different message id.
396        let text = instruction("m1", "actuator1").replace("\"m1\"", "\"m2\"");
397        let again = a.observe(Cem, &text, now);
398        assert!(
399            again.report.contains(rules::DUPLICATE_INSTRUCTION_ID),
400            "{}",
401            again.report
402        );
403    }
404
405    #[test]
406    fn a_vendor_extension_is_reported_rather_than_refused() {
407        let mut a = Analyzer::new();
408        let now = at("2024-01-01T12:00:00Z");
409        let observed = a.observe(
410            Rm,
411            r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
412                "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
413            now,
414        );
415        assert_eq!(observed.pruned, vec!["/acme_cell_temperature".to_string()]);
416        assert!(observed.report.contains(rules::UNKNOWN_PROPERTY));
417        assert!(observed.message.is_some(), "the message is still forwarded");
418
419        // Strictly, the same frame does not decode at all — and that is a finding, not a
420        // reason to stop reading the file.
421        let mut a = Analyzer::new().strict();
422        let observed = a.observe(
423            Rm,
424            r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
425                "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
426            now,
427        );
428        assert!(observed.message.is_none());
429        assert!(observed.report.contains(rules::DECODE_FAILED));
430        assert_eq!(observed.kind, Some(MessageKind::FrbcStorageStatus));
431    }
432
433    #[test]
434    fn a_frame_that_is_not_s2_at_all_is_a_finding_and_not_the_end() {
435        let mut a = Analyzer::new();
436        let now = at("2024-01-01T12:00:00Z");
437        let observed = a.observe(Rm, "{ not json", now);
438        assert!(observed.report.contains(rules::DECODE_FAILED));
439        assert_eq!(observed.kind, None);
440        // And the next frame is still read.
441        assert!(a.observe(Rm, DETAILS, now).is_clean());
442    }
443
444    #[test]
445    fn a_description_published_for_later_is_in_force_when_its_time_comes() {
446        let mut a = Analyzer::new();
447        let early = at("2024-01-01T12:00:00Z");
448        a.observe(
449            Cem,
450            r#"{"message_type":"SelectControlType","message_id":"c1",
451                "control_type":"FILL_RATE_BASED_CONTROL"}"#,
452            early,
453        );
454        let later = SYSTEM.replace("2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z");
455        assert!(a.observe(Rm, &later, early).is_clean());
456        // Queued, not in force: nothing yet describes an actuator, so an instruction is
457        // unjudgeable rather than wrong — a rule that fired here would accuse the CEM of
458        // naming an actuator that simply has not been announced yet.
459        assert!(a.registry().frbc.is_none());
460        let too_soon = a.observe(Cem, &instruction("m1", "actuator1"), early);
461        assert!(!too_soon.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
462
463        // After `valid_from` it is in force, and now the same instruction is checked
464        // against it — including the one that names something it does not describe.
465        let after = at("2024-01-02T00:00:01Z");
466        let now_fine = a.observe(Cem, &instruction("m2", "actuator1"), after);
467        assert!(now_fine.is_clean(), "{}", now_fine.report);
468        assert!(a.registry().frbc.is_some());
469        let wrong = a.observe(Cem, &instruction("m3", "nope"), after);
470        assert!(wrong.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
471    }
472}