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        reconnect_after: Option<Duration>,
259    },
260}
261
262/// A Customer Energy Manager's side of one S2 session.
263///
264/// The mirror of [`RmSession`](super::RmSession), over the same core: the same state
265/// table, the same acknowledgement ledger, the same registry. Wiring one of each
266/// together through [`crate::testing::Conversation`] is how the documented conversations are
267/// tested.
268pub struct CemSession {
269    core: SessionCore,
270    config: CemConfig,
271    events: VecDeque<CemEvent>,
272    peer_versions: Vec<ProtocolVersion>,
273    negotiated: Option<ProtocolVersion>,
274    handshake_sent: bool,
275    pending_control_type: Option<(Id, ControlType)>,
276    policy: Option<Box<dyn InboundPolicy + Send>>,
277    backoff: Backoff,
278}
279
280impl core::fmt::Debug for CemSession {
281    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
282        f.debug_struct("CemSession")
283            .field("state", &self.core.state)
284            .field("profile", &self.core.profile)
285            .field("outstanding_acks", &self.core.acks.outstanding())
286            .field("queued", &self.core.outbox.len())
287            .finish_non_exhaustive()
288    }
289}
290
291impl CemSession {
292    /// A manager's side of a session, not yet opened.
293    #[must_use]
294    pub fn new(config: CemConfig) -> Self {
295        let core = SessionCore::new(CoreConfig {
296            role: EnergyManagementRole::Cem,
297            negotiation: config.negotiation.clone(),
298            ack_timeout: config.ack_timeout,
299            out_of_order: config.out_of_order,
300            skew_tolerance: config.skew_tolerance,
301            max_message_bytes: config.max_message_bytes,
302            strictness: config.strictness,
303            s2_connect: config.s2_connect,
304            reconnect_attempt: config.reconnect_attempt,
305        });
306        Self {
307            core,
308            config,
309            events: VecDeque::new(),
310            peer_versions: Vec::new(),
311            negotiated: None,
312            handshake_sent: false,
313            pending_control_type: None,
314            policy: None,
315            backoff: Backoff::default(),
316        }
317    }
318
319    /// Install a hook consulted before every inbound message is acknowledged.
320    pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
321        self.policy = Some(policy);
322    }
323
324    /// Where the session has got to.
325    #[must_use]
326    pub fn state(&self) -> &SessionState {
327        &self.core.state
328    }
329
330    /// The wire profile in use.
331    #[must_use]
332    pub fn profile(&self) -> WireProfile {
333        self.core.profile
334    }
335
336    /// What this session has done, for an operator's metrics rather than for the
337    /// application: how many messages crossed, how many were refused, and how long the
338    /// peer takes to answer.
339    #[must_use]
340    pub fn stats(&self) -> super::core::Stats {
341        self.core.stats
342    }
343
344    /// Everything this session has learned about the resource.
345    #[must_use]
346    pub fn registry(&self) -> &super::core::Registry {
347        &self.core.registry
348    }
349
350    /// The resource's details, once it has sent them.
351    #[must_use]
352    pub fn details(&self) -> Option<&ResourceManagerDetails> {
353        self.core.registry.details.as_ref()
354    }
355
356    /// Begin.
357    ///
358    /// With a handshake, this queues one — the Resource Manager also sends one, and
359    /// neither order is wrong. With a version already agreed, it does nothing but wait
360    /// for the resource's details.
361    pub fn open(&mut self, now: Timestamp) {
362        if !matches!(self.core.state, SessionState::Idle) {
363            return;
364        }
365        match &self.config.negotiation {
366            Negotiation::Handshake => {
367                self.core.state = SessionState::Handshaking;
368                self.handshake_sent = true;
369                let handshake = Handshake {
370                    message_id: self.core.next_message_id(),
371                    role: EnergyManagementRole::Cem,
372                    supported_protocol_versions: Some(self.config.supported_versions.clone()),
373                };
374                self.core.transmit(Message::from(handshake), now);
375            }
376            Negotiation::PreNegotiated(profile) => {
377                let profile = *profile;
378                self.core.profile = profile;
379                self.negotiated = Some(profile.version());
380                self.core.state = SessionState::Connected;
381                self.events.push_back(CemEvent::Negotiated {
382                    version: profile.version(),
383                    profile,
384                });
385            }
386        }
387    }
388
389    /// The next message to put on the wire.
390    pub fn poll_transmit(&mut self) -> Option<Outgoing> {
391        self.core.poll_transmit()
392    }
393
394    /// The next thing the application needs to know.
395    pub fn poll_event(&mut self) -> Option<CemEvent> {
396        self.events.pop_front()
397    }
398
399    /// When [`handle_timeout`](Self::handle_timeout) next has something to do.
400    #[must_use]
401    pub fn poll_timeout(&self) -> Option<Timestamp> {
402        self.core.poll_timeout()
403    }
404
405    /// Feed in one text frame. Never fails.
406    ///
407    /// A frame that arrives after the session is over is ignored rather than answered:
408    /// the transport is gone, so an acknowledgement queued for it is one nobody will
409    /// ever read — and a closed session that keeps filling its outbox is a closed
410    /// session that keeps growing. [`handle_message`](Self::handle_message) makes the
411    /// same check; this one is for the frames that never get that far.
412    pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
413        if self.core.state.is_closed() {
414            return Inbound {
415                kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
416                status: ReceptionStatusValues::Ok,
417                report: Report::new(),
418            };
419        }
420        self.core.stats.received = self.core.stats.received.saturating_add(1);
421        let options = self.core.decode_options();
422        match codec::decode_with(text, &options) {
423            Ok(decoded) => {
424                if !decoded.pruned.is_empty() {
425                    let mut report = Report::new();
426                    for path in &decoded.pruned {
427                        report.push(
428                            rules::UNKNOWN_PROPERTY,
429                            path,
430                            "property is not defined by the schema and was removed",
431                        );
432                    }
433                    self.events.push_back(CemEvent::Warnings {
434                        kind: decoded.message.kind(),
435                        report,
436                    });
437                }
438                self.handle_message(decoded.message, now)
439            }
440            Err(error) => {
441                self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
442                let kind = error.peek().and_then(|p| p.kind);
443                let status = error.reception_status();
444                if kind != Some(MessageKind::ReceptionStatus) {
445                    self.core.acknowledge(
446                        status.subject_message_id,
447                        status.status,
448                        status.diagnostic_label.clone(),
449                        now,
450                    );
451                }
452                let mut report = Report::new();
453                report.push(rules::DECODE_FAILED, "", error.to_string());
454                self.events.push_back(CemEvent::Refused {
455                    kind,
456                    status: status.status,
457                    report: report.clone(),
458                });
459                Inbound {
460                    kind,
461                    status: status.status,
462                    report,
463                }
464            }
465        }
466    }
467
468    /// Feed in one already-decoded message.
469    pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
470        if self.core.state.is_closed() {
471            return Inbound::ignored(message.kind());
472        }
473
474        if let Message::ReceptionStatus(status) = &message {
475            self.on_reception_status(status, now);
476            return Inbound {
477                kind: Some(MessageKind::ReceptionStatus),
478                status: ReceptionStatusValues::Ok,
479                report: Report::new(),
480            };
481        }
482
483        let kind = message.kind();
484        let Some(id) = message.id() else {
485            return Inbound::ignored(kind);
486        };
487
488        if let Some(previous) = self.core.acks.previous_answer(id) {
489            // Answered again with the same status, and deliberately not processed twice:
490            // that is what makes the engine idempotent under a proxy that retries. It is
491            // reported, because a peer that reuses identifiers is a bug worth seeing.
492            self.core.acknowledge(id, previous, None, now);
493            self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
494            let mut report = Report::new();
495            report.push_related(
496                rules::DUPLICATE_MESSAGE_ID,
497                "/message_id",
498                alloc::format!("{id} was already answered {previous:?}; not processed again"),
499                [id],
500            );
501            self.events.push_back(CemEvent::Warnings {
502                kind,
503                report: report.clone(),
504            });
505            return Inbound {
506                kind: Some(kind),
507                status: previous,
508                report,
509            };
510        }
511
512        let seen = self.core.acks.seen_ids();
513        let report = {
514            let ctx = self.core.registry.context(
515                self.core.profile,
516                EnergyManagementRole::Rm,
517                self.core.state.phase(),
518                self.core.s2_connect,
519                now,
520                &seen,
521                self.core.skew_tolerance,
522            );
523            message.validate(&ctx)
524        };
525
526        if report.has_errors() {
527            let status = ReceptionStatusValues::InvalidContent;
528            self.core
529                .acknowledge(id, status, report.diagnostic_label(), now);
530            let closing = self.config.out_of_order == OutOfOrderPolicy::Close
531                && (report.contains(rules::NOT_ALLOWED_IN_STATE)
532                    || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
533            self.events.push_back(CemEvent::Refused {
534                kind: Some(kind),
535                status,
536                report: report.clone(),
537            });
538            if closing {
539                let reason = CloseReason::ProtocolError(
540                    report
541                        .diagnostic_label()
542                        .unwrap_or_else(|| "out of order".to_string()),
543                );
544                self.close_with(reason);
545            }
546            return Inbound {
547                kind: Some(kind),
548                status,
549                report,
550            };
551        }
552
553        let policy = self
554            .policy
555            .as_mut()
556            .and_then(|policy| policy.review(&message));
557        if let Some((status, diagnostic)) = policy {
558            self.core
559                .acknowledge(id, status, Some(diagnostic.clone()), now);
560            let mut refusal = report.clone();
561            refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
562            self.events.push_back(CemEvent::Refused {
563                kind: Some(kind),
564                status,
565                report: refusal,
566            });
567            return Inbound {
568                kind: Some(kind),
569                status,
570                report,
571            };
572        }
573
574        self.core
575            .acknowledge(id, ReceptionStatusValues::Ok, None, now);
576        if !report.is_empty() {
577            self.core.stats.accepted_with_warnings =
578                self.core.stats.accepted_with_warnings.saturating_add(1);
579            self.events.push_back(CemEvent::Warnings {
580                kind,
581                report: report.clone(),
582            });
583        }
584        self.process(message, now);
585        Inbound {
586            kind: Some(kind),
587            status: ReceptionStatusValues::Ok,
588            report,
589        }
590    }
591
592    fn process(&mut self, message: Message, now: Timestamp) {
593        match &message {
594            Message::Handshake(h) => {
595                if let Some(versions) = &h.supported_protocol_versions {
596                    self.peer_versions.clone_from(versions);
597                }
598                // The manager is the side that chooses: `S2J messages/Handshake` makes
599                // the version list mandatory for the RM and optional for the CEM,
600                // because the RM is the constrained side and the manager adapts.
601                // Canonical comparison, not `==`: an RM that speaks S2 Connect as well
602                // offers `v1.0.0` where this list holds `1.0.0`, and the two are the
603                // same version (E25, D31). What goes back out is *our* spelling, so the
604                // answer is always a string this side already offered.
605                let Some(chosen) = self
606                    .config
607                    .supported_versions
608                    .iter()
609                    .find(|ours| self.peer_versions.iter().any(|theirs| ours.matches(theirs)))
610                    .cloned()
611                else {
612                    self.close_with(CloseReason::NoCommonVersion);
613                    return;
614                };
615                let Some(profile) = chosen.wire_profile() else {
616                    self.close_with(CloseReason::NoCommonVersion);
617                    return;
618                };
619                self.core.profile = profile;
620                self.negotiated = Some(chosen.clone());
621                self.core.state = SessionState::Connected;
622                let message_id = self.core.next_message_id();
623                self.core.transmit(
624                    Message::from(HandshakeResponse {
625                        message_id,
626                        selected_protocol_version: chosen.clone(),
627                    }),
628                    now,
629                );
630                self.events.push_back(CemEvent::Negotiated {
631                    version: chosen,
632                    profile,
633                });
634                return;
635            }
636            Message::SessionRequest(request) => {
637                self.events.push_back(CemEvent::SessionRequested {
638                    request: request.request,
639                    diagnostic: request.diagnostic_label.clone(),
640                });
641                self.close_with(CloseReason::PeerRequested(request.request));
642                return;
643            }
644            Message::RevokeObject(revoke) => {
645                self.core
646                    .registry
647                    .revoke(revoke.object_type, revoke.object_id);
648                self.events.push_back(CemEvent::Revoked {
649                    object_type: revoke.object_type,
650                    object_id: revoke.object_id,
651                });
652                return;
653            }
654            _ => {}
655        }
656
657        self.core.registry.record(&message, Some(now));
658
659        let kind = message.kind();
660        match message {
661            Message::ResourceManagerDetails(details) => {
662                self.events.push_back(CemEvent::ResourceDescribed(details));
663            }
664            Message::PowerMeasurement(m) => {
665                self.events.push_back(CemEvent::Measurement(Box::new(m)));
666            }
667            Message::PowerForecast(f) => self.events.push_back(CemEvent::Forecast(f)),
668            Message::InstructionStatusUpdate(u) => {
669                self.events.push_back(CemEvent::InstructionStatus(u));
670            }
671            Message::FrbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
672                actuator: Some(s.actuator_id),
673                timer: s.timer_id,
674                finished_at: s.finished_at,
675            }),
676            Message::DdbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
677                actuator: Some(s.actuator_id),
678                timer: s.timer_id,
679                finished_at: s.finished_at,
680            }),
681            Message::OmbcTimerStatus(ref s) => self.events.push_back(CemEvent::TimerReported {
682                actuator: None,
683                timer: s.timer_id,
684                finished_at: s.finished_at,
685            }),
686            other => {
687                let is_description = matches!(
688                    kind,
689                    MessageKind::FrbcSystemDescription
690                        | MessageKind::OmbcSystemDescription
691                        | MessageKind::DdbcSystemDescription
692                        | MessageKind::PebcPowerConstraints
693                        | MessageKind::PebcEnergyConstraint
694                        | MessageKind::PpbcPowerProfileDefinition
695                        | MessageKind::FrbcLeakageBehaviour
696                        | MessageKind::FrbcUsageForecast
697                        | MessageKind::FrbcFillLevelTargetProfile
698                        | MessageKind::DdbcAverageDemandRateForecast
699                );
700                if is_description {
701                    self.events.push_back(CemEvent::Description {
702                        kind,
703                        message: other,
704                    });
705                } else {
706                    self.events.push_back(CemEvent::Status {
707                        kind,
708                        message: other,
709                    });
710                }
711            }
712        }
713    }
714
715    fn on_reception_status(
716        &mut self,
717        status: &crate::types::common::ReceptionStatus,
718        now: Timestamp,
719    ) {
720        match self.core.acks.received(status, now) {
721            AckOutcome::Accepted { handle, latency } => {
722                self.core.stats.acked = self.core.stats.acked.saturating_add(1);
723                self.core.stats.record_latency(latency);
724                // A control type becomes active when the resource says it accepted the
725                // selection, not when the manager decided to ask.
726                if let Some((id, control_type)) = self.pending_control_type
727                    && id == handle.id
728                {
729                    self.pending_control_type = None;
730                    if control_type == ControlType::NoSelection {
731                        self.core.state = SessionState::Connected;
732                        self.events.push_back(CemEvent::Deselected);
733                    } else {
734                        self.core.state = SessionState::ControlTypeSelected(control_type);
735                        self.events.push_back(CemEvent::Ready { control_type });
736                    }
737                }
738                self.events.push_back(CemEvent::Acked(handle));
739            }
740            AckOutcome::Refused {
741                handle,
742                status,
743                diagnostic,
744                consequence,
745                latency,
746            } => {
747                self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
748                self.core.stats.record_latency(latency);
749                if self
750                    .pending_control_type
751                    .is_some_and(|(id, _)| id == handle.id)
752                {
753                    self.pending_control_type = None;
754                }
755                self.events.push_back(CemEvent::Nacked {
756                    handle,
757                    status,
758                    diagnostic: diagnostic.clone(),
759                    consequence,
760                });
761                if consequence == Consequence::Disconnect {
762                    self.close_with(CloseReason::PermanentError(
763                        diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
764                    ));
765                }
766            }
767            AckOutcome::TimedOut(handle) => {
768                self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
769                self.events.push_back(CemEvent::AckTimedOut(handle));
770            }
771            AckOutcome::Unmatched { subject, status } => {
772                self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
773                self.events
774                    .push_back(CemEvent::UnmatchedAck { subject, status });
775            }
776        }
777    }
778
779    /// Let time pass.
780    pub fn handle_timeout(&mut self, now: Timestamp) {
781        for handle in self.core.acks.expire(now) {
782            if self
783                .pending_control_type
784                .is_some_and(|(id, _)| id == handle.id)
785            {
786                self.pending_control_type = None;
787            }
788            self.events.push_back(CemEvent::AckTimedOut(handle));
789        }
790        for message in self.core.registry.activate_due(now) {
791            self.events.push_back(CemEvent::DescriptionActivated {
792                kind: message.kind(),
793            });
794        }
795    }
796
797    /// The transport went away.
798    pub fn transport_closed(&mut self, now: Timestamp) {
799        let _ = now;
800        self.close_with(CloseReason::TransportClosed);
801    }
802
803    /// Activate a control type.
804    ///
805    /// The session does not become active until the resource acknowledges it, which is
806    /// when [`CemEvent::Ready`] arrives.
807    pub fn select_control_type(
808        &mut self,
809        control_type: ControlType,
810        now: Timestamp,
811    ) -> Result<MessageHandle, SendError> {
812        let message_id = self.core.next_message_id();
813        let handle = self.send(
814            SelectControlType {
815                message_id,
816                control_type,
817            },
818            now,
819        )?;
820        self.pending_control_type = Some((handle.id, control_type));
821        Ok(handle)
822    }
823
824    /// Send an instruction.
825    pub fn instruct(
826        &mut self,
827        instruction: impl Into<Message>,
828        now: Timestamp,
829    ) -> Result<MessageHandle, SendError> {
830        let message = instruction.into();
831        if self.config.enforce_transitions {
832            let seen = self.core.acks.seen_ids();
833            let explanation = {
834                let ctx = self.core.registry.context(
835                    self.core.profile,
836                    EnergyManagementRole::Cem,
837                    self.core.state.phase(),
838                    self.core.s2_connect,
839                    now,
840                    &seen,
841                    self.core.skew_tolerance,
842                );
843                crate::model::explain(&message, &ctx)
844            };
845            // Two different faults, and telling them apart is the point of having rule
846            // identifiers at all: a timer that has not finished is a "wait", and an
847            // abnormal-condition-only mode used without `abnormal_condition` is a
848            // "never".
849            if let Some(explanation) = explanation.filter(|e| !e.is_actionable()) {
850                let (rule, reason) = if let Some((timer, label)) = explanation.blocked_by.first() {
851                    (
852                        rules::BLOCKED_BY_TIMER,
853                        alloc::format!(
854                            "{} {timer} has not finished, and it blocks this transition",
855                            label.as_deref().unwrap_or("timer")
856                        ),
857                    )
858                } else {
859                    (
860                        rules::ABNORMAL_ONLY,
861                        "this instruction uses an option marked abnormal_condition_only                          without setting abnormal_condition"
862                            .to_string(),
863                    )
864                };
865                let mut report = Report::new();
866                report.push(rule, "", reason);
867                if let Some(violation) = report.violations().first() {
868                    return Err(SendError::Invalid(Box::new(violation.clone())));
869                }
870            }
871        }
872        self.send(message, now)
873    }
874
875    /// Withdraw something published earlier.
876    pub fn revoke(
877        &mut self,
878        object_type: RevokableObjects,
879        object_id: Id,
880        now: Timestamp,
881    ) -> Result<MessageHandle, SendError> {
882        let message_id = self.core.next_message_id();
883        let handle = self.send(
884            RevokeObject {
885                message_id,
886                object_type,
887                object_id,
888            },
889            now,
890        )?;
891        self.core.registry.revoke(object_type, object_id);
892        Ok(handle)
893    }
894
895    /// Ask the peer to end or restart the session.
896    pub fn request_session(
897        &mut self,
898        request: SessionRequestType,
899        diagnostic: Option<String>,
900        now: Timestamp,
901    ) -> Result<MessageHandle, SendError> {
902        let message_id = self.core.next_message_id();
903        let handle = self.send(
904            SessionRequest {
905                message_id,
906                request,
907                diagnostic_label: diagnostic,
908            },
909            now,
910        )?;
911        // Having asked to end the session, this side stops using it. The request is
912        // already queued, so the peer still hears about it.
913        self.close_with(CloseReason::LocallyRequested(request));
914        Ok(handle)
915    }
916
917    /// Send a message.
918    pub fn send(
919        &mut self,
920        message: impl Into<Message>,
921        now: Timestamp,
922    ) -> Result<MessageHandle, SendError> {
923        let message = message.into();
924        let kind = message.kind();
925        if self.core.state.is_closed() {
926            return Err(SendError::Closed);
927        }
928        if !kind.exists_in(self.core.profile) {
929            return Err(SendError::NotInProfile {
930                kind,
931                profile: self.core.profile,
932            });
933        }
934        let allowance =
935            crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Cem, kind);
936        if !allowance.is_allowed() {
937            return Err(SendError::NotAllowed {
938                kind,
939                state: state_name(&self.core.state),
940            });
941        }
942        if self.config.validate_outbound {
943            let seen = self.core.acks.seen_ids();
944            let report = {
945                let ctx = self.core.registry.context(
946                    self.core.profile,
947                    EnergyManagementRole::Cem,
948                    self.core.state.phase(),
949                    self.core.s2_connect,
950                    now,
951                    &seen,
952                    self.core.skew_tolerance,
953                );
954                message.validate(&ctx)
955            };
956            if let Some(violation) = report.first_error() {
957                return Err(SendError::Invalid(Box::new(violation.clone())));
958            }
959            if !report.is_empty() {
960                self.core.stats.sent_with_warnings =
961                    self.core.stats.sent_with_warnings.saturating_add(1);
962                self.events
963                    .push_back(CemEvent::OutboundWarnings { kind, report });
964            }
965        }
966        self.core.transmit(message, now).ok_or(SendError::Closed)
967    }
968
969    /// End the session locally.
970    pub fn close(&mut self) {
971        self.close_with(CloseReason::Local);
972    }
973
974    fn close_with(&mut self, reason: CloseReason) {
975        if self.core.state.is_closed() {
976            return;
977        }
978        let reconnect_after = match &reason {
979            CloseReason::Local => None,
980            // `RECONNECT` — "Please reconnect the WebSocket session" — is an
981            // instruction to come straight back, whoever sent it.
982            CloseReason::PeerRequested(SessionRequestType::Reconnect)
983            | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
984            _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
985        };
986        self.core.state = SessionState::Closed(reason.clone());
987        self.events.push_back(CemEvent::Closed {
988            reason,
989            reconnect_after,
990        });
991    }
992}