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