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