Skip to main content

s2_kit/validate/
state.rs

1//! The normative table of what may be sent when.
2//!
3//! `S2C §State of communication` gives it as a table with one row per state and one
4//! column per role. This module is that table, and it is the only place the rule lives:
5//! the session engines consult it rather than carrying a second copy.
6//!
7//! ```text
8//! WebSocketConnected ──SelectControlType(ct)──▶ ControlTypeActivated(ct)
9//!         ▲                                             │
10//!         └──────── SelectControlType(NO_SELECTION) ─────┘
11//! ```
12
13use crate::message::MessageKind;
14use crate::types::common::{ControlType, EnergyManagementRole};
15
16/// Whether a message may be sent, and if not, why not.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Allowance {
19    /// It may.
20    Yes,
21    /// Not in this state.
22    WrongState,
23    /// Not from this role.
24    WrongRole,
25}
26
27impl Allowance {
28    /// Whether the message is allowed.
29    #[must_use]
30    pub const fn is_allowed(self) -> bool {
31        matches!(self, Allowance::Yes)
32    }
33}
34
35/// Where a session has got to, as the state table sees it.
36///
37/// The standard's own table has two rows — `WebSocket Connected` and
38/// `ControlType <X> activated` — because under S2 Connect the version is settled before
39/// the socket opens and there is nothing before the first row. A bare-WebSocket session
40/// has one more: `S2J messages/Handshake` is exchanged first, and until it is, the two
41/// sides have not agreed which schema the next message is to be read against.
42///
43/// [`Negotiating`](Self::Negotiating) is that row. Leaving it out is what lets a
44/// `PowerMeasurement` sent before the handshake — a message whose *version* nobody has
45/// agreed — pass a check named after the state it is not in.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum Phase {
48    /// Before the handshake has completed, on a session that has one.
49    ///
50    /// Only `Handshake`, `HandshakeResponse`, `SessionRequest` and `ReceptionStatus` may
51    /// cross. A session under S2 Connect is never in this phase: session initiation
52    /// already agreed the version, and the handshake messages "can not be sent".
53    Negotiating,
54    /// `WebSocketConnected`, the standard's first row.
55    ///
56    /// Also where a session sits after `NO_SELECTION` or `NOT_CONTROLABLE`, which are a
57    /// deselection and a selection with nothing to instruct.
58    #[default]
59    Connected,
60    /// `ControlTypeActivated`, the standard's per-control-type rows.
61    Activated(ControlType),
62}
63
64impl Phase {
65    /// The phase a control-type selection puts a session in.
66    ///
67    /// `NO_SELECTION` and `NOT_CONTROLABLE` are [`Connected`](Self::Connected): the first
68    /// is a deselection, the second a legal selection after which nothing control-type
69    /// specific may flow (docs `learn/examples/nocontrol`).
70    #[must_use]
71    pub fn selected(control_type: ControlType) -> Self {
72        if control_type.is_controllable() {
73            Phase::Activated(control_type)
74        } else {
75            Phase::Connected
76        }
77    }
78
79    /// The control type that is active, if one that can be instructed is.
80    #[must_use]
81    pub const fn active_control_type(self) -> Option<ControlType> {
82        match self {
83            Phase::Activated(c) => Some(c),
84            Phase::Negotiating | Phase::Connected => None,
85        }
86    }
87
88    /// The row's name, for a diagnostic.
89    #[must_use]
90    pub fn label(self) -> &'static str {
91        match self {
92            Phase::Negotiating => "negotiating",
93            Phase::Connected => "WebSocketConnected",
94            Phase::Activated(c) => c.abbreviation().unwrap_or("WebSocketConnected"),
95        }
96    }
97}
98
99/// Whether `sender` may send `kind` while the session is in `phase`.
100#[must_use]
101pub fn allowed(phase: Phase, sender: EnergyManagementRole, kind: MessageKind) -> Allowance {
102    use MessageKind as K;
103
104    if let Some(expected) = kind.sender()
105        && expected != sender
106    {
107        return Allowance::WrongRole;
108    }
109
110    let active = phase.active_control_type();
111
112    // The arms below are grouped by *reason*, not by outcome, so several share a body on
113    // purpose: collapsing them would lose the row of the standard's table each belongs to.
114    #[allow(clippy::match_same_arms)]
115    match kind {
116        // Never state-dependent: either side, at any point. A handshake has to be
117        // answerable, and either side may give up at any moment.
118        K::ReceptionStatus | K::SessionRequest => Allowance::Yes,
119
120        // The handshake belongs to the start of a session, and only to it. Under S2
121        // Connect it does not happen at all, which is a warning rather than a state error
122        // (E9 / S2-STATE-003).
123        K::Handshake | K::HandshakeResponse => match phase {
124            Phase::Negotiating | Phase::Connected => Allowance::Yes,
125            Phase::Activated(_) => Allowance::WrongState,
126        },
127
128        // Everything below needs an agreed version to be read against, so nothing but the
129        // handshake itself crosses while one is still being agreed.
130        _ if phase == Phase::Negotiating => Allowance::WrongState,
131
132        // The RM's standing capabilities, and the CEM's ability to change its mind.
133        // `S2C`: measurements and forecasts "can always be used, even if no Control Type
134        // has been activated".
135        K::ResourceManagerDetails
136        | K::PowerMeasurement
137        | K::PowerForecast
138        | K::SelectControlType => Allowance::Yes,
139
140        // Only meaningful once something can be instructed.
141        K::InstructionStatusUpdate | K::RevokeObject => {
142            if active.is_some() {
143                Allowance::Yes
144            } else {
145                Allowance::WrongState
146            }
147        }
148
149        // Everything else belongs to exactly one control type.
150        _ => match (kind.control_type(), active) {
151            (Some(needed), Some(current)) if needed == current => Allowance::Yes,
152            _ => Allowance::WrongState,
153        },
154    }
155}
156
157/// Every message the role may send in the phase, for documentation and tests.
158#[must_use]
159pub fn allowed_kinds(phase: Phase, sender: EnergyManagementRole) -> alloc::vec::Vec<MessageKind> {
160    MessageKind::ALL
161        .iter()
162        .copied()
163        .filter(|k| allowed(phase, sender, *k).is_allowed())
164        .collect()
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use EnergyManagementRole::{Cem, Rm};
171    use alloc::vec::Vec;
172
173    fn names(phase: Phase, sender: EnergyManagementRole) -> Vec<&'static str> {
174        let mut v: Vec<_> = allowed_kinds(phase, sender)
175            .into_iter()
176            .map(crate::message::MessageKind::as_str)
177            .collect();
178        v.sort_unstable();
179        v
180    }
181
182    #[test]
183    fn the_websocket_connected_row_is_the_standards_own() {
184        // `S2C §State of communication`, row "WebSocket Connected". The handshake
185        // messages are added because a bare-WebSocket session exchanges them here.
186        assert_eq!(
187            names(Phase::Connected, Cem),
188            alloc::vec![
189                "Handshake",
190                "HandshakeResponse",
191                "ReceptionStatus",
192                "SelectControlType",
193                "SessionRequest",
194            ]
195        );
196        assert_eq!(
197            names(Phase::Connected, Rm),
198            alloc::vec![
199                "Handshake",
200                "PowerForecast",
201                "PowerMeasurement",
202                "ReceptionStatus",
203                "ResourceManagerDetails",
204                "SessionRequest",
205            ]
206        );
207    }
208
209    #[test]
210    fn nothing_but_the_handshake_crosses_while_the_version_is_still_being_agreed() {
211        // The row the standard's table does not have, because under S2 Connect there is
212        // nothing before `WebSocketConnected`. A bare-WebSocket session does have one,
213        // and a message sent in it is a message whose schema version nobody has agreed.
214        assert_eq!(
215            names(Phase::Negotiating, Rm),
216            alloc::vec!["Handshake", "ReceptionStatus", "SessionRequest"]
217        );
218        assert_eq!(
219            names(Phase::Negotiating, Cem),
220            alloc::vec![
221                "Handshake",
222                "HandshakeResponse",
223                "ReceptionStatus",
224                "SessionRequest",
225            ]
226        );
227        // Including the RM's standing capabilities, which are unrestricted *afterwards*.
228        assert_eq!(
229            allowed(Phase::Negotiating, Rm, MessageKind::PowerMeasurement),
230            Allowance::WrongState
231        );
232        assert_eq!(
233            allowed(Phase::Negotiating, Rm, MessageKind::ResourceManagerDetails),
234            Allowance::WrongState
235        );
236        assert_eq!(
237            allowed(Phase::Negotiating, Cem, MessageKind::SelectControlType),
238            Allowance::WrongState
239        );
240    }
241
242    #[test]
243    fn the_handshake_is_over_once_a_control_type_is_active() {
244        assert_eq!(
245            allowed(
246                Phase::Activated(ControlType::FillRateBasedControl),
247                Rm,
248                MessageKind::Handshake
249            ),
250            Allowance::WrongState
251        );
252    }
253
254    #[test]
255    fn the_frbc_row_is_the_standards_own() {
256        let frbc = Phase::Activated(ControlType::FillRateBasedControl);
257        assert_eq!(
258            names(frbc, Cem),
259            alloc::vec![
260                "FRBC.Instruction",
261                "ReceptionStatus",
262                "RevokeObject",
263                "SelectControlType",
264                "SessionRequest",
265            ]
266        );
267        assert_eq!(
268            names(frbc, Rm),
269            alloc::vec![
270                "FRBC.ActuatorStatus",
271                "FRBC.FillLevelTargetProfile",
272                "FRBC.LeakageBehaviour",
273                "FRBC.StorageStatus",
274                "FRBC.SystemDescription",
275                "FRBC.TimerStatus",
276                "FRBC.UsageForecast",
277                "InstructionStatusUpdate",
278                "PowerForecast",
279                "PowerMeasurement",
280                "ReceptionStatus",
281                "ResourceManagerDetails",
282                "RevokeObject",
283                "SessionRequest",
284            ]
285        );
286    }
287
288    #[test]
289    fn the_pebc_row_is_the_standards_own() {
290        let pebc = Phase::Activated(ControlType::PowerEnvelopeBasedControl);
291        assert_eq!(
292            names(pebc, Cem),
293            alloc::vec![
294                "PEBC.Instruction",
295                "ReceptionStatus",
296                "RevokeObject",
297                "SelectControlType",
298                "SessionRequest",
299            ]
300        );
301        assert_eq!(
302            names(pebc, Rm),
303            alloc::vec![
304                "InstructionStatusUpdate",
305                "PEBC.EnergyConstraint",
306                "PEBC.PowerConstraints",
307                "PowerForecast",
308                "PowerMeasurement",
309                "ReceptionStatus",
310                "ResourceManagerDetails",
311                "RevokeObject",
312                "SessionRequest",
313            ]
314        );
315    }
316
317    #[test]
318    fn selecting_not_controlable_leaves_the_session_where_it_was() {
319        // "NOT_CONTROLABLE" is a real selection, but nothing control-type specific may
320        // follow it: docs `learn/examples/nocontrol`.
321        assert_eq!(
322            Phase::selected(ControlType::NotControllable),
323            Phase::Connected
324        );
325        assert_eq!(Phase::selected(ControlType::NoSelection), Phase::Connected);
326        assert_eq!(
327            Phase::selected(ControlType::FillRateBasedControl),
328            Phase::Activated(ControlType::FillRateBasedControl)
329        );
330    }
331
332    #[test]
333    fn a_control_type_message_in_the_wrong_control_type_is_a_state_error() {
334        assert_eq!(
335            allowed(
336                Phase::Activated(ControlType::PowerEnvelopeBasedControl),
337                Cem,
338                MessageKind::FrbcInstruction
339            ),
340            Allowance::WrongState
341        );
342        assert_eq!(
343            allowed(Phase::Connected, Cem, MessageKind::FrbcInstruction),
344            Allowance::WrongState
345        );
346    }
347
348    #[test]
349    fn a_message_from_the_wrong_role_is_a_role_error() {
350        // An RM does not instruct, and a CEM does not describe itself as a resource.
351        // The role is checked before the phase, so it is the answer even where both are
352        // wrong: a peer told "not in this state" would try again later for ever.
353        assert_eq!(
354            allowed(
355                Phase::Activated(ControlType::FillRateBasedControl),
356                Rm,
357                MessageKind::FrbcInstruction
358            ),
359            Allowance::WrongRole
360        );
361        assert_eq!(
362            allowed(Phase::Connected, Cem, MessageKind::ResourceManagerDetails),
363            Allowance::WrongRole
364        );
365        assert_eq!(
366            allowed(Phase::Connected, Rm, MessageKind::SelectControlType),
367            Allowance::WrongRole
368        );
369        assert_eq!(
370            allowed(Phase::Negotiating, Cem, MessageKind::ResourceManagerDetails),
371            Allowance::WrongRole
372        );
373    }
374
375    #[test]
376    fn revocation_is_accepted_from_both_roles() {
377        // E6: the state table lists RevokeObject only for the RM, but RevokableObjects
378        // contains every instruction type, which only a CEM sends. Refusing the CEM's
379        // revocation would make most of that enum unreachable.
380        for role in [Cem, Rm] {
381            assert_eq!(
382                allowed(
383                    Phase::Activated(ControlType::FillRateBasedControl),
384                    role,
385                    MessageKind::RevokeObject
386                ),
387                Allowance::Yes
388            );
389        }
390    }
391
392    #[test]
393    fn instruction_statuses_need_something_to_be_about() {
394        assert_eq!(
395            allowed(Phase::Connected, Rm, MessageKind::InstructionStatusUpdate),
396            Allowance::WrongState
397        );
398        assert_eq!(
399            allowed(
400                Phase::Activated(ControlType::OperationModeBasedControl),
401                Rm,
402                MessageKind::InstructionStatusUpdate
403            ),
404            Allowance::Yes
405        );
406    }
407
408    #[test]
409    fn every_message_is_allowed_somewhere() {
410        // A message no phase and no role can send would be a hole in the table.
411        for kind in MessageKind::ALL {
412            let reachable = [
413                Phase::Negotiating,
414                Phase::Connected,
415                Phase::Activated(ControlType::PowerEnvelopeBasedControl),
416                Phase::Activated(ControlType::PowerProfileBasedControl),
417                Phase::Activated(ControlType::OperationModeBasedControl),
418                Phase::Activated(ControlType::FillRateBasedControl),
419                Phase::Activated(ControlType::DemandDrivenBasedControl),
420            ]
421            .into_iter()
422            .any(|phase| {
423                [Cem, Rm]
424                    .into_iter()
425                    .any(|role| allowed(phase, role, *kind).is_allowed())
426            });
427            assert!(reachable, "{kind} can never be sent");
428        }
429    }
430}