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