Skip to main content

s2_kit/session/
rm.rs

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