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::{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    active: Option<ControlType>,
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            active: None,
128            seen: Vec::new(),
129            skew_tolerance: Duration::from_secs(30),
130            s2_connect: false,
131            max_message_bytes: DecodeOptions::DEFAULT_MAX_BYTES,
132        }
133    }
134
135    /// Decode against a particular wire profile.
136    ///
137    /// A transcript of a `0.0.2-beta` session must be read as one, or every
138    /// `DDBC.SystemDescription` in it is a profile mismatch.
139    #[must_use]
140    pub const fn profile(mut self, profile: WireProfile) -> Self {
141        self.profile = profile;
142        self
143    }
144
145    /// Refuse a message with a property the schema does not define, as an endpoint would.
146    #[must_use]
147    pub const fn strict(mut self) -> Self {
148        self.strictness = Strictness::Strict;
149        self
150    }
151
152    /// Read the conversation as one carried by S2 Connect, where a handshake is redundant.
153    #[must_use]
154    pub const fn over_s2_connect(mut self) -> Self {
155        self.s2_connect = true;
156        self
157    }
158
159    /// How far a peer's clock may differ before it is worth reporting.
160    #[must_use]
161    pub const fn skew_tolerance(mut self, tolerance: Duration) -> Self {
162        self.skew_tolerance = tolerance;
163        self
164    }
165
166    /// Everything the conversation has published, from both sides.
167    #[must_use]
168    pub const fn registry(&self) -> &Registry {
169        &self.registry
170    }
171
172    /// The control type in force, as the conversation has selected it.
173    #[must_use]
174    pub const fn active_control_type(&self) -> Option<ControlType> {
175        self.active
176    }
177
178    /// Observe one frame.
179    ///
180    /// Total: a frame that is not JSON, not S2 or not in the profile yields a report
181    /// carrying `S2-MSG-004`, not an error — an analyzer that stops at the first bad frame
182    /// stops exactly where it was needed.
183    pub fn observe(
184        &mut self,
185        sender: EnergyManagementRole,
186        text: &str,
187        now: Timestamp,
188    ) -> Observed {
189        let options = DecodeOptions {
190            strictness: self.strictness,
191            profile: self.profile,
192            max_bytes: self.max_message_bytes,
193        };
194        // A description whose `valid_from` has arrived is in force before this message is
195        // judged against it.
196        let _ = self.registry.activate_due(now);
197
198        match codec::decode_with(text, &options) {
199            Err(error) => Self::on_decode_error(sender, &error),
200            Ok(decoded) => {
201                let mut report = Report::new();
202                for path in &decoded.pruned {
203                    report.push(
204                        rules::UNKNOWN_PROPERTY,
205                        path,
206                        "property is not defined by the schema and was removed",
207                    );
208                }
209                let kind = decoded.message.kind();
210                {
211                    let ctx = self.registry.context(
212                        self.profile,
213                        sender,
214                        self.active,
215                        self.s2_connect,
216                        now,
217                        &self.seen,
218                        self.skew_tolerance,
219                    );
220                    report.extend(decoded.message.validate(&ctx));
221                }
222                let status = report.reception_status();
223                self.record(&decoded.message, now);
224                Observed {
225                    sender,
226                    kind: Some(kind),
227                    message: Some(decoded.message),
228                    pruned: decoded.pruned,
229                    report,
230                    status,
231                }
232            }
233        }
234    }
235
236    fn on_decode_error(sender: EnergyManagementRole, error: &DecodeError) -> Observed {
237        let mut report = Report::new();
238        report.push(
239            rules::DECODE_FAILED,
240            "",
241            alloc::string::ToString::to_string(error),
242        );
243        Observed {
244            sender,
245            kind: error.peek().and_then(|p| p.kind),
246            message: None,
247            pruned: Vec::new(),
248            report,
249            status: error.status_value(),
250        }
251    }
252
253    /// Fold a message into what is known, whichever direction it went.
254    fn record(&mut self, message: &Message, now: Timestamp) {
255        match message {
256            // A control type is active from the moment it is selected. An observer cannot
257            // wait for the acknowledgement the way a `CemSession` does: it may not have
258            // been recorded, and a transcript that starts mid-session never carries it.
259            Message::SelectControlType(select) => {
260                self.active = (select.control_type != ControlType::NoSelection)
261                    .then_some(select.control_type);
262            }
263            Message::RevokeObject(revoke) => {
264                self.registry.revoke(revoke.object_type, revoke.object_id);
265            }
266            _ => self.registry.record(message, Some(now)),
267        }
268        if let Some(id) = message.id()
269            && !self.seen.contains(&id)
270        {
271            self.seen.push(id);
272            if self.seen.len() > Registry::MAX_TRACKED {
273                self.seen.remove(0);
274            }
275        }
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use crate::types::common::EnergyManagementRole::{Cem, Rm};
283    // Explicit because the crate is `no_std`: without `std` there is no prelude to take
284    // `.to_string()` from, and `cargo test --lib --no-default-features` is a CI job.
285    use alloc::string::ToString;
286    use alloc::vec;
287
288    fn at(s: &str) -> Timestamp {
289        s.parse().unwrap_or(Timestamp::UNIX_EPOCH)
290    }
291
292    const DETAILS: &str = r#"{"message_type":"ResourceManagerDetails","message_id":"d1",
293        "resource_id":"battery-1","roles":[{"role":"ENERGY_STORAGE","commodity":"ELECTRICITY"}],
294        "instruction_processing_delay":500,
295        "available_control_types":["FILL_RATE_BASED_CONTROL"],
296        "provides_forecast":false,
297        "provides_power_measurement_types":["ELECTRIC.POWER.3_PHASE_SYMMETRIC"]}"#;
298
299    const SYSTEM: &str = r#"{"message_type":"FRBC.SystemDescription","message_id":"s1",
300        "valid_from":"2024-01-01T00:00:00Z",
301        "actuators":[{"id":"actuator1","supported_commodities":["ELECTRICITY"],
302          "operation_modes":[{"id":"om1","elements":[{"fill_level_range":{"start_of_range":0,"end_of_range":100},
303            "fill_rate":{"start_of_range":0,"end_of_range":0.001},
304            "power_ranges":[{"start_of_range":0,"end_of_range":5000,
305              "commodity_quantity":"ELECTRIC.POWER.3_PHASE_SYMMETRIC"}]}],
306            "abnormal_condition_only":false}],
307          "transitions":[],"timers":[]}],
308        "storage":{"provides_leakage_behaviour":false,"provides_fill_level_target_profile":false,
309          "provides_usage_forecast":false,
310          "fill_level_range":{"start_of_range":0,"end_of_range":100}}}"#;
311
312    fn instruction(id: &str, actuator: &str) -> alloc::string::String {
313        alloc::format!(
314            r#"{{"message_type":"FRBC.Instruction","message_id":"{id}","id":"i-{id}",
315                "actuator_id":"{actuator}","operation_mode":"om1","operation_mode_factor":0.5,
316                "execution_time":"2024-01-01T12:00:00Z","abnormal_condition":false}}"#
317        )
318    }
319
320    /// Drive a legal opening: details, control type selected, system description.
321    fn opened() -> Analyzer {
322        let mut a = Analyzer::new();
323        let now = at("2024-01-01T12:00:00Z");
324        assert!(a.observe(Rm, DETAILS, now).is_clean());
325        assert!(
326            a.observe(
327                Cem,
328                r#"{"message_type":"SelectControlType","message_id":"c1",
329                    "control_type":"FILL_RATE_BASED_CONTROL"}"#,
330                now
331            )
332            .is_clean()
333        );
334        assert_eq!(
335            a.active_control_type(),
336            Some(ControlType::FillRateBasedControl)
337        );
338        let observed = a.observe(Rm, SYSTEM, now);
339        assert!(observed.is_clean(), "{}", observed.report);
340        a
341    }
342
343    #[test]
344    fn an_instruction_is_checked_against_a_description_the_observer_only_watched() {
345        // The whole point: neither side of this exchange is the observer, and no single
346        // session holds both halves. The `FRBC.SystemDescription` came from the resource
347        // and the instruction from the manager.
348        let mut a = opened();
349        let now = at("2024-01-01T12:00:01Z");
350
351        let good = a.observe(Cem, &instruction("m1", "actuator1"), now);
352        assert!(good.is_clean(), "{}", good.report);
353
354        let bad = a.observe(Cem, &instruction("m2", "nope"), now);
355        assert!(
356            bad.report.contains(rules::FRBC_UNKNOWN_ACTUATOR),
357            "{}",
358            bad.report
359        );
360    }
361
362    #[test]
363    fn the_state_table_applies_to_a_conversation_nobody_is_in() {
364        let mut a = Analyzer::new();
365        let now = at("2024-01-01T12:00:00Z");
366        // No control type has been selected, so an instruction is out of order.
367        let observed = a.observe(Cem, &instruction("m1", "actuator1"), now);
368        assert!(observed.report.contains(rules::NOT_ALLOWED_IN_STATE));
369
370        // And a message from the wrong side is caught too.
371        let observed = a.observe(
372            Rm,
373            r#"{"message_type":"SelectControlType","message_id":"c1",
374            "control_type":"FILL_RATE_BASED_CONTROL"}"#,
375            now,
376        );
377        assert!(observed.report.contains(rules::NOT_ALLOWED_FOR_ROLE));
378    }
379
380    #[test]
381    fn a_reused_instruction_identifier_is_seen_across_the_whole_conversation() {
382        let mut a = opened();
383        let now = at("2024-01-01T12:00:01Z");
384        let first = a.observe(Cem, &instruction("m1", "actuator1"), now);
385        assert!(first.is_clean(), "{}", first.report);
386        // Same instruction id, different message id.
387        let text = instruction("m1", "actuator1").replace("\"m1\"", "\"m2\"");
388        let again = a.observe(Cem, &text, now);
389        assert!(
390            again.report.contains(rules::DUPLICATE_INSTRUCTION_ID),
391            "{}",
392            again.report
393        );
394    }
395
396    #[test]
397    fn a_vendor_extension_is_reported_rather_than_refused() {
398        let mut a = Analyzer::new();
399        let now = at("2024-01-01T12:00:00Z");
400        let observed = a.observe(
401            Rm,
402            r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
403                "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
404            now,
405        );
406        assert_eq!(observed.pruned, vec!["/acme_cell_temperature".to_string()]);
407        assert!(observed.report.contains(rules::UNKNOWN_PROPERTY));
408        assert!(observed.message.is_some(), "the message is still forwarded");
409
410        // Strictly, the same frame does not decode at all — and that is a finding, not a
411        // reason to stop reading the file.
412        let mut a = Analyzer::new().strict();
413        let observed = a.observe(
414            Rm,
415            r#"{"message_type":"FRBC.StorageStatus","message_id":"m1",
416                "present_fill_level":52.0,"acme_cell_temperature":31.4}"#,
417            now,
418        );
419        assert!(observed.message.is_none());
420        assert!(observed.report.contains(rules::DECODE_FAILED));
421        assert_eq!(observed.kind, Some(MessageKind::FrbcStorageStatus));
422    }
423
424    #[test]
425    fn a_frame_that_is_not_s2_at_all_is_a_finding_and_not_the_end() {
426        let mut a = Analyzer::new();
427        let now = at("2024-01-01T12:00:00Z");
428        let observed = a.observe(Rm, "{ not json", now);
429        assert!(observed.report.contains(rules::DECODE_FAILED));
430        assert_eq!(observed.kind, None);
431        // And the next frame is still read.
432        assert!(a.observe(Rm, DETAILS, now).is_clean());
433    }
434
435    #[test]
436    fn a_description_published_for_later_is_in_force_when_its_time_comes() {
437        let mut a = Analyzer::new();
438        let early = at("2024-01-01T12:00:00Z");
439        a.observe(
440            Cem,
441            r#"{"message_type":"SelectControlType","message_id":"c1",
442                "control_type":"FILL_RATE_BASED_CONTROL"}"#,
443            early,
444        );
445        let later = SYSTEM.replace("2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z");
446        assert!(a.observe(Rm, &later, early).is_clean());
447        // Queued, not in force: nothing yet describes an actuator, so an instruction is
448        // unjudgeable rather than wrong — a rule that fired here would accuse the CEM of
449        // naming an actuator that simply has not been announced yet.
450        assert!(a.registry().frbc.is_none());
451        let too_soon = a.observe(Cem, &instruction("m1", "actuator1"), early);
452        assert!(!too_soon.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
453
454        // After `valid_from` it is in force, and now the same instruction is checked
455        // against it — including the one that names something it does not describe.
456        let after = at("2024-01-02T00:00:01Z");
457        let now_fine = a.observe(Cem, &instruction("m2", "actuator1"), after);
458        assert!(now_fine.is_clean(), "{}", now_fine.report);
459        assert!(a.registry().frbc.is_some());
460        let wrong = a.observe(Cem, &instruction("m3", "nope"), after);
461        assert!(wrong.report.contains(rules::FRBC_UNKNOWN_ACTUATOR));
462    }
463}