Skip to main content

s2_kit/session/
cem.rs

1//! The Customer Energy Manager's side of one S2 session.
2
3use alloc::boxed::Box;
4use alloc::collections::VecDeque;
5use alloc::string::{String, ToString};
6use alloc::vec::Vec;
7
8use super::core::{
9    AckOutcome, Backoff, CloseReason, CoreConfig, MessageHandle, Negotiation, OutOfOrderPolicy,
10    Outgoing, SendError, SessionCore, SessionState,
11};
12use super::rm::state_name;
13use super::{Inbound, InboundPolicy};
14use crate::codec::{self, Strictness};
15use crate::message::{Message, MessageKind};
16use crate::types::common::{
17    Consequence, ControlType, EnergyManagementRole, Handshake, HandshakeResponse,
18    InstructionStatusUpdate, PowerForecast, PowerMeasurement, ReceptionStatusValues,
19    ResourceManagerDetails, RevokableObjects, RevokeObject, SelectControlType, SessionRequest,
20    SessionRequestType,
21};
22use crate::types::{Duration, Id, ProtocolVersion, Timestamp, WireProfile};
23use crate::validate::{Report, Validate, rules};
24
25/// How a [`CemSession`] behaves.
26#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub struct CemConfig {
29    /// How the protocol version is agreed.
30    pub negotiation: Negotiation,
31    /// The versions this manager can speak, most preferred first.
32    pub supported_versions: Vec<ProtocolVersion>,
33    /// How long to wait for an acknowledgement.
34    pub ack_timeout: Duration,
35    /// What to do about a message that is not allowed in the current state.
36    pub out_of_order: OutOfOrderPolicy,
37    /// How far a peer's clock may differ before it is worth reporting.
38    pub skew_tolerance: Duration,
39    /// The largest inbound message that will be parsed.
40    pub max_message_bytes: usize,
41    /// Whether to prune unknown properties rather than refuse the message.
42    pub strictness: Strictness,
43    /// Whether the session runs under S2 Connect.
44    pub s2_connect: bool,
45    /// Whether to validate outbound messages and refuse to send an invalid one.
46    pub validate_outbound: bool,
47    /// Whether to refuse an instruction whose transition is blocked by a timer.
48    ///
49    /// Off by default: the S2 documentation, *Operation modes* says a Resource Manager may
50    /// change mode without the CEM asking and even without a described transition, so
51    /// the manager's picture of the timers is always slightly stale. Refusing to send on
52    /// a stale picture is worse than sending and being told no.
53    pub enforce_transitions: bool,
54    /// How many reconnection attempts have already failed.
55    ///
56    /// A session is one connection, so it cannot count these itself. Carry the number
57    /// across: the `reconnect_after` on a `Closed` event is
58    /// [`Backoff::ceiling`](crate::session::Backoff::ceiling) for *this* attempt, and a
59    /// session that always starts at zero always recommends two seconds — a back-off that
60    /// does not back off.
61    pub reconnect_attempt: u32,
62}
63
64impl Default for CemConfig {
65    fn default() -> Self {
66        Self {
67            negotiation: Negotiation::Handshake,
68            supported_versions: alloc::vec![ProtocolVersion::V1_0_0, ProtocolVersion::V0_0_2_BETA,],
69            ack_timeout: Duration::from_secs(5),
70            out_of_order: OutOfOrderPolicy::Report,
71            skew_tolerance: Duration::from_secs(30),
72            max_message_bytes: codec::DecodeOptions::DEFAULT_MAX_BYTES,
73            strictness: Strictness::Strict,
74            s2_connect: false,
75            validate_outbound: true,
76            enforce_transitions: false,
77            reconnect_attempt: 0,
78        }
79    }
80}
81
82impl CemConfig {
83    /// Stop checking outbound messages before they go.
84    ///
85    /// On by default, because learning at the call site beats earning an
86    /// `INVALID_CONTENT` from a peer. Turn it off for a bridge that must forward exactly
87    /// what it was handed, or for a test that needs a peer's refusal rather than its own.
88    #[must_use]
89    pub fn without_outbound_validation(mut self) -> Self {
90        self.validate_outbound = false;
91        self
92    }
93
94    /// Use a version that was already agreed, as S2 Connect does.
95    #[must_use]
96    pub fn pre_negotiated(mut self, profile: WireProfile) -> Self {
97        self.negotiation = Negotiation::PreNegotiated(profile);
98        self.s2_connect = true;
99        self
100    }
101
102    /// Support exactly these versions.
103    #[must_use]
104    pub fn supporting(mut self, versions: impl IntoIterator<Item = ProtocolVersion>) -> Self {
105        self.supported_versions = versions.into_iter().collect();
106        self
107    }
108
109    /// Start this session knowing that `attempts` reconnections have already failed.
110    ///
111    /// What makes the `reconnect_after` on a `Closed` event grow. The application owns
112    /// the reconnection loop (D36), so it also owns the counter: reset it to zero after a
113    /// session that reached `Connected`, and increment it after one that did not.
114    #[must_use]
115    pub const fn after_failed_attempts(mut self, attempts: u32) -> Self {
116        self.reconnect_attempt = attempts;
117        self
118    }
119}
120
121/// Something a Customer Energy Manager's application needs to know about.
122#[derive(Debug, Clone, PartialEq)]
123#[non_exhaustive]
124pub enum CemEvent {
125    /// A protocol version was agreed.
126    Negotiated {
127        /// The version string that was chosen.
128        version: ProtocolVersion,
129        /// The wire shape it selects.
130        profile: WireProfile,
131    },
132    /// The resource described itself. Now a control type can be selected.
133    ResourceDescribed(Box<ResourceManagerDetails>),
134    /// The control type this manager selected is active.
135    Ready {
136        /// What is active.
137        control_type: ControlType,
138    },
139    /// The control type was deactivated.
140    Deselected,
141    /// The resource published a description or a constraint.
142    Description {
143        /// Which message.
144        kind: MessageKind,
145        /// The message.
146        message: Message,
147    },
148    /// The resource reported a status.
149    Status {
150        /// Which message.
151        kind: MessageKind,
152        /// The message.
153        message: Message,
154    },
155    /// A measurement arrived.
156    Measurement(Box<PowerMeasurement>),
157    /// A forecast arrived.
158    Forecast(Box<PowerForecast>),
159    /// What became of an instruction this manager sent.
160    ///
161    /// The whole update, not just the status: `timestamp` is "when status_type has
162    /// changed the last time", which is **not** when the message arrived, and a manager
163    /// reconciling a late `SUCCEEDED` against its own dispatch log needs the difference.
164    InstructionStatus(InstructionStatusUpdate),
165    /// The resource reported on a timer.
166    ///
167    /// Reported, not *finished*: `S2J messages/*.TimerStatus.finished_at` says that "if
168    /// the timer was never started, the value can be an arbitrary DateTimeStamp in the
169    /// past", so a past instant means the timer ran out **or** never ran, and a manager
170    /// choosing a transition cares which. The supported reading is narrower — a
171    /// `finished_at` in the future blocks, everything else does not — and is the one
172    /// [`model::blocking_timers`](crate::model::blocking_timers) uses.
173    TimerReported {
174        /// The actuator it belongs to, where the control type has actuators.
175        actuator: Option<Id>,
176        /// Which timer.
177        timer: Id,
178        /// When it finishes. In the past means it is not blocking — which is not quite
179        /// the same as saying it ever ran.
180        finished_at: Timestamp,
181    },
182    /// A description that was published for the future is now in force.
183    DescriptionActivated {
184        /// Which message became effective.
185        kind: MessageKind,
186    },
187    /// The resource withdrew an object.
188    Revoked {
189        /// What kind.
190        object_type: RevokableObjects,
191        /// Which one.
192        object_id: Id,
193    },
194    /// Something we sent was accepted.
195    Acked(MessageHandle),
196    /// Something we sent was refused.
197    Nacked {
198        /// What was refused.
199        handle: MessageHandle,
200        /// How.
201        status: ReceptionStatusValues,
202        /// What the peer said.
203        diagnostic: Option<String>,
204        /// What the standard says to do about it.
205        consequence: Consequence,
206    },
207    /// Nothing came back in time.
208    AckTimedOut(MessageHandle),
209    /// An acknowledgement arrived for something we never sent.
210    UnmatchedAck {
211        /// What it was about.
212        subject: Id,
213        /// How it was answered.
214        status: ReceptionStatusValues,
215    },
216    /// The resource asked to end or restart the session.
217    SessionRequested {
218        /// Reconnect or terminate.
219        request: SessionRequestType,
220        /// What it said about it.
221        diagnostic: Option<String>,
222    },
223    /// An inbound message was refused.
224    Refused {
225        /// What it claimed to be.
226        kind: Option<MessageKind>,
227        /// How it was refused.
228        status: ReceptionStatusValues,
229        /// Everything wrong with it.
230        report: Report,
231    },
232    /// An inbound message was accepted but is suspect.
233    Warnings {
234        /// What it was.
235        kind: MessageKind,
236        /// What is suspect about it.
237        report: Report,
238    },
239    /// A message **this side** sent had warnings of its own.
240    ///
241    /// `validate_outbound` refuses an outbound message with an *error* at the call site;
242    /// this is what it has to say about the rest. A resource publishing a description
243    /// `s2-python` will refuse (`S2-ACT-001`), or a manager instructing a transition its
244    /// own picture of the timers says is blocked (`S2-INST-005`), learns it here rather
245    /// than from a peer. Separate from [`Warnings`](Self::Warnings) because the two mean
246    /// opposite things: one is a peer worth watching, the other is this side.
247    OutboundWarnings {
248        /// What was sent.
249        kind: MessageKind,
250        /// What this side's own validator said about it.
251        report: Report,
252    },
253    /// The session ended.
254    Closed {
255        /// Why.
256        reason: CloseReason,
257        /// How long to wait before reconnecting, if reconnecting makes sense.
258        ///
259        /// Already jittered as `S2C §Reconnection strategy` prescribes when built with
260        /// `std`; the un-jittered ceiling without it — draw with
261        /// [`Backoff::delay`](super::Backoff::delay) there.
262        reconnect_after: Option<Duration>,
263    },
264}
265
266/// A Customer Energy Manager's side of one S2 session.
267///
268/// The mirror of [`RmSession`](super::RmSession), over the same core: the same state
269/// table, the same acknowledgement ledger, the same registry. Wiring one of each
270/// together through [`crate::testing::Conversation`] is how the documented conversations are
271/// tested.
272pub struct CemSession {
273    core: SessionCore,
274    config: CemConfig,
275    events: VecDeque<CemEvent>,
276    peer_versions: Vec<ProtocolVersion>,
277    negotiated: Option<ProtocolVersion>,
278    handshake_sent: bool,
279    pending_control_type: Option<(Id, ControlType)>,
280    policy: Option<Box<dyn InboundPolicy + Send>>,
281    backoff: Backoff,
282}
283
284impl core::fmt::Debug for CemSession {
285    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
286        f.debug_struct("CemSession")
287            .field("state", &self.core.state)
288            .field("profile", &self.core.profile)
289            .field("outstanding_acks", &self.core.acks.outstanding())
290            .field("queued", &self.core.outbox.len())
291            .finish_non_exhaustive()
292    }
293}
294
295impl CemSession {
296    /// A manager's side of a session, not yet opened.
297    #[must_use]
298    pub fn new(config: CemConfig) -> Self {
299        let core = SessionCore::new(CoreConfig {
300            role: EnergyManagementRole::Cem,
301            negotiation: config.negotiation.clone(),
302            ack_timeout: config.ack_timeout,
303            out_of_order: config.out_of_order,
304            skew_tolerance: config.skew_tolerance,
305            max_message_bytes: config.max_message_bytes,
306            strictness: config.strictness,
307            s2_connect: config.s2_connect,
308            reconnect_attempt: config.reconnect_attempt,
309        });
310        Self {
311            core,
312            config,
313            events: VecDeque::new(),
314            peer_versions: Vec::new(),
315            negotiated: None,
316            handshake_sent: false,
317            pending_control_type: None,
318            policy: None,
319            backoff: Backoff::default(),
320        }
321    }
322
323    /// Install a hook consulted before every inbound message is acknowledged.
324    pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
325        self.policy = Some(policy);
326    }
327
328    /// Where the session has got to.
329    #[must_use]
330    pub fn state(&self) -> &SessionState {
331        &self.core.state
332    }
333
334    /// The wire profile in use.
335    #[must_use]
336    pub fn profile(&self) -> WireProfile {
337        self.core.profile
338    }
339
340    /// The version string the handshake settled on, exactly as it crossed the wire —
341    /// or the pre-negotiated one under S2 Connect. `None` until then.
342    ///
343    /// [`profile`](Self::profile) is what the codec reads with; this is what an operator
344    /// greps for, and the evidence R2's trigger is evaluated on: which string a peer
345    /// actually *selects*.
346    #[must_use]
347    pub fn negotiated_version(&self) -> Option<&ProtocolVersion> {
348        self.negotiated.as_ref()
349    }
350
351    /// What this session has done, for an operator's metrics rather than for the
352    /// application: how many messages crossed, how many were refused, and how long the
353    /// peer takes to answer.
354    #[must_use]
355    pub fn stats(&self) -> super::core::Stats {
356        self.core.stats
357    }
358
359    /// Everything this session has learned about the resource.
360    #[must_use]
361    pub fn registry(&self) -> &super::core::Registry {
362        &self.core.registry
363    }
364
365    /// The resource's details, once it has sent them.
366    #[must_use]
367    pub fn details(&self) -> Option<&ResourceManagerDetails> {
368        self.core.registry.details.as_ref()
369    }
370
371    /// Begin.
372    ///
373    /// With a handshake, this queues one — the Resource Manager also sends one, and
374    /// neither order is wrong. With a version already agreed, it does nothing but wait
375    /// for the resource's details.
376    pub fn open(&mut self, now: Timestamp) {
377        if !matches!(self.core.state, SessionState::Idle) {
378            return;
379        }
380        match &self.config.negotiation {
381            Negotiation::Handshake => {
382                self.core.state = SessionState::Handshaking;
383                self.handshake_sent = true;
384                let handshake = Handshake {
385                    message_id: self.core.next_message_id(),
386                    role: EnergyManagementRole::Cem,
387                    supported_protocol_versions: Some(self.config.supported_versions.clone()),
388                };
389                self.core.transmit(Message::from(handshake), now);
390            }
391            Negotiation::PreNegotiated(profile) => {
392                let profile = *profile;
393                self.core.profile = profile;
394                self.negotiated = Some(profile.version());
395                self.core.state = SessionState::Connected;
396                self.events.push_back(CemEvent::Negotiated {
397                    version: profile.version(),
398                    profile,
399                });
400            }
401        }
402    }
403
404    /// The next message to put on the wire.
405    pub fn poll_transmit(&mut self) -> Option<Outgoing> {
406        self.core.poll_transmit()
407    }
408
409    /// The next thing the application needs to know.
410    pub fn poll_event(&mut self) -> Option<CemEvent> {
411        self.events.pop_front()
412    }
413
414    /// When [`handle_timeout`](Self::handle_timeout) next has something to do.
415    #[must_use]
416    pub fn poll_timeout(&self) -> Option<Timestamp> {
417        self.core.poll_timeout()
418    }
419
420    /// Feed in one text frame. Never fails.
421    ///
422    /// A frame that arrives after the session is over is ignored rather than answered:
423    /// the transport is gone, so an acknowledgement queued for it is one nobody will
424    /// ever read — and a closed session that keeps filling its outbox is a closed
425    /// session that keeps growing. [`handle_message`](Self::handle_message) makes the
426    /// same check; this one is for the frames that never get that far.
427    pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
428        if self.core.state.is_closed() {
429            let peek = crate::codec::peek(text).ok();
430            return Inbound {
431                kind: peek.as_ref().and_then(|p| p.kind),
432                message_id: peek.and_then(|p| p.message_id),
433                status: ReceptionStatusValues::Ok,
434                report: Report::new(),
435            };
436        }
437        self.core.stats.received = self.core.stats.received.saturating_add(1);
438        let options = self.core.decode_options();
439        match codec::decode_with(text, &options) {
440            Ok(decoded) => {
441                if !decoded.pruned.is_empty() {
442                    let mut report = Report::new();
443                    for path in &decoded.pruned {
444                        report.push(
445                            rules::UNKNOWN_PROPERTY,
446                            path,
447                            "property is not defined by the schema and was removed",
448                        );
449                    }
450                    self.events.push_back(CemEvent::Warnings {
451                        kind: decoded.message.kind(),
452                        report,
453                    });
454                }
455                self.handle_message(decoded.message, now)
456            }
457            Err(error) => {
458                self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
459                let kind = error.peek().and_then(|p| p.kind);
460                let status = error.reception_status();
461                if kind != Some(MessageKind::ReceptionStatus) {
462                    self.core.acknowledge(
463                        status.subject_message_id,
464                        status.status,
465                        status.diagnostic_label.clone(),
466                        now,
467                    );
468                }
469                let mut report = Report::new();
470                report.push(rules::DECODE_FAILED, "", error.to_string());
471                self.events.push_back(CemEvent::Refused {
472                    kind,
473                    status: status.status,
474                    report: report.clone(),
475                });
476                Inbound {
477                    kind,
478                    message_id: error.peek().and_then(|p| p.message_id),
479                    status: status.status,
480                    report,
481                }
482            }
483        }
484    }
485
486    /// Feed in one already-decoded message.
487    pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
488        if self.core.state.is_closed() {
489            return Inbound::ignored(message.kind(), message.id());
490        }
491
492        if let Message::ReceptionStatus(status) = &message {
493            self.on_reception_status(status, now);
494            return Inbound {
495                kind: Some(MessageKind::ReceptionStatus),
496                message_id: None,
497                status: ReceptionStatusValues::Ok,
498                report: Report::new(),
499            };
500        }
501
502        let kind = message.kind();
503        let Some(id) = message.id() else {
504            return Inbound::ignored(kind, None);
505        };
506
507        if let Some(previous) = self.core.acks.previous_answer(id) {
508            // Answered again with the same status, and deliberately not processed twice:
509            // that is what makes the engine idempotent under a proxy that retries. It is
510            // reported, because a peer that reuses identifiers is a bug worth seeing.
511            self.core.acknowledge(id, previous, None, now);
512            self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
513            let mut report = Report::new();
514            report.push_related(
515                rules::DUPLICATE_MESSAGE_ID,
516                "/message_id",
517                alloc::format!("{id} was already answered {previous:?}; not processed again"),
518                [id],
519            );
520            self.events.push_back(CemEvent::Warnings {
521                kind,
522                report: report.clone(),
523            });
524            return Inbound {
525                kind: Some(kind),
526                message_id: Some(id),
527                status: previous,
528                report,
529            };
530        }
531
532        let seen = self.core.acks.seen_ids();
533        let report = {
534            let ctx = self.core.registry.context(
535                self.core.profile,
536                EnergyManagementRole::Rm,
537                self.core.state.phase(),
538                self.core.s2_connect,
539                now,
540                &seen,
541                self.core.skew_tolerance,
542            );
543            message.validate(&ctx)
544        };
545
546        if report.has_errors() {
547            let status = ReceptionStatusValues::InvalidContent;
548            self.core
549                .acknowledge(id, status, report.diagnostic_label(), now);
550            let closing = self.config.out_of_order == OutOfOrderPolicy::Close
551                && (report.contains(rules::NOT_ALLOWED_IN_STATE)
552                    || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
553            self.events.push_back(CemEvent::Refused {
554                kind: Some(kind),
555                status,
556                report: report.clone(),
557            });
558            if closing {
559                let reason = CloseReason::ProtocolError(
560                    report
561                        .diagnostic_label()
562                        .unwrap_or_else(|| "out of order".to_string()),
563                );
564                self.close_with(reason);
565            }
566            return Inbound {
567                kind: Some(kind),
568                message_id: Some(id),
569                status,
570                report,
571            };
572        }
573
574        let policy = self
575            .policy
576            .as_mut()
577            .and_then(|policy| policy.review(&message));
578        if let Some((status, diagnostic)) = policy {
579            self.core
580                .acknowledge(id, status, Some(diagnostic.clone()), now);
581            let mut refusal = report.clone();
582            refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
583            self.events.push_back(CemEvent::Refused {
584                kind: Some(kind),
585                status,
586                report: refusal,
587            });
588            return Inbound {
589                kind: Some(kind),
590                message_id: Some(id),
591                status,
592                report,
593            };
594        }
595
596        self.core
597            .acknowledge(id, ReceptionStatusValues::Ok, None, now);
598        if !report.is_empty() {
599            self.core.stats.accepted_with_warnings =
600                self.core.stats.accepted_with_warnings.saturating_add(1);
601            self.events.push_back(CemEvent::Warnings {
602                kind,
603                report: report.clone(),
604            });
605        }
606        self.process(message, now);
607        Inbound {
608            kind: Some(kind),
609            message_id: Some(id),
610            status: ReceptionStatusValues::Ok,
611            report,
612        }
613    }
614
615    fn process(&mut self, message: Message, now: Timestamp) {
616        // Under S2 Connect the version was settled by session initiation, and
617        // `S2C §Communication - JSON messages` says these "can not be sent". One that
618        // arrives anyway is acknowledged — `S2-STATE-003` reports it — and otherwise
619        // ignored: it must not renegotiate what `initiateSession` already decided.
620        if self.core.s2_connect
621            && matches!(
622                message,
623                Message::Handshake(_) | Message::HandshakeResponse(_)
624            )
625        {
626            return;
627        }
628        match &message {
629            Message::Handshake(h) => {
630                if let Some(versions) = &h.supported_protocol_versions {
631                    self.peer_versions.clone_from(versions);
632                }
633                // The manager is the side that chooses: `S2J messages/Handshake` makes
634                // the version list mandatory for the RM and optional for the CEM,
635                // because the RM is the constrained side and the manager adapts.
636                // Canonical comparison, not `==`: an RM that speaks S2 Connect as well
637                // offers `v1.0.0` where this list holds `1.0.0`, and the two are the
638                // same version (E25, D31). What goes back out is *our* spelling, so the
639                // answer is always a string this side already offered.
640                let Some(chosen) = self
641                    .config
642                    .supported_versions
643                    .iter()
644                    .find(|ours| self.peer_versions.iter().any(|theirs| ours.matches(theirs)))
645                    .cloned()
646                else {
647                    self.close_with(CloseReason::NoCommonVersion);
648                    return;
649                };
650                let Some(profile) = chosen.wire_profile() else {
651                    self.close_with(CloseReason::NoCommonVersion);
652                    return;
653                };
654                self.core.profile = profile;
655                self.negotiated = Some(chosen.clone());
656                self.core.state = SessionState::Connected;
657                let message_id = self.core.next_message_id();
658                self.core.transmit(
659                    Message::from(HandshakeResponse {
660                        message_id,
661                        selected_protocol_version: chosen.clone(),
662                    }),
663                    now,
664                );
665                self.events.push_back(CemEvent::Negotiated {
666                    version: chosen,
667                    profile,
668                });
669                return;
670            }
671            Message::SessionRequest(request) => {
672                self.events.push_back(CemEvent::SessionRequested {
673                    request: request.request,
674                    diagnostic: request.diagnostic_label.clone(),
675                });
676                self.close_with(CloseReason::PeerRequested(request.request));
677                return;
678            }
679            Message::RevokeObject(revoke) => {
680                self.core
681                    .registry
682                    .revoke(revoke.object_type, revoke.object_id);
683                self.events.push_back(CemEvent::Revoked {
684                    object_type: revoke.object_type,
685                    object_id: revoke.object_id,
686                });
687                return;
688            }
689            _ => {}
690        }
691
692        self.core.registry.record(&message, Some(now));
693
694        let kind = message.kind();
695        match message {
696            Message::ResourceManagerDetails(details) => {
697                self.events.push_back(CemEvent::ResourceDescribed(details));
698            }
699            Message::PowerMeasurement(m) => {
700                self.events.push_back(CemEvent::Measurement(Box::new(m)));
701            }
702            Message::PowerForecast(f) => self.events.push_back(CemEvent::Forecast(f)),
703            Message::InstructionStatusUpdate(u) => {
704                self.events.push_back(CemEvent::InstructionStatus(u));
705            }
706            Message::FrbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
707                actuator: Some(s.actuator_id),
708                timer: s.timer_id,
709                finished_at: s.finished_at,
710            }),
711            Message::DdbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
712                actuator: Some(s.actuator_id),
713                timer: s.timer_id,
714                finished_at: s.finished_at,
715            }),
716            Message::OmbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
717                actuator: None,
718                timer: s.timer_id,
719                finished_at: s.finished_at,
720            }),
721            other => {
722                let is_description = matches!(
723                    kind,
724                    MessageKind::FrbcSystemDescription
725                        | MessageKind::OmbcSystemDescription
726                        | MessageKind::DdbcSystemDescription
727                        | MessageKind::PebcPowerConstraints
728                        | MessageKind::PebcEnergyConstraint
729                        | MessageKind::PpbcPowerProfileDefinition
730                        | MessageKind::FrbcLeakageBehaviour
731                        | MessageKind::FrbcUsageForecast
732                        | MessageKind::FrbcFillLevelTargetProfile
733                        | MessageKind::DdbcAverageDemandRateForecast
734                );
735                if is_description {
736                    self.events.push_back(CemEvent::Description {
737                        kind,
738                        message: other,
739                    });
740                } else {
741                    self.events.push_back(CemEvent::Status {
742                        kind,
743                        message: other,
744                    });
745                }
746            }
747        }
748    }
749
750    fn on_reception_status(
751        &mut self,
752        status: &crate::types::common::ReceptionStatus,
753        now: Timestamp,
754    ) {
755        match self.core.acks.received(status, now) {
756            AckOutcome::Accepted { handle, latency } => {
757                self.core.stats.acked = self.core.stats.acked.saturating_add(1);
758                self.core.stats.record_latency(latency);
759                // A control type becomes active when the resource says it accepted the
760                // selection, not when the manager decided to ask.
761                if let Some((id, control_type)) = self.pending_control_type
762                    && id == handle.id
763                {
764                    self.pending_control_type = None;
765                    if control_type == ControlType::NoSelection {
766                        self.core.state = SessionState::Connected;
767                        self.events.push_back(CemEvent::Deselected);
768                    } else {
769                        self.core.state = SessionState::ControlTypeSelected(control_type);
770                        self.events.push_back(CemEvent::Ready { control_type });
771                    }
772                }
773                self.events.push_back(CemEvent::Acked(handle));
774            }
775            AckOutcome::Refused {
776                handle,
777                status,
778                diagnostic,
779                consequence,
780                latency,
781            } => {
782                self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
783                self.core.stats.record_latency(latency);
784                if self
785                    .pending_control_type
786                    .is_some_and(|(id, _)| id == handle.id)
787                {
788                    self.pending_control_type = None;
789                }
790                self.events.push_back(CemEvent::Nacked {
791                    handle,
792                    status,
793                    diagnostic: diagnostic.clone(),
794                    consequence,
795                });
796                if consequence == Consequence::Disconnect {
797                    self.close_with(CloseReason::PermanentError(
798                        diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
799                    ));
800                }
801            }
802            AckOutcome::TimedOut(handle) => {
803                self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
804                self.events.push_back(CemEvent::AckTimedOut(handle));
805            }
806            AckOutcome::Unmatched { subject, status } => {
807                self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
808                self.events
809                    .push_back(CemEvent::UnmatchedAck { subject, status });
810            }
811        }
812    }
813
814    /// Let time pass.
815    pub fn handle_timeout(&mut self, now: Timestamp) {
816        for handle in self.core.acks.expire(now) {
817            if self
818                .pending_control_type
819                .is_some_and(|(id, _)| id == handle.id)
820            {
821                self.pending_control_type = None;
822            }
823            self.events.push_back(CemEvent::AckTimedOut(handle));
824        }
825        for message in self.core.registry.activate_due(now) {
826            self.events.push_back(CemEvent::DescriptionActivated {
827                kind: message.kind(),
828            });
829        }
830    }
831
832    /// The transport went away.
833    pub fn transport_closed(&mut self, now: Timestamp) {
834        let _ = now;
835        self.close_with(CloseReason::TransportClosed);
836    }
837
838    /// Activate a control type.
839    ///
840    /// The session does not become active until the resource acknowledges it, which is
841    /// when [`CemEvent::Ready`] arrives.
842    pub fn select_control_type(
843        &mut self,
844        control_type: ControlType,
845        now: Timestamp,
846    ) -> Result<MessageHandle, SendError> {
847        let message_id = self.core.next_message_id();
848        let handle = self.send(
849            SelectControlType {
850                message_id,
851                control_type,
852            },
853            now,
854        )?;
855        self.pending_control_type = Some((handle.id, control_type));
856        Ok(handle)
857    }
858
859    /// Send an instruction.
860    pub fn instruct(
861        &mut self,
862        instruction: impl Into<Message>,
863        now: Timestamp,
864    ) -> Result<MessageHandle, SendError> {
865        let message = instruction.into();
866        if self.config.enforce_transitions {
867            let seen = self.core.acks.seen_ids();
868            let explanation = {
869                let ctx = self.core.registry.context(
870                    self.core.profile,
871                    EnergyManagementRole::Cem,
872                    self.core.state.phase(),
873                    self.core.s2_connect,
874                    now,
875                    &seen,
876                    self.core.skew_tolerance,
877                );
878                crate::model::explain(&message, &ctx)
879            };
880            // Two different faults, and telling them apart is the point of having rule
881            // identifiers at all: a timer that has not finished is a "wait", and an
882            // abnormal-condition-only mode used without `abnormal_condition` is a
883            // "never".
884            if let Some(explanation) = explanation.filter(|e| !e.is_actionable()) {
885                let (rule, reason) = if let Some((timer, label)) = explanation.blocked_by.first() {
886                    (
887                        rules::BLOCKED_BY_TIMER,
888                        alloc::format!(
889                            "{} {timer} has not finished, and it blocks this transition",
890                            label.as_deref().unwrap_or("timer")
891                        ),
892                    )
893                } else {
894                    (
895                        rules::ABNORMAL_ONLY,
896                        "this instruction uses an option marked abnormal_condition_only                          without setting abnormal_condition"
897                            .to_string(),
898                    )
899                };
900                let mut report = Report::new();
901                report.push(rule, "", reason);
902                if let Some(violation) = report.violations().first() {
903                    return Err(SendError::Invalid(Box::new(violation.clone())));
904                }
905            }
906        }
907        self.send(message, now)
908    }
909
910    /// Withdraw something published earlier.
911    pub fn revoke(
912        &mut self,
913        object_type: RevokableObjects,
914        object_id: Id,
915        now: Timestamp,
916    ) -> Result<MessageHandle, SendError> {
917        let message_id = self.core.next_message_id();
918        let handle = self.send(
919            RevokeObject {
920                message_id,
921                object_type,
922                object_id,
923            },
924            now,
925        )?;
926        self.core.registry.revoke(object_type, object_id);
927        Ok(handle)
928    }
929
930    /// Ask the peer to end or restart the session.
931    pub fn request_session(
932        &mut self,
933        request: SessionRequestType,
934        diagnostic: Option<String>,
935        now: Timestamp,
936    ) -> Result<MessageHandle, SendError> {
937        let message_id = self.core.next_message_id();
938        let handle = self.send(
939            SessionRequest {
940                message_id,
941                request,
942                diagnostic_label: diagnostic,
943            },
944            now,
945        )?;
946        // Having asked to end the session, this side stops using it. The request is
947        // already queued, so the peer still hears about it.
948        self.close_with(CloseReason::LocallyRequested(request));
949        Ok(handle)
950    }
951
952    /// Send a message.
953    pub fn send(
954        &mut self,
955        message: impl Into<Message>,
956        now: Timestamp,
957    ) -> Result<MessageHandle, SendError> {
958        let message = message.into();
959        let kind = message.kind();
960        if self.core.state.is_closed() {
961            return Err(SendError::Closed);
962        }
963        if !kind.exists_in(self.core.profile) {
964            return Err(SendError::NotInProfile {
965                kind,
966                profile: self.core.profile,
967            });
968        }
969        let allowance =
970            crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Cem, kind);
971        if !allowance.is_allowed() {
972            return Err(SendError::NotAllowed {
973                kind,
974                state: state_name(&self.core.state),
975            });
976        }
977        if self.config.validate_outbound {
978            let seen = self.core.acks.seen_ids();
979            let report = {
980                let ctx = self.core.registry.context(
981                    self.core.profile,
982                    EnergyManagementRole::Cem,
983                    self.core.state.phase(),
984                    self.core.s2_connect,
985                    now,
986                    &seen,
987                    self.core.skew_tolerance,
988                );
989                message.validate(&ctx)
990            };
991            if let Some(violation) = report.first_error() {
992                return Err(SendError::Invalid(Box::new(violation.clone())));
993            }
994            if !report.is_empty() {
995                self.core.stats.sent_with_warnings =
996                    self.core.stats.sent_with_warnings.saturating_add(1);
997                self.events
998                    .push_back(CemEvent::OutboundWarnings { kind, report });
999            }
1000        }
1001        self.core.transmit(message, now).ok_or(SendError::Closed)
1002    }
1003
1004    /// End the session locally.
1005    pub fn close(&mut self) {
1006        self.close_with(CloseReason::Local);
1007    }
1008
1009    fn close_with(&mut self, reason: CloseReason) {
1010        if self.core.state.is_closed() {
1011            return;
1012        }
1013        let reconnect_after = match &reason {
1014            CloseReason::Local => None,
1015            // `RECONNECT` — "Please reconnect the WebSocket session" — is an
1016            // instruction to come straight back, whoever sent it.
1017            CloseReason::PeerRequested(SessionRequestType::Reconnect)
1018            | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
1019            // `S2C §Reconnection strategy`: `random(0, min(max, base × 2^n))`. Drawn here
1020            // when there is an RNG to draw from, so a fleet that sleeps exactly this long
1021            // does not reconnect in lockstep; without `std` it is the ceiling, and the
1022            // firmware draws with [`Backoff::delay`](super::Backoff::delay).
1023            #[cfg(feature = "std")]
1024            _ => Some(self.backoff.delay_with(self.core.reconnect_attempt)),
1025            #[cfg(not(feature = "std"))]
1026            _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
1027        };
1028        self.core.state = SessionState::Closed(reason.clone());
1029        self.events.push_back(CemEvent::Closed {
1030            reason,
1031            reconnect_after,
1032        });
1033    }
1034}