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