Skip to main content

s2_kit/session/
core.rs

1//! What both session engines are built on: the outbox, the acknowledgement ledger, and
2//! the registry of everything either side has published.
3
4use alloc::boxed::Box;
5use alloc::collections::VecDeque;
6use alloc::string::String;
7use alloc::vec::Vec;
8
9use crate::codec::{self, DecodeOptions};
10use crate::message::{Message, MessageKind};
11use crate::types::common::{
12    Consequence, ControlType, EnergyManagementRole, InstructionStatus, ReceptionStatus,
13    ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
14};
15use crate::types::{Duration, Id, Timestamp, WireProfile, ddbc, frbc, ombc, pebc, ppbc};
16use crate::validate::{Context, TimerState};
17
18/// A message a driver should put on the wire.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Outgoing {
21    /// The encoded message, ready to send as one text frame.
22    pub text: String,
23    /// What it is.
24    pub kind: MessageKind,
25    /// Its identifier, for correlating with the acknowledgement that follows.
26    pub message_id: Option<Id>,
27}
28
29/// A message that is waiting for its acknowledgement.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct MessageHandle {
32    /// The `message_id` that was sent.
33    pub id: Id,
34    /// What was sent.
35    pub kind: MessageKind,
36}
37
38/// How the session agrees a protocol version with its peer.
39#[derive(Debug, Clone, PartialEq, Eq, Default)]
40pub enum Negotiation {
41    /// Exchange `Handshake` and `HandshakeResponse`, as a bare WebSocket session does.
42    #[default]
43    Handshake,
44    /// The version was already agreed — by S2 Connect's session initiation, where
45    /// `S2C §Communication - JSON messages` says the handshake messages "can not be
46    /// sent".
47    PreNegotiated(WireProfile),
48}
49
50/// Where a session has got to.
51///
52/// `Connected` and `ControlTypeSelected` are the standard's own two states,
53/// `WebSocketConnected` and `ControlTypeActivated`. The rest are this crate's: a session
54/// that has not started, one that is mid-handshake, and one that is over.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum SessionState {
57    /// Nothing has been sent yet.
58    Idle,
59    /// The handshake is in progress.
60    Handshaking,
61    /// `WebSocketConnected`: details, measurements and forecasts flow.
62    Connected,
63    /// `ControlTypeActivated`. Note that `NOT_CONTROLABLE` is a legal selection and
64    /// lands here too, with nothing control-type specific allowed after it.
65    ControlTypeSelected(ControlType),
66    /// Over, and why.
67    Closed(CloseReason),
68}
69
70impl SessionState {
71    /// Which row of `S2C §State of communication` this session is on.
72    ///
73    /// [`Idle`](Self::Idle) and [`Handshaking`](Self::Handshaking) are both
74    /// [`Phase::Negotiating`](crate::validate::Phase::Negotiating): a session that has not
75    /// opened and one that is mid-handshake have the same answer to "may this message
76    /// cross?", which is *no, the two sides have not agreed which schema to read it
77    /// against*.
78    ///
79    /// A [`Closed`](Self::Closed) session reports
80    /// [`Phase::Connected`](crate::validate::Phase::Connected) and nothing reads
81    /// it: every path that consults the table refuses on [`is_closed`](Self::is_closed)
82    /// first.
83    #[must_use]
84    pub fn phase(&self) -> crate::validate::Phase {
85        use crate::validate::Phase;
86        match self {
87            SessionState::Idle | SessionState::Handshaking => Phase::Negotiating,
88            SessionState::Connected | SessionState::Closed(_) => Phase::Connected,
89            SessionState::ControlTypeSelected(c) => Phase::selected(*c),
90        }
91    }
92
93    /// The control type that is active, if it is one that can be instructed.
94    #[must_use]
95    pub fn active_control_type(&self) -> Option<ControlType> {
96        match self {
97            SessionState::ControlTypeSelected(c) if c.is_controllable() => Some(*c),
98            _ => None,
99        }
100    }
101
102    /// Whether instructions and statuses may flow.
103    #[must_use]
104    pub fn is_active(&self) -> bool {
105        self.active_control_type().is_some()
106    }
107
108    /// Whether the session is over.
109    #[must_use]
110    pub fn is_closed(&self) -> bool {
111        matches!(self, SessionState::Closed(_))
112    }
113}
114
115/// Why a session ended.
116#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
117#[non_exhaustive]
118pub enum CloseReason {
119    /// The application asked for it.
120    #[error("closed locally")]
121    Local,
122    /// The peer sent a `SessionRequest`.
123    #[error("the peer asked to {0:?}")]
124    PeerRequested(crate::types::common::SessionRequestType),
125    /// This side sent a `SessionRequest`.
126    ///
127    /// Distinct from [`PeerRequested`](Self::PeerRequested) because the two are not the
128    /// same event to anybody reading a log: one is a device being told to go away, the
129    /// other is a device deciding to. Both still carry the request type, because
130    /// `RECONNECT` and `TERMINATE` differ in urgency whichever side asked
131    /// (`S2J schemas/SessionRequestType`).
132    #[error("this side asked to {0:?}")]
133    LocallyRequested(crate::types::common::SessionRequestType),
134    /// The transport went away.
135    #[error("the transport closed")]
136    TransportClosed,
137    /// The peer selected a version that was never offered.
138    #[error("the peer selected protocol version {selected}, which was not offered")]
139    UnsupportedVersion {
140        /// What it chose.
141        selected: crate::types::ProtocolVersion,
142    },
143    /// The two sides have no version in common.
144    #[error("no protocol version is supported by both sides")]
145    NoCommonVersion,
146    /// The peer reported an error it cannot recover from.
147    ///
148    /// `S2J schemas/ReceptionStatusValues`: `PERMANENT_ERROR` — "Consequence: Disconnect."
149    #[error("the peer reported a permanent error: {0}")]
150    PermanentError(String),
151    /// The peer did something the protocol does not allow, and the session was
152    /// configured to close on it.
153    #[error("protocol error: {0}")]
154    ProtocolError(String),
155}
156
157/// What to do when a message arrives that is not allowed in the current state.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
159pub enum OutOfOrderPolicy {
160    /// Answer `INVALID_CONTENT`, report it, and carry on.
161    ///
162    /// `S2J schemas/ReceptionStatusValues` gives the consequence of `INVALID_CONTENT` as
163    /// "Message is ignored, proceed if possible" — a peer that is early is not a peer
164    /// that is hostile, and closing on it takes a resource out of a manager's reach for
165    /// a race.
166    #[default]
167    Report,
168    /// Answer, then close the session.
169    Close,
170}
171
172/// Why an outbound message was refused before it reached the wire.
173#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
174#[non_exhaustive]
175pub enum SendError {
176    /// The session is over.
177    #[error("the session is closed")]
178    Closed,
179    /// The message is not allowed in this state — the application learns at the call
180    /// site rather than from the peer's rejection.
181    #[error("{kind} is not allowed while the session is {state}")]
182    NotAllowed {
183        /// What was being sent.
184        kind: MessageKind,
185        /// Where the session is.
186        state: &'static str,
187    },
188    /// The message does not exist in the negotiated wire profile.
189    #[error("{kind} does not exist in S2 JSON {profile}")]
190    NotInProfile {
191        /// What was being sent.
192        kind: MessageKind,
193        /// The profile.
194        profile: WireProfile,
195    },
196    /// The message is invalid, and sending it would only earn an `INVALID_CONTENT`.
197    #[error("{0}")]
198    Invalid(Box<crate::validate::Violation>),
199}
200
201/// What happened to a message that was waiting for an acknowledgement.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum AckOutcome {
204    /// The peer accepted it.
205    Accepted {
206        /// What was sent.
207        handle: MessageHandle,
208        /// How long the answer took.
209        latency: Duration,
210    },
211    /// The peer refused it.
212    Refused {
213        /// What was sent.
214        handle: MessageHandle,
215        /// How it was refused.
216        status: ReceptionStatusValues,
217        /// What the peer said about it.
218        diagnostic: Option<String>,
219        /// What the standard says to do about it.
220        consequence: Consequence,
221        /// How long the answer took.
222        latency: Duration,
223    },
224    /// Nothing came back in time.
225    TimedOut(MessageHandle),
226    /// An acknowledgement arrived for something we never sent, or had given up on.
227    Unmatched {
228        /// What it was about.
229        subject: Id,
230        /// How it was answered.
231        status: ReceptionStatusValues,
232    },
233}
234
235/// One message the ledger is waiting on.
236#[derive(Debug, Clone, Copy)]
237struct Outstanding {
238    handle: MessageHandle,
239    /// When it went out, so the answer can be timed.
240    sent_at: Timestamp,
241    /// When to give up on it.
242    deadline: Timestamp,
243}
244
245/// Tracks what has been sent and not yet acknowledged.
246///
247/// The point of a ledger rather than an `await` is that nothing blocks: a peer that never
248/// answers produces an [`AckOutcome::TimedOut`], not a stalled task. That is the deadlock
249/// `[s2-json #22]` describes, designed out.
250#[derive(Debug, Clone, Default)]
251pub struct AckLedger {
252    pending: Vec<Outstanding>,
253    /// Identifiers already answered, so a duplicate delivery is answered again with the
254    /// same status rather than processed twice.
255    answered: VecDeque<(Id, ReceptionStatusValues)>,
256    max_answered: usize,
257}
258
259impl AckLedger {
260    /// A ledger that remembers the last `max_answered` inbound identifiers.
261    #[must_use]
262    pub fn new(max_answered: usize) -> Self {
263        Self {
264            pending: Vec::new(),
265            answered: VecDeque::new(),
266            max_answered,
267        }
268    }
269
270    /// Record an outbound message that expects an acknowledgement.
271    pub fn sent(&mut self, handle: MessageHandle, sent_at: Timestamp, deadline: Timestamp) {
272        self.pending.push(Outstanding {
273            handle,
274            sent_at,
275            deadline,
276        });
277    }
278
279    /// Match an inbound `ReceptionStatus` to what it answers.
280    // `now` is `Copy` and belongs to the shape of every call that takes a clock.
281    #[allow(clippy::needless_pass_by_value)]
282    pub fn received(&mut self, status: &ReceptionStatus, now: Timestamp) -> AckOutcome {
283        let Some(position) = self
284            .pending
285            .iter()
286            .position(|entry| entry.handle.id == status.subject_message_id)
287        else {
288            return AckOutcome::Unmatched {
289                subject: status.subject_message_id,
290                status: status.status,
291            };
292        };
293        let entry = self.pending.remove(position);
294        let latency = now.saturating_duration_since(entry.sent_at);
295        if status.status == ReceptionStatusValues::Ok {
296            AckOutcome::Accepted {
297                handle: entry.handle,
298                latency,
299            }
300        } else {
301            AckOutcome::Refused {
302                handle: entry.handle,
303                status: status.status,
304                diagnostic: status.diagnostic_label.clone(),
305                consequence: status.status.consequence(),
306                latency,
307            }
308        }
309    }
310
311    /// Everything whose deadline has passed.
312    pub fn expire(&mut self, now: Timestamp) -> Vec<MessageHandle> {
313        let mut out = Vec::new();
314        self.pending.retain(|entry| {
315            if entry.deadline <= now {
316                out.push(entry.handle);
317                false
318            } else {
319                true
320            }
321        });
322        out
323    }
324
325    /// The earliest deadline still outstanding.
326    #[must_use]
327    pub fn next_deadline(&self) -> Option<Timestamp> {
328        self.pending.iter().map(|entry| entry.deadline).min()
329    }
330
331    /// How many messages are waiting.
332    #[must_use]
333    pub fn outstanding(&self) -> usize {
334        self.pending.len()
335    }
336
337    /// Remember how an inbound message was answered.
338    pub fn answered(&mut self, id: Id, status: ReceptionStatusValues) {
339        if self.answered.len() >= self.max_answered {
340            self.answered.pop_front();
341        }
342        self.answered.push_back((id, status));
343    }
344
345    /// How an inbound message was answered before, if it has been seen.
346    #[must_use]
347    pub fn previous_answer(&self, id: Id) -> Option<ReceptionStatusValues> {
348        self.answered
349            .iter()
350            .rev()
351            .find(|(seen, _)| *seen == id)
352            .map(|(_, status)| *status)
353    }
354
355    /// Whether an identifier has been answered before.
356    #[must_use]
357    pub fn has_seen(&self, id: Id) -> bool {
358        self.previous_answer(id).is_some()
359    }
360
361    /// Every identifier answered so far, for the duplicate-identifier rule.
362    pub fn seen_ids(&self) -> Vec<Id> {
363        self.answered.iter().map(|(id, _)| *id).collect()
364    }
365}
366
367/// Everything either side has published on this session.
368///
369/// Every table is bounded: a peer cannot grow memory by sending identifiers it never
370/// resolves ([`Registry::MAX_TRACKED`]).
371#[derive(Debug, Clone, Default)]
372pub struct Registry {
373    /// The resource's details.
374    pub details: Option<ResourceManagerDetails>,
375    /// The FRBC system description in force.
376    pub frbc: Option<frbc::SystemDescription>,
377    /// The OMBC system description in force.
378    pub ombc: Option<ombc::SystemDescription>,
379    /// The DDBC system description in force.
380    pub ddbc: Option<ddbc::SystemDescription>,
381    /// Descriptions whose `valid_from` is still in the future.
382    pub scheduled: Vec<(Timestamp, Message)>,
383    /// Power constraints in force.
384    pub pebc_constraints: Vec<pebc::PowerConstraints>,
385    /// Energy constraints in force.
386    pub pebc_energy: Vec<pebc::EnergyConstraint>,
387    /// Power profiles published.
388    pub ppbc_profiles: Vec<ppbc::PowerProfileDefinition>,
389    /// Instruction identifiers used.
390    pub instructions: Vec<Id>,
391    /// `(message_id, instruction_id)` for every instruction seen on this session.
392    ///
393    /// Kept so that an `InstructionStatusUpdate` naming an identifier nobody instructed
394    /// can say *why*: the commonest cause by far is a peer echoing the instruction's
395    /// `message_id` instead of its `id`, and the two are both `ID`s and both present in
396    /// the message it is answering. The official `s2-example-implementations` battery
397    /// does exactly this, so anybody who talks to it meets the mistake on their first
398    /// instruction.
399    pub instruction_messages: Vec<(Id, Id)>,
400    /// The latest status of each instruction.
401    pub instruction_statuses: Vec<(Id, InstructionStatus)>,
402    /// Objects that could be revoked.
403    pub published: Vec<(RevokableObjects, Id)>,
404    /// The operation mode each actuator is in (`Id::NIL` for OMBC's single machine).
405    pub active_modes: Vec<(Id, Id)>,
406    /// When each actuator's timers finish, keyed by actuator **and** timer: a timer
407    /// identifier is unique only within the description that declares it.
408    pub timers: Vec<TimerState>,
409    /// The present fill level, once a storage status has arrived.
410    pub fill_level: Option<f64>,
411}
412
413impl Registry {
414    /// The most identifiers of any one kind that are remembered.
415    pub const MAX_TRACKED: usize = 4096;
416
417    /// The most descriptions that may be queued for a future `valid_from`.
418    ///
419    /// Far smaller than [`MAX_TRACKED`](Self::MAX_TRACKED) because each entry is a whole
420    /// decoded message rather than an identifier. An eviction drops the description
421    /// furthest from taking effect.
422    pub const MAX_SCHEDULED: usize = 16;
423
424    fn bound<T>(v: &mut Vec<T>) {
425        if v.len() > Self::MAX_TRACKED {
426            v.remove(0);
427        }
428    }
429
430    fn upsert<T, K: PartialEq>(v: &mut Vec<T>, key: &K, value: T, key_of: impl Fn(&T) -> K) {
431        if let Some(slot) = v.iter_mut().find(|existing| key_of(existing) == *key) {
432            *slot = value;
433        } else {
434            v.push(value);
435            Self::bound(v);
436        }
437    }
438
439    /// Record what a message publishes, whichever direction it went.
440    ///
441    /// A description whose `valid_from` is in the future is held until it becomes
442    /// effective; [`Registry::activate_due`] promotes it.
443    // `Option<Timestamp>` is `Copy`; taking it by value reads better at every call site.
444    #[allow(clippy::needless_pass_by_value)]
445    pub fn record(&mut self, message: &Message, now: Option<Timestamp>) {
446        if let Some((object_type, id)) = message.revokable_id() {
447            Self::upsert(
448                &mut self.published,
449                &(object_type, id),
450                (object_type, id),
451                |(t, i)| (*t, *i),
452            );
453        }
454        if let Some(id) = message.instruction_id() {
455            if !self.instructions.contains(&id) {
456                self.instructions.push(id);
457                Self::bound(&mut self.instructions);
458            }
459            if let Some(message_id) = message.id() {
460                Self::upsert(
461                    &mut self.instruction_messages,
462                    &message_id,
463                    (message_id, id),
464                    |(m, _)| *m,
465                );
466            }
467        }
468
469        let scheduled_for = match message {
470            Message::FrbcSystemDescription(d) => Some(d.valid_from),
471            Message::OmbcSystemDescription(d) => Some(d.valid_from),
472            Message::DdbcSystemDescription(d) => Some(d.valid_from),
473            _ => None,
474        };
475        if let (Some(valid_from), Some(now)) = (scheduled_for, now)
476            && valid_from > now
477        {
478            self.schedule(valid_from, message);
479            return;
480        }
481
482        self.apply(message);
483    }
484
485    /// Queue a description that is not in force yet, bounded and without duplicates.
486    fn schedule(&mut self, valid_from: Timestamp, message: &Message) {
487        // A description re-sent with the same identifier replaces the queued one rather
488        // than joining it: the second announcement is a correction, not a second event.
489        let identity = message.revokable_id();
490        if let Some(slot) = self
491            .scheduled
492            .iter_mut()
493            .find(|(_, queued)| queued.revokable_id() == identity)
494        {
495            *slot = (valid_from, message.clone());
496            return;
497        }
498        self.scheduled.push((valid_from, message.clone()));
499        while self.scheduled.len() > Self::MAX_SCHEDULED {
500            // Drop the one furthest from taking effect.
501            if let Some(furthest) = self
502                .scheduled
503                .iter()
504                .enumerate()
505                .max_by_key(|(_, (at, _))| *at)
506                .map(|(i, _)| i)
507            {
508                self.scheduled.remove(furthest);
509            } else {
510                break;
511            }
512        }
513    }
514
515    /// Make a message's contents effective now.
516    fn apply(&mut self, message: &Message) {
517        match message {
518            Message::ResourceManagerDetails(d) => self.details = Some((**d).clone()),
519            // A new system description redefines the scope every operation-mode and
520            // timer identifier lives in (`S2J schemas/Timer.id`), so what was known
521            // about the old one is not knowledge about the new one. Both tables are
522            // cleared, exactly as [`Registry::revoke`] clears them — keeping a
523            // `finished_at` from a description that no longer exists is how one
524            // actuator's retired timer comes to block a transition of its replacement.
525            Message::FrbcSystemDescription(d) => {
526                self.frbc = Some((**d).clone());
527                self.forget_actuator_state();
528            }
529            Message::OmbcSystemDescription(d) => {
530                self.ombc = Some((**d).clone());
531                self.forget_actuator_state();
532            }
533            Message::DdbcSystemDescription(d) => {
534                self.ddbc = Some((**d).clone());
535                self.forget_actuator_state();
536            }
537            Message::PebcPowerConstraints(c) => Self::upsert(
538                &mut self.pebc_constraints,
539                &c.id,
540                (**c).clone(),
541                |existing| existing.id,
542            ),
543            Message::PebcEnergyConstraint(c) => {
544                Self::upsert(&mut self.pebc_energy, &c.id, (**c).clone(), |e| e.id);
545            }
546            Message::PpbcPowerProfileDefinition(p) => {
547                Self::upsert(&mut self.ppbc_profiles, &p.id, (**p).clone(), |e| e.id);
548            }
549            Message::FrbcStorageStatus(s) => self.fill_level = Some(s.present_fill_level),
550            Message::FrbcActuatorStatus(s) => {
551                Self::upsert(
552                    &mut self.active_modes,
553                    &s.actuator_id,
554                    (s.actuator_id, s.active_operation_mode_id),
555                    |(a, _)| *a,
556                );
557            }
558            Message::DdbcActuatorStatus(s) => {
559                Self::upsert(
560                    &mut self.active_modes,
561                    &s.actuator_id,
562                    (s.actuator_id, s.active_operation_mode_id),
563                    |(a, _)| *a,
564                );
565            }
566            Message::OmbcStatus(s) => {
567                Self::upsert(
568                    &mut self.active_modes,
569                    &Id::NIL,
570                    (Id::NIL, s.active_operation_mode_id),
571                    |(a, _)| *a,
572                );
573            }
574            Message::FrbcTimerStatus(s) => {
575                let actuator = s.actuator_id;
576                Self::upsert(
577                    &mut self.timers,
578                    &(actuator, s.timer_id),
579                    TimerState {
580                        actuator,
581                        timer: s.timer_id,
582                        finished_at: s.finished_at,
583                    },
584                    |t| (t.actuator, t.timer),
585                );
586            }
587            Message::DdbcTimerStatus(s) => {
588                let actuator = s.actuator_id;
589                Self::upsert(
590                    &mut self.timers,
591                    &(actuator, s.timer_id),
592                    TimerState {
593                        actuator,
594                        timer: s.timer_id,
595                        finished_at: s.finished_at,
596                    },
597                    |t| (t.actuator, t.timer),
598                );
599            }
600            Message::OmbcTimerStatus(s) => {
601                let actuator = Id::NIL;
602                Self::upsert(
603                    &mut self.timers,
604                    &(actuator, s.timer_id),
605                    TimerState {
606                        actuator,
607                        timer: s.timer_id,
608                        finished_at: s.finished_at,
609                    },
610                    |t| (t.actuator, t.timer),
611                );
612            }
613            Message::InstructionStatusUpdate(u) => Self::upsert(
614                &mut self.instruction_statuses,
615                &u.instruction_id,
616                (u.instruction_id, u.status_type),
617                |(i, _)| *i,
618            ),
619            Message::RevokeObject(r) => self.revoke(r.object_type, r.object_id),
620            _ => {}
621        }
622    }
623
624    /// Forget what was known about the operation modes and timers of a description
625    /// that has just been replaced or withdrawn.
626    fn forget_actuator_state(&mut self) {
627        self.active_modes.clear();
628        self.timers.clear();
629    }
630
631    /// Promote every scheduled description whose time has come.
632    pub fn activate_due(&mut self, now: Timestamp) -> Vec<Message> {
633        let mut due = Vec::new();
634        self.scheduled.retain(|(at, message)| {
635            if *at <= now {
636                due.push(message.clone());
637                false
638            } else {
639                true
640            }
641        });
642        for message in &due {
643            self.apply(message);
644        }
645        due
646    }
647
648    /// The earliest scheduled description still waiting.
649    #[must_use]
650    pub fn next_activation(&self) -> Option<Timestamp> {
651        self.scheduled.iter().map(|(at, _)| *at).min()
652    }
653
654    /// Withdraw an object.
655    ///
656    /// A system description has no `id` of its own, so the standard has its `message_id`
657    /// stand in ([`Message::revokable_id`](crate::message::Message::revokable_id)). That
658    /// makes the identifier load-bearing rather than decorative: a Resource Manager that
659    /// has published description **B** and then revokes the superseded **A** must not
660    /// lose **B**. So the stored description is cleared only when it is the one named.
661    pub fn revoke(&mut self, object_type: RevokableObjects, object_id: Id) {
662        self.published
663            .retain(|(t, i)| !(*t == object_type && *i == object_id));
664        // A description still waiting for its `valid_from` is revokable too, and it is
665        // the one a CEM is most likely to withdraw: it has not taken effect yet.
666        self.scheduled
667            .retain(|(_, message)| message.revokable_id() != Some((object_type, object_id)));
668        match object_type {
669            RevokableObjects::PebcPowerConstraints => {
670                self.pebc_constraints.retain(|c| c.id != object_id);
671            }
672            RevokableObjects::PebcEnergyConstraint => {
673                self.pebc_energy.retain(|c| c.id != object_id);
674            }
675            RevokableObjects::PpbcPowerProfileDefinition => {
676                self.ppbc_profiles.retain(|p| p.id != object_id);
677            }
678            RevokableObjects::FrbcSystemDescription => {
679                if self
680                    .frbc
681                    .as_ref()
682                    .is_some_and(|d| d.message_id == object_id)
683                {
684                    self.frbc = None;
685                    self.forget_actuator_state();
686                }
687            }
688            RevokableObjects::OmbcSystemDescription => {
689                if self
690                    .ombc
691                    .as_ref()
692                    .is_some_and(|d| d.message_id == object_id)
693                {
694                    self.ombc = None;
695                    self.forget_actuator_state();
696                }
697            }
698            RevokableObjects::DdbcSystemDescription => {
699                if self
700                    .ddbc
701                    .as_ref()
702                    .is_some_and(|d| d.message_id == object_id)
703                {
704                    self.ddbc = None;
705                    self.forget_actuator_state();
706                }
707            }
708            _ => {
709                // An instruction: it stays in `instructions` so that a later status
710                // update can still be matched to it, and is marked revoked.
711                Self::upsert(
712                    &mut self.instruction_statuses,
713                    &object_id,
714                    (object_id, InstructionStatus::Revoked),
715                    |(i, _)| *i,
716                );
717            }
718        }
719    }
720
721    /// The validation context this registry supports.
722    ///
723    /// The argument list is long because a `Context` is: every one of these is a fact a
724    /// cross-message rule needs and the registry does not own.
725    #[allow(clippy::too_many_arguments)]
726    pub fn context<'a>(
727        &'a self,
728        profile: WireProfile,
729        sender: EnergyManagementRole,
730        phase: crate::validate::Phase,
731        s2_connect: bool,
732        now: Timestamp,
733        seen: &'a [Id],
734        skew_tolerance: Duration,
735    ) -> Context<'a> {
736        Context {
737            profile,
738            sender: Some(sender),
739            phase,
740            s2_connect,
741            details: self.details.as_ref(),
742            frbc: self.frbc.as_ref(),
743            ombc: self.ombc.as_ref(),
744            ddbc: self.ddbc.as_ref(),
745            pebc_constraints: &self.pebc_constraints,
746            ppbc_profiles: &self.ppbc_profiles,
747            instructions: &self.instructions,
748            instruction_messages: &self.instruction_messages,
749            instruction_statuses: &self.instruction_statuses,
750            seen_message_ids: seen,
751            published: &self.published,
752            active_modes: &self.active_modes,
753            timers: &self.timers,
754            fill_level: self.fill_level,
755            now: Some(now),
756            skew_tolerance,
757        }
758    }
759}
760
761/// What a session has done, for an operator rather than an application.
762///
763/// An application reacts to events; an operator asks a fleet *which gateway is being
764/// refused, and how slow is the slowest peer?* — and the engine that saw it is the only
765/// place the answer exists. Counters rather than a `Metrics` trait: a hook every consumer
766/// must implement to learn a number the session already has is a hook.
767///
768/// Read them with `stats()` and push them wherever the host's metrics go.
769#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
770#[non_exhaustive]
771pub struct Stats {
772    /// Messages put on the wire, `ReceptionStatus` included.
773    pub sent: u64,
774    /// Frames fed in, whether or not they decoded.
775    pub received: u64,
776    /// Frames that did not decode at all.
777    pub undecodable: u64,
778    /// Inbound messages answered with something other than `OK`.
779    pub refused: u64,
780    /// Inbound messages accepted with warnings — the ones worth looking at before they
781    /// become refusals.
782    pub accepted_with_warnings: u64,
783    /// Outbound messages this side sent that its own validator had something to say
784    /// about.
785    ///
786    /// Counted separately from the inbound ones because they mean the opposite thing: an
787    /// inbound warning is a peer to talk to, an outbound one is a bug on this side that
788    /// has not been refused yet.
789    pub sent_with_warnings: u64,
790    /// Duplicate deliveries answered again rather than processed twice.
791    pub duplicates: u64,
792    /// Outbound messages the peer accepted.
793    pub acked: u64,
794    /// Outbound messages the peer refused.
795    pub nacked: u64,
796    /// Outbound messages nothing came back for in time.
797    pub ack_timeouts: u64,
798    /// Acknowledgements for something never sent, or already given up on.
799    pub unmatched_acks: u64,
800    /// The sum of every acknowledgement round trip, in milliseconds.
801    ///
802    /// A sum rather than a mean, because a sum can be added up across sessions;
803    /// [`mean_ack_latency_ms`](Self::mean_ack_latency_ms) divides it.
804    pub ack_latency_total_ms: u64,
805    /// The slowest acknowledgement, in milliseconds — the number a mean hides.
806    pub ack_latency_max_ms: u64,
807}
808
809impl Stats {
810    /// How many outbound messages were answered at all, either way.
811    #[must_use]
812    pub const fn answered(&self) -> u64 {
813        self.acked + self.nacked
814    }
815
816    /// The mean acknowledgement round trip in milliseconds, if anything was answered.
817    #[must_use]
818    pub const fn mean_ack_latency_ms(&self) -> Option<u64> {
819        match self.answered() {
820            0 => None,
821            n => Some(self.ack_latency_total_ms / n),
822        }
823    }
824
825    pub(crate) fn record_latency(&mut self, latency: Duration) {
826        let ms = latency.as_millis();
827        self.ack_latency_total_ms = self.ack_latency_total_ms.saturating_add(ms);
828        self.ack_latency_max_ms = self.ack_latency_max_ms.max(ms);
829    }
830}
831
832/// The state both engines share.
833#[derive(Debug, Clone)]
834pub struct SessionCore {
835    /// Where the session has got to.
836    pub state: SessionState,
837    /// How the version is agreed.
838    pub negotiation: Negotiation,
839    /// The profile in use, once it is known.
840    pub profile: WireProfile,
841    /// Whether this session runs under S2 Connect.
842    pub s2_connect: bool,
843    /// Messages waiting to go out.
844    pub outbox: VecDeque<Outgoing>,
845    /// What is waiting to be acknowledged.
846    pub acks: AckLedger,
847    /// What has been published.
848    pub registry: Registry,
849    /// How long to wait for an acknowledgement.
850    pub ack_timeout: Duration,
851    /// How the engine answers an out-of-order message.
852    pub out_of_order: OutOfOrderPolicy,
853    /// How far a peer's clock may differ before it is worth reporting.
854    pub skew_tolerance: Duration,
855    /// The size cap applied to inbound text.
856    pub max_message_bytes: usize,
857    /// Whether to prune unknown properties instead of refusing the message.
858    pub strictness: codec::Strictness,
859    /// How many reconnection attempts have already failed, for the back-off.
860    ///
861    /// A session object lives for exactly one connection, so this cannot be counted
862    /// *here*: it is what the application carries across reconnections, through
863    /// `RmConfig::after_failed_attempts` / `CemConfig::after_failed_attempts`. Left at
864    /// zero, every `Closed` event would recommend the same two-second ceiling for ever,
865    /// which is a back-off that does not back off.
866    pub reconnect_attempt: u32,
867    /// What this session has done.
868    pub stats: Stats,
869    /// Which role this engine plays, for the identifiers it mints.
870    ///
871    /// Only read when `uuid` is off, where it is the prefix that keeps the two sides'
872    /// counters legible in a transcript.
873    #[cfg_attr(feature = "uuid", allow(dead_code))]
874    role: EnergyManagementRole,
875    /// The counter behind [`SessionCore::next_message_id`] when `uuid` is off.
876    minted: u64,
877}
878
879/// What both engines hand the core when they build it.
880///
881/// A struct rather than eight positional arguments: three of them are a `Duration`, a
882/// `usize` and a `bool`, and `new(role, negotiation, ack_timeout, out_of_order,
883/// skew_tolerance, ...)` is a call in which swapping the two durations compiles and
884/// changes when a session gives up on an acknowledgement.
885pub(crate) struct CoreConfig {
886    pub role: EnergyManagementRole,
887    pub negotiation: Negotiation,
888    pub ack_timeout: Duration,
889    pub out_of_order: OutOfOrderPolicy,
890    pub skew_tolerance: Duration,
891    pub max_message_bytes: usize,
892    pub strictness: codec::Strictness,
893    pub s2_connect: bool,
894    pub reconnect_attempt: u32,
895}
896
897impl SessionCore {
898    pub(crate) fn new(cfg: CoreConfig) -> Self {
899        let CoreConfig {
900            role,
901            negotiation,
902            ack_timeout,
903            out_of_order,
904            skew_tolerance,
905            max_message_bytes,
906            strictness,
907            s2_connect,
908            reconnect_attempt,
909        } = cfg;
910        let profile = match &negotiation {
911            Negotiation::PreNegotiated(p) => *p,
912            Negotiation::Handshake => WireProfile::V1_0_0,
913        };
914        Self {
915            state: SessionState::Idle,
916            negotiation,
917            profile,
918            s2_connect,
919            outbox: VecDeque::new(),
920            acks: AckLedger::new(256),
921            registry: Registry::default(),
922            ack_timeout,
923            out_of_order,
924            skew_tolerance,
925            max_message_bytes,
926            strictness,
927            reconnect_attempt,
928            stats: Stats::default(),
929            role,
930            minted: 0,
931        }
932    }
933
934    /// An identifier for a message the engine is generating itself.
935    ///
936    /// A UUIDv4 with `uuid`, because `s2energy` refuses an `ID` that is not one (E1, R3);
937    /// otherwise a per-session counter prefixed with the role, `rm-1`, which the pattern
938    /// allows. Either way it must be **unique**: a repeated `message_id` collides in the
939    /// acknowledgement ledger and reads as a duplicate to the peer.
940    pub(crate) fn next_message_id(&mut self) -> Id {
941        self.minted = self.minted.wrapping_add(1);
942        #[cfg(feature = "uuid")]
943        {
944            Id::generate()
945        }
946        #[cfg(not(feature = "uuid"))]
947        {
948            use core::fmt::Write as _;
949            let mut buffer = alloc::string::String::new();
950            let prefix = match self.role {
951                EnergyManagementRole::Rm => "rm",
952                EnergyManagementRole::Cem => "cem",
953            };
954            // The pattern allows 64 characters; `cem-` plus a `u64` is at most 24.
955            let _ = write!(buffer, "{prefix}-{}", self.minted);
956            Id::parse(&buffer).unwrap_or(Id::NIL)
957        }
958    }
959
960    pub(crate) fn decode_options(&self) -> DecodeOptions {
961        DecodeOptions {
962            strictness: self.strictness,
963            profile: self.profile,
964            max_bytes: self.max_message_bytes,
965        }
966    }
967
968    /// Queue a message, register it for acknowledgement, and record what it publishes.
969    // The message is consumed conceptually — the caller has handed it over — even though
970    // the encoder and the registry both take it by reference.
971    #[allow(clippy::needless_pass_by_value)]
972    pub(crate) fn transmit(&mut self, message: Message, now: Timestamp) -> Option<MessageHandle> {
973        let kind = message.kind();
974        let id = message.id();
975        self.registry.record(&message, Some(now));
976        self.outbox.push_back(Outgoing {
977            text: codec::encode(&message),
978            kind,
979            message_id: id,
980        });
981        self.stats.sent = self.stats.sent.saturating_add(1);
982        // `ReceptionStatus` is the one message with no `message_id` of its own, and the
983        // one message that is never acknowledged. Both facts are the same fact: nothing
984        // without an identifier can be answered, so nothing without one enters the
985        // ledger.
986        let handle = id.map(|id| MessageHandle { id, kind })?;
987        let deadline = now
988            .checked_add(self.ack_timeout)
989            .unwrap_or(Timestamp::UNIX_EPOCH);
990        self.acks.sent(handle, now, deadline);
991        Some(handle)
992    }
993
994    /// Answer an inbound message, as the standard requires of every message but one.
995    // `now` is `Copy` and belongs to the shape of every `handle_*`/`acknowledge` call.
996    #[allow(clippy::needless_pass_by_value)]
997    pub(crate) fn acknowledge(
998        &mut self,
999        subject: Id,
1000        status: ReceptionStatusValues,
1001        diagnostic: Option<String>,
1002        now: Timestamp,
1003    ) {
1004        let _ = now;
1005        self.acks.answered(subject, status);
1006        if status != ReceptionStatusValues::Ok {
1007            self.stats.refused = self.stats.refused.saturating_add(1);
1008        }
1009        let message = Message::from(ReceptionStatus {
1010            subject_message_id: subject,
1011            status,
1012            diagnostic_label: diagnostic,
1013        });
1014        self.outbox.push_back(Outgoing {
1015            text: codec::encode(&message),
1016            kind: MessageKind::ReceptionStatus,
1017            message_id: None,
1018        });
1019        self.stats.sent = self.stats.sent.saturating_add(1);
1020    }
1021
1022    /// The next instant at which [`handle_timeout`](crate::session::RmSession::handle_timeout)
1023    /// has something to do.
1024    ///
1025    /// `None` once the session is over. A closed session still holds unanswered messages
1026    /// in its ledger and possibly a description scheduled for tomorrow, but neither can
1027    /// ever resolve — the transport is gone — so waking a driver for them would keep an
1028    /// idle device's timer alive for ever.
1029    #[must_use]
1030    pub fn poll_timeout(&self) -> Option<Timestamp> {
1031        if self.state.is_closed() {
1032            return None;
1033        }
1034        match (self.acks.next_deadline(), self.registry.next_activation()) {
1035            (Some(a), Some(b)) => Some(a.min(b)),
1036            (a, b) => a.or(b),
1037        }
1038    }
1039
1040    /// The next message to put on the wire.
1041    pub fn poll_transmit(&mut self) -> Option<Outgoing> {
1042        self.outbox.pop_front()
1043    }
1044}
1045
1046/// The reconnection delay S2 Connect prescribes.
1047///
1048/// `S2C §Reconnection strategy`: `delay_n = random(0, min(max_delay, base_delay × 2^n))`
1049/// with a base of two seconds and a maximum of six hundred.
1050///
1051/// The randomness is a parameter rather than a call into an RNG, so the core stays pure
1052/// and a test can pin it. [`Backoff::delay_with`] is the convenience for a driver.
1053#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1054pub struct Backoff {
1055    /// The first delay's ceiling.
1056    pub base: Duration,
1057    /// The ceiling no delay exceeds.
1058    pub max: Duration,
1059}
1060
1061impl Default for Backoff {
1062    fn default() -> Self {
1063        Self {
1064            base: Duration::from_secs(2),
1065            max: Duration::from_secs(600),
1066        }
1067    }
1068}
1069
1070impl Backoff {
1071    /// The ceiling for attempt `n`, counting from zero.
1072    #[must_use]
1073    pub fn ceiling(self, attempt: u32) -> Duration {
1074        let scaled = self
1075            .base
1076            .as_millis()
1077            .saturating_mul(1u64 << attempt.min(40));
1078        Duration::from_millis(scaled.min(self.max.as_millis()))
1079    }
1080
1081    /// The delay for attempt `n`, given a random number in `[0, 1)`.
1082    #[must_use]
1083    pub fn delay(self, attempt: u32, random: f64) -> Duration {
1084        let ceiling = self.ceiling(attempt).as_millis();
1085        #[allow(
1086            clippy::cast_precision_loss,
1087            clippy::cast_sign_loss,
1088            clippy::cast_possible_truncation
1089        )]
1090        Duration::from_millis((ceiling as f64 * random.clamp(0.0, 1.0)) as u64)
1091    }
1092
1093    /// The delay for attempt `n`, drawing the random number itself.
1094    #[cfg(feature = "std")]
1095    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1096    #[must_use]
1097    pub fn delay_with(self, attempt: u32) -> Duration {
1098        use rand::RngExt as _;
1099        let mut rng = rand::rng();
1100        self.delay(attempt, rng.random_range(0.0..1.0))
1101    }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use super::*;
1107    use crate::types::common::{NumberRange, SessionRequestType};
1108    use alloc::vec;
1109
1110    fn at(s: &str) -> Timestamp {
1111        s.parse().unwrap()
1112    }
1113
1114    fn core_config(role: EnergyManagementRole) -> CoreConfig {
1115        CoreConfig {
1116            role,
1117            negotiation: Negotiation::Handshake,
1118            ack_timeout: Duration::from_secs(5),
1119            out_of_order: OutOfOrderPolicy::Report,
1120            skew_tolerance: Duration::from_secs(30),
1121            max_message_bytes: 1024,
1122            strictness: codec::Strictness::Strict,
1123            s2_connect: false,
1124            reconnect_attempt: 0,
1125        }
1126    }
1127
1128    #[test]
1129    fn every_identifier_the_engine_mints_is_different() {
1130        // The property the acknowledgement ledger rests on, and the one a peer's duplicate
1131        // detection rests on — in every feature configuration, not only with `uuid`.
1132        let mut core = SessionCore::new(core_config(EnergyManagementRole::Rm));
1133        let minted: Vec<Id> = (0..64).map(|_| core.next_message_id()).collect();
1134        let mut unique = minted.clone();
1135        unique.sort_unstable();
1136        unique.dedup();
1137        assert_eq!(unique.len(), minted.len(), "identifiers must not repeat");
1138        assert!(
1139            !minted.contains(&Id::NIL),
1140            "the nil identifier means `no message to name`, not `this message`"
1141        );
1142
1143        // And the two roles are told apart in a transcript, which is what the prefix is
1144        // for when there is no UUID to read.
1145        let mut cem = SessionCore::new(core_config(EnergyManagementRole::Cem));
1146        let theirs = cem.next_message_id();
1147        assert_ne!(theirs, minted[0]);
1148        #[cfg(not(feature = "uuid"))]
1149        {
1150            assert!(minted[0].as_str().starts_with("rm-"));
1151            assert!(theirs.as_str().starts_with("cem-"));
1152        }
1153    }
1154
1155    #[test]
1156    fn the_ledger_matches_answers_to_what_they_answer() {
1157        let mut ledger = AckLedger::new(8);
1158        let handle = MessageHandle {
1159            id: Id::new_const("m1"),
1160            kind: MessageKind::FrbcStorageStatus,
1161        };
1162        ledger.sent(
1163            handle,
1164            at("2024-01-01T12:00:00Z"),
1165            at("2024-01-01T12:00:05Z"),
1166        );
1167        assert_eq!(ledger.outstanding(), 1);
1168
1169        let outcome = ledger.received(
1170            &ReceptionStatus::ok(Id::new_const("m1")),
1171            at("2024-01-01T12:00:00.250Z"),
1172        );
1173        // And the round trip is timed, which is the number an operator compares between
1174        // one gateway and the next.
1175        assert_eq!(
1176            outcome,
1177            AckOutcome::Accepted {
1178                handle,
1179                latency: Duration::from_millis(250)
1180            }
1181        );
1182        assert_eq!(ledger.outstanding(), 0);
1183
1184        // A second answer for the same message matches nothing.
1185        let outcome = ledger.received(
1186            &ReceptionStatus::ok(Id::new_const("m1")),
1187            at("2024-01-01T12:00:01Z"),
1188        );
1189        assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
1190    }
1191
1192    #[test]
1193    fn an_unanswered_message_times_out_rather_than_blocking() {
1194        let mut ledger = AckLedger::new(8);
1195        let handle = MessageHandle {
1196            id: Id::new_const("m1"),
1197            kind: MessageKind::FrbcStorageStatus,
1198        };
1199        ledger.sent(
1200            handle,
1201            at("2024-01-01T12:00:00Z"),
1202            at("2024-01-01T12:00:05Z"),
1203        );
1204        assert_eq!(ledger.next_deadline(), Some(at("2024-01-01T12:00:05Z")));
1205        assert!(ledger.expire(at("2024-01-01T12:00:04Z")).is_empty());
1206        assert_eq!(ledger.expire(at("2024-01-01T12:00:05Z")), vec![handle]);
1207        assert_eq!(ledger.next_deadline(), None);
1208
1209        // A late answer is reported, not treated as an error.
1210        let outcome = ledger.received(
1211            &ReceptionStatus::ok(Id::new_const("m1")),
1212            at("2024-01-01T12:00:01Z"),
1213        );
1214        assert!(matches!(outcome, AckOutcome::Unmatched { .. }));
1215    }
1216
1217    #[test]
1218    fn a_refusal_carries_the_standards_own_consequence() {
1219        let mut ledger = AckLedger::new(8);
1220        let handle = MessageHandle {
1221            id: Id::new_const("m1"),
1222            kind: MessageKind::FrbcInstruction,
1223        };
1224        ledger.sent(
1225            handle,
1226            at("2024-01-01T12:00:00Z"),
1227            at("2024-01-01T12:00:05Z"),
1228        );
1229        let outcome = ledger.received(
1230            &ReceptionStatus::error(
1231                Id::new_const("m1"),
1232                ReceptionStatusValues::TemporaryError,
1233                "busy",
1234            ),
1235            at("2024-01-01T12:00:01Z"),
1236        );
1237        match outcome {
1238            AckOutcome::Refused { consequence, .. } => {
1239                assert_eq!(consequence, Consequence::Retry);
1240            }
1241            other => panic!("{other:?}"),
1242        }
1243    }
1244
1245    #[test]
1246    fn the_answered_ring_is_bounded_and_remembers_the_answer() {
1247        let mut ledger = AckLedger::new(2);
1248        ledger.answered(Id::new_const("m1"), ReceptionStatusValues::Ok);
1249        ledger.answered(Id::new_const("m2"), ReceptionStatusValues::InvalidContent);
1250        assert_eq!(
1251            ledger.previous_answer(Id::new_const("m2")),
1252            Some(ReceptionStatusValues::InvalidContent)
1253        );
1254        ledger.answered(Id::new_const("m3"), ReceptionStatusValues::Ok);
1255        // m1 has fallen out of the ring; a peer cannot grow memory without bound.
1256        assert_eq!(ledger.previous_answer(Id::new_const("m1")), None);
1257        assert!(ledger.has_seen(Id::new_const("m3")));
1258    }
1259
1260    #[test]
1261    fn a_description_valid_in_the_future_waits_its_turn() {
1262        let mut registry = Registry::default();
1263        let later = at("2024-01-01T13:00:00Z");
1264        let now = at("2024-01-01T12:00:00Z");
1265        let description = Message::from(frbc::SystemDescription {
1266            message_id: Id::new_const("m1"),
1267            valid_from: later,
1268            actuators: vec![],
1269            storage: frbc::StorageDescription {
1270                diagnostic_label: None,
1271                fill_level_label: None,
1272                provides_leakage_behaviour: false,
1273                provides_fill_level_target_profile: false,
1274                provides_usage_forecast: false,
1275                fill_level_range: NumberRange::new(0.0, 100.0),
1276            },
1277        });
1278
1279        registry.record(&description, Some(now));
1280        assert!(registry.frbc.is_none(), "not effective yet");
1281        assert_eq!(registry.next_activation(), Some(later));
1282        assert!(registry.activate_due(at("2024-01-01T12:59:59Z")).is_empty());
1283
1284        let due = registry.activate_due(later);
1285        assert_eq!(due.len(), 1);
1286        assert!(registry.frbc.is_some());
1287        assert_eq!(registry.next_activation(), None);
1288    }
1289
1290    #[test]
1291    fn revoking_removes_the_object_and_marks_an_instruction_revoked() {
1292        let mut registry = Registry::default();
1293        let constraints = pebc::PowerConstraints {
1294            message_id: Id::new_const("m1"),
1295            id: Id::new_const("pc1"),
1296            valid_from: at("2024-01-01T12:00:00Z"),
1297            valid_until: None,
1298            consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1299            allowed_limit_ranges: vec![],
1300        };
1301        registry.record(&Message::from(constraints), None);
1302        assert_eq!(registry.pebc_constraints.len(), 1);
1303        assert_eq!(registry.published.len(), 1);
1304
1305        registry.revoke(RevokableObjects::PebcPowerConstraints, Id::new_const("pc1"));
1306        assert!(registry.pebc_constraints.is_empty());
1307        assert!(registry.published.is_empty());
1308
1309        registry.revoke(RevokableObjects::FrbcInstruction, Id::new_const("i1"));
1310        assert_eq!(
1311            registry.instruction_statuses,
1312            vec![(Id::new_const("i1"), InstructionStatus::Revoked)]
1313        );
1314    }
1315
1316    fn frbc_description(message_id: Id, valid_from: Timestamp) -> Message {
1317        Message::from(frbc::SystemDescription {
1318            message_id,
1319            valid_from,
1320            actuators: vec![],
1321            storage: frbc::StorageDescription {
1322                diagnostic_label: None,
1323                fill_level_label: None,
1324                provides_leakage_behaviour: false,
1325                provides_fill_level_target_profile: false,
1326                provides_usage_forecast: false,
1327                fill_level_range: NumberRange::new(0.0, 100.0),
1328            },
1329        })
1330    }
1331
1332    #[test]
1333    fn revoking_a_superseded_description_leaves_the_live_one_alone() {
1334        // A system description has no `id`, so its `message_id` stands in. That makes the
1335        // identifier load-bearing: an RM that published A, then B, and then withdraws the
1336        // stale A must still have B. Ignoring the identifier would blind the session to
1337        // the description it is actually running against.
1338        let mut registry = Registry::default();
1339        let now = at("2024-01-01T12:00:00Z");
1340        registry.record(&frbc_description(Id::new_const("sd-a"), now), Some(now));
1341        registry.record(&frbc_description(Id::new_const("sd-b"), now), Some(now));
1342        assert_eq!(
1343            registry.frbc.as_ref().map(|d| d.message_id),
1344            Some(Id::new_const("sd-b"))
1345        );
1346
1347        registry.revoke(
1348            RevokableObjects::FrbcSystemDescription,
1349            Id::new_const("sd-a"),
1350        );
1351        assert_eq!(
1352            registry.frbc.as_ref().map(|d| d.message_id),
1353            Some(Id::new_const("sd-b")),
1354            "revoking the superseded description must not clear the live one"
1355        );
1356
1357        // Revoking the one in force does clear it.
1358        registry.revoke(
1359            RevokableObjects::FrbcSystemDescription,
1360            Id::new_const("sd-b"),
1361        );
1362        assert!(registry.frbc.is_none());
1363    }
1364
1365    #[test]
1366    fn revoking_a_description_that_has_not_taken_effect_yet_cancels_it() {
1367        let mut registry = Registry::default();
1368        let now = at("2024-01-01T12:00:00Z");
1369        let later = at("2024-01-01T13:00:00Z");
1370        registry.record(&frbc_description(Id::new_const("sd-a"), later), Some(now));
1371        assert_eq!(registry.next_activation(), Some(later));
1372
1373        registry.revoke(
1374            RevokableObjects::FrbcSystemDescription,
1375            Id::new_const("sd-a"),
1376        );
1377        assert_eq!(registry.next_activation(), None);
1378        assert!(registry.activate_due(later).is_empty());
1379        assert!(registry.frbc.is_none(), "a revoked description never runs");
1380    }
1381
1382    #[test]
1383    fn the_queue_of_future_descriptions_is_bounded_by_message_count_not_identifier_count() {
1384        // Each entry is a whole decoded message, so the bound has to be a small number.
1385        // A peer that announces a thousand future shapes of itself must not be able to
1386        // grow this session's memory a thousand messages' worth.
1387        let mut registry = Registry::default();
1388        let now = at("2024-01-01T12:00:00Z");
1389        for minute in 0..100u32 {
1390            let at_time = now
1391                .checked_add(Duration::from_secs(u64::from(minute) * 60 + 60))
1392                .unwrap();
1393            let id_str = alloc::format!("sd-{minute:04}");
1394            registry.record(
1395                &frbc_description(Id::parse(&id_str).unwrap(), at_time),
1396                Some(now),
1397            );
1398        }
1399        assert_eq!(registry.scheduled.len(), Registry::MAX_SCHEDULED);
1400        // The ones kept are the soonest, because those are the ones a CEM has to plan
1401        // around first.
1402        let furthest = registry.scheduled.iter().map(|(at, _)| *at).max().unwrap();
1403        assert_eq!(
1404            furthest,
1405            now.checked_add(Duration::from_secs(Registry::MAX_SCHEDULED as u64 * 60))
1406                .unwrap()
1407        );
1408    }
1409
1410    #[test]
1411    fn re_announcing_a_future_description_corrects_it_rather_than_queueing_twice() {
1412        let mut registry = Registry::default();
1413        let now = at("2024-01-01T12:00:00Z");
1414        let first = at("2024-01-01T13:00:00Z");
1415        let corrected = at("2024-01-01T14:00:00Z");
1416        registry.record(&frbc_description(Id::new_const("sd-a"), first), Some(now));
1417        registry.record(
1418            &frbc_description(Id::new_const("sd-a"), corrected),
1419            Some(now),
1420        );
1421        assert_eq!(registry.scheduled.len(), 1);
1422        assert_eq!(registry.next_activation(), Some(corrected));
1423    }
1424
1425    #[test]
1426    fn two_actuators_may_share_a_timer_identifier() {
1427        // `S2J schemas/Timer.id`: unique "in the scope of the ... FRBC.ActuatorDescription
1428        // in which it is used" — so `timer1` on actuator1 and `timer1` on actuator2 are
1429        // two different timers, and one finishing says nothing about the other.
1430        let mut registry = Registry::default();
1431        let mut status = |actuator: &'static str, finished_at: &str| {
1432            registry.record(
1433                &Message::from(frbc::TimerStatus {
1434                    message_id: Id::new_const("m1"),
1435                    timer_id: Id::new_const("timer1"),
1436                    actuator_id: Id::new_const(actuator),
1437                    finished_at: at(finished_at),
1438                }),
1439                None,
1440            );
1441        };
1442        status("actuator1", "2024-01-01T13:00:00Z");
1443        status("actuator2", "2024-01-01T11:00:00Z");
1444
1445        assert_eq!(registry.timers.len(), 2, "one entry per actuator");
1446        let finished_at = |actuator: &'static str| {
1447            registry
1448                .timers
1449                .iter()
1450                .find(|t| t.actuator == Id::new_const(actuator) && t.timer == "timer1")
1451                .map(|t| t.finished_at)
1452        };
1453        assert_eq!(finished_at("actuator1"), Some(at("2024-01-01T13:00:00Z")));
1454        assert_eq!(finished_at("actuator2"), Some(at("2024-01-01T11:00:00Z")));
1455    }
1456
1457    #[test]
1458    fn resending_a_description_replaces_rather_than_accumulates() {
1459        let mut registry = Registry::default();
1460        for level in [10.0, 20.0] {
1461            registry.record(
1462                &Message::from(frbc::StorageStatus {
1463                    message_id: Id::new_const("m1"),
1464                    present_fill_level: level,
1465                }),
1466                None,
1467            );
1468        }
1469        assert_eq!(registry.fill_level, Some(20.0));
1470
1471        let make = |id: &'static str, until: &str| pebc::PowerConstraints {
1472            message_id: Id::new_const("mm"),
1473            id: Id::new_const(id),
1474            valid_from: at("2024-01-01T12:00:00Z"),
1475            valid_until: Some(at(until)),
1476            consequence_type: pebc::PowerEnvelopeConsequenceType::Vanish,
1477            allowed_limit_ranges: vec![],
1478        };
1479        registry.record(&Message::from(make("pc1", "2024-01-01T13:00:00Z")), None);
1480        registry.record(&Message::from(make("pc1", "2024-01-01T14:00:00Z")), None);
1481        assert_eq!(registry.pebc_constraints.len(), 1);
1482        assert_eq!(
1483            registry.pebc_constraints[0].valid_until,
1484            Some(at("2024-01-01T14:00:00Z"))
1485        );
1486    }
1487
1488    #[test]
1489    fn the_backoff_is_the_one_s2_connect_prescribes() {
1490        let b = Backoff::default();
1491        // Ceilings double from two seconds and stop at ten minutes.
1492        assert_eq!(b.ceiling(0), Duration::from_secs(2));
1493        assert_eq!(b.ceiling(1), Duration::from_secs(4));
1494        assert_eq!(b.ceiling(2), Duration::from_secs(8));
1495        assert_eq!(b.ceiling(20), Duration::from_secs(600));
1496        assert_eq!(b.ceiling(100), Duration::from_secs(600));
1497        // And the delay is uniform below the ceiling.
1498        assert_eq!(b.delay(3, 0.0), Duration::ZERO);
1499        assert_eq!(b.delay(3, 1.0), Duration::from_secs(16));
1500        assert_eq!(b.delay(3, 0.5), Duration::from_secs(8));
1501    }
1502
1503    #[test]
1504    fn session_state_reports_what_may_flow() {
1505        assert!(!SessionState::Connected.is_active());
1506        assert_eq!(SessionState::Connected.active_control_type(), None);
1507        let active = SessionState::ControlTypeSelected(ControlType::FillRateBasedControl);
1508        assert!(active.is_active());
1509        // NOT_CONTROLABLE is a selection, but nothing can be instructed after it.
1510        let inert = SessionState::ControlTypeSelected(ControlType::NotControllable);
1511        assert!(!inert.is_active());
1512        assert!(SessionState::Closed(CloseReason::Local).is_closed());
1513        let _ = SessionRequestType::Terminate;
1514    }
1515}