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        reconnect_after: Option<Duration>,
248    },
249}
250
251/// A Resource Manager's side of one S2 session.
252///
253/// Sans-I/O: it never touches a socket and never reads a clock. Feed it text and a
254/// `now`, drain what it wants to send, drain what it wants to tell you.
255///
256/// ```
257/// use s2_kit::prelude::*;
258/// use s2_kit::session::{RmConfig, RmSession};
259///
260/// # let details = ResourceManagerDetails::builder()
261/// #     .resource_id(Id::parse("battery-1").unwrap())
262/// #     .roles(vec![Role::new(RoleType::EnergyStorage, Commodity::Electricity)])
263/// #     .instruction_processing_delay(Duration::from_millis(500))
264/// #     .available_control_types(vec![ControlType::FillRateBasedControl])
265/// #     .provides_forecast(false)
266/// #     .provides_power_measurement_types(vec![CommodityQuantity::ElectricPowerL1])
267/// #     .build();
268/// let now: Timestamp = "2024-01-01T12:00:00Z".parse().unwrap();
269/// let mut rm = RmSession::new(RmConfig::default(), details);
270/// rm.open(now);
271///
272/// let hello = rm.poll_transmit().unwrap();
273/// assert_eq!(hello.kind, MessageKind::Handshake);
274/// ```
275pub struct RmSession {
276    core: SessionCore,
277    details: ResourceManagerDetails,
278    config: RmConfig,
279    events: VecDeque<RmEvent>,
280    peer_versions: Vec<ProtocolVersion>,
281    negotiated: Option<ProtocolVersion>,
282    handshake_seen: bool,
283    policy: Option<Box<dyn InboundPolicy + Send>>,
284    backoff: Backoff,
285}
286
287impl core::fmt::Debug for RmSession {
288    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
289        f.debug_struct("RmSession")
290            .field("state", &self.core.state)
291            .field("profile", &self.core.profile)
292            .field("outstanding_acks", &self.core.acks.outstanding())
293            .field("queued", &self.core.outbox.len())
294            .finish_non_exhaustive()
295    }
296}
297
298impl RmSession {
299    /// A session for one resource, not yet opened.
300    #[must_use]
301    pub fn new(config: RmConfig, details: ResourceManagerDetails) -> Self {
302        let core = SessionCore::new(CoreConfig {
303            role: EnergyManagementRole::Rm,
304            negotiation: config.negotiation.clone(),
305            ack_timeout: config.ack_timeout,
306            out_of_order: config.out_of_order,
307            skew_tolerance: config.skew_tolerance,
308            max_message_bytes: config.max_message_bytes,
309            strictness: config.strictness,
310            s2_connect: config.s2_connect,
311            reconnect_attempt: config.reconnect_attempt,
312        });
313        Self {
314            core,
315            details,
316            config,
317            events: VecDeque::new(),
318            peer_versions: Vec::new(),
319            negotiated: None,
320            handshake_seen: false,
321            policy: None,
322            backoff: Backoff::default(),
323        }
324    }
325
326    /// Install a hook consulted before every inbound message is acknowledged.
327    ///
328    /// This is the only way to answer `TEMPORARY_ERROR` or `PERMANENT_ERROR`: the
329    /// engine chooses every other status itself, synchronously, so that an
330    /// acknowledgement can never be forgotten or delayed.
331    pub fn set_inbound_policy(&mut self, policy: Box<dyn InboundPolicy + Send>) {
332        self.policy = Some(policy);
333    }
334
335    /// Where the session has got to.
336    #[must_use]
337    pub fn state(&self) -> &SessionState {
338        &self.core.state
339    }
340
341    /// The wire profile in use.
342    #[must_use]
343    pub fn profile(&self) -> WireProfile {
344        self.core.profile
345    }
346
347    /// What this session has done, for an operator's metrics rather than for the
348    /// application: how many messages crossed, how many were refused, and how long the
349    /// peer takes to answer.
350    #[must_use]
351    pub fn stats(&self) -> super::core::Stats {
352        self.core.stats
353    }
354
355    /// Everything this session has learned, for a validator or a user interface.
356    #[must_use]
357    pub fn registry(&self) -> &super::core::Registry {
358        &self.core.registry
359    }
360
361    /// Begin. The Resource Manager speaks first.
362    ///
363    /// With a handshake, this queues one. With a version already agreed — S2 Connect —
364    /// it goes straight to sending the resource's details, which is what
365    /// `S2C §Communication - JSON messages` requires.
366    pub fn open(&mut self, now: Timestamp) {
367        if !matches!(self.core.state, SessionState::Idle) {
368            return;
369        }
370        match &self.config.negotiation {
371            Negotiation::Handshake => {
372                let handshake = Handshake {
373                    message_id: self.core.next_message_id(),
374                    role: EnergyManagementRole::Rm,
375                    supported_protocol_versions: Some(self.config.offered_versions.clone()),
376                };
377                self.core.state = SessionState::Handshaking;
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(RmEvent::Negotiated {
386                    version: profile.version(),
387                    profile,
388                });
389                self.send_details(now);
390            }
391        }
392    }
393
394    fn send_details(&mut self, now: Timestamp) {
395        let mut details = self.details.clone();
396        details.message_id = self.core.next_message_id();
397        self.core.transmit(Message::from(details), now);
398    }
399
400    /// The next message to put on the wire.
401    pub fn poll_transmit(&mut self) -> Option<Outgoing> {
402        self.core.poll_transmit()
403    }
404
405    /// The next thing the application needs to know.
406    pub fn poll_event(&mut self) -> Option<RmEvent> {
407        self.events.pop_front()
408    }
409
410    /// When [`handle_timeout`](Self::handle_timeout) next has something to do.
411    #[must_use]
412    pub fn poll_timeout(&self) -> Option<Timestamp> {
413        self.core.poll_timeout()
414    }
415
416    /// Feed in one text frame. Never fails: every failure is answered and reported.
417    ///
418    /// A frame that arrives after the session is over is ignored rather than answered:
419    /// the transport is gone, so an acknowledgement queued for it is one nobody will
420    /// ever read — and a closed session that keeps filling its outbox is a closed
421    /// session that keeps growing. [`handle_message`](Self::handle_message) makes the
422    /// same check; this one is for the frames that never get that far.
423    pub fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
424        if self.core.state.is_closed() {
425            return Inbound {
426                kind: crate::codec::peek(text).ok().and_then(|p| p.kind),
427                status: ReceptionStatusValues::Ok,
428                report: Report::new(),
429            };
430        }
431        self.core.stats.received = self.core.stats.received.saturating_add(1);
432        let options = self.core.decode_options();
433        match codec::decode_with(text, &options) {
434            Ok(decoded) => {
435                if !decoded.pruned.is_empty() {
436                    let mut report = Report::new();
437                    for path in &decoded.pruned {
438                        report.push(
439                            rules::UNKNOWN_PROPERTY,
440                            path,
441                            "property is not defined by the schema and was removed",
442                        );
443                    }
444                    self.events.push_back(RmEvent::Warnings {
445                        kind: decoded.message.kind(),
446                        report,
447                    });
448                }
449                self.handle_message(decoded.message, now)
450            }
451            Err(error) => {
452                self.core.stats.undecodable = self.core.stats.undecodable.saturating_add(1);
453                let kind = error.peek().and_then(|p| p.kind);
454                let status = error.reception_status();
455                // A `ReceptionStatus` is never acknowledged, even a broken one:
456                // answering it would be an infinite politeness.
457                if kind != Some(MessageKind::ReceptionStatus) {
458                    self.core.acknowledge(
459                        status.subject_message_id,
460                        status.status,
461                        status.diagnostic_label.clone(),
462                        now,
463                    );
464                }
465                let mut report = Report::new();
466                report.push(rules::DECODE_FAILED, "", error.to_string());
467                self.events.push_back(RmEvent::Refused {
468                    kind,
469                    status: status.status,
470                    report: report.clone(),
471                });
472                Inbound {
473                    kind,
474                    status: status.status,
475                    report,
476                }
477            }
478        }
479    }
480
481    /// Feed in one already-decoded message.
482    pub fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
483        if self.core.state.is_closed() {
484            return Inbound::ignored(message.kind());
485        }
486
487        // A ReceptionStatus is the one message that is never itself acknowledged.
488        if let Message::ReceptionStatus(status) = &message {
489            self.on_reception_status(status, now);
490            return Inbound {
491                kind: Some(MessageKind::ReceptionStatus),
492                status: ReceptionStatusValues::Ok,
493                report: Report::new(),
494            };
495        }
496
497        let kind = message.kind();
498        let Some(id) = message.id() else {
499            return Inbound::ignored(kind);
500        };
501
502        // A duplicate delivery is answered again with the same status and not processed
503        // twice, which makes the engine idempotent under a proxy that retries.
504        if let Some(previous) = self.core.acks.previous_answer(id) {
505            // Answered again with the same status, and deliberately not processed twice:
506            // that is what makes the engine idempotent under a proxy that retries. It is
507            // reported, because a peer that reuses identifiers is a bug worth seeing.
508            self.core.acknowledge(id, previous, None, now);
509            self.core.stats.duplicates = self.core.stats.duplicates.saturating_add(1);
510            let mut report = Report::new();
511            report.push_related(
512                rules::DUPLICATE_MESSAGE_ID,
513                "/message_id",
514                alloc::format!("{id} was already answered {previous:?}; not processed again"),
515                [id],
516            );
517            self.events.push_back(RmEvent::Warnings {
518                kind,
519                report: report.clone(),
520            });
521            return Inbound {
522                kind: Some(kind),
523                status: previous,
524                report,
525            };
526        }
527
528        let seen = self.core.acks.seen_ids();
529        let report = {
530            let ctx = self.core.registry.context(
531                self.core.profile,
532                EnergyManagementRole::Cem,
533                self.core.state.phase(),
534                self.core.s2_connect,
535                now,
536                &seen,
537                self.core.skew_tolerance,
538            );
539            message.validate(&ctx)
540        };
541
542        if report.has_errors() {
543            let status = ReceptionStatusValues::InvalidContent;
544            self.core
545                .acknowledge(id, status, report.diagnostic_label(), now);
546            let closing = self.config.out_of_order == OutOfOrderPolicy::Close
547                && (report.contains(rules::NOT_ALLOWED_IN_STATE)
548                    || report.contains(rules::NOT_ALLOWED_FOR_ROLE));
549            self.events.push_back(RmEvent::Refused {
550                kind: Some(kind),
551                status,
552                report: report.clone(),
553            });
554            if closing {
555                let reason = CloseReason::ProtocolError(
556                    report
557                        .diagnostic_label()
558                        .unwrap_or_else(|| "out of order".to_string()),
559                );
560                self.close_with(reason);
561            }
562            return Inbound {
563                kind: Some(kind),
564                status,
565                report,
566            };
567        }
568
569        // The application's only chance to refuse something it cannot store or act on.
570        let policy = self
571            .policy
572            .as_mut()
573            .and_then(|policy| policy.review(&message));
574        if let Some((status, diagnostic)) = policy {
575            self.core
576                .acknowledge(id, status, Some(diagnostic.clone()), now);
577            let mut refusal = report.clone();
578            refusal.push(rules::APPLICATION_REFUSED, "", diagnostic);
579            self.events.push_back(RmEvent::Refused {
580                kind: Some(kind),
581                status,
582                report: refusal,
583            });
584            return Inbound {
585                kind: Some(kind),
586                status,
587                report,
588            };
589        }
590
591        self.core
592            .acknowledge(id, ReceptionStatusValues::Ok, None, now);
593        if !report.is_empty() {
594            self.core.stats.accepted_with_warnings =
595                self.core.stats.accepted_with_warnings.saturating_add(1);
596            self.events.push_back(RmEvent::Warnings {
597                kind,
598                report: report.clone(),
599            });
600        }
601        self.process(message, now);
602        Inbound {
603            kind: Some(kind),
604            status: ReceptionStatusValues::Ok,
605            report,
606        }
607    }
608
609    /// Act on a message that has been accepted and acknowledged.
610    fn process(&mut self, message: Message, now: Timestamp) {
611        match &message {
612            Message::Handshake(h) => {
613                self.handshake_seen = true;
614                if let Some(versions) = &h.supported_protocol_versions {
615                    self.peer_versions.clone_from(versions);
616                }
617            }
618            Message::HandshakeResponse(response) => {
619                let selected = response.selected_protocol_version.clone();
620                // Canonical comparison, not `==`: the two specifications spell one
621                // version two ways and a CEM built on S2 Connect answers `v1.0.0` where
622                // an S2 JSON handshake writes `1.0.0` (E25, D31). Refusing that is
623                // refusing a peer that selected exactly what was offered.
624                if !self
625                    .config
626                    .offered_versions
627                    .iter()
628                    .any(|offered| offered.matches(&selected))
629                {
630                    self.close_with(CloseReason::UnsupportedVersion { selected });
631                    return;
632                }
633                let Some(profile) = selected.wire_profile() else {
634                    self.close_with(CloseReason::UnsupportedVersion { selected });
635                    return;
636                };
637                self.core.profile = profile;
638                self.negotiated = Some(selected.clone());
639                self.core.state = SessionState::Connected;
640                self.events.push_back(RmEvent::Negotiated {
641                    version: selected,
642                    profile,
643                });
644                self.send_details(now);
645            }
646            Message::SelectControlType(select) => {
647                let control_type = select.control_type;
648                if control_type == ControlType::NoSelection {
649                    self.core.state = SessionState::Connected;
650                    self.events.push_back(RmEvent::Deselected);
651                } else {
652                    self.core.state = SessionState::ControlTypeSelected(control_type);
653                    self.events.push_back(RmEvent::Ready { control_type });
654                }
655            }
656            Message::SessionRequest(request) => {
657                self.events.push_back(RmEvent::SessionRequested {
658                    request: request.request,
659                    diagnostic: request.diagnostic_label.clone(),
660                });
661                self.close_with(CloseReason::PeerRequested(request.request));
662                return;
663            }
664            Message::RevokeObject(revoke) => {
665                self.core
666                    .registry
667                    .revoke(revoke.object_type, revoke.object_id);
668                self.events.push_back(RmEvent::Revoked {
669                    object_type: revoke.object_type,
670                    object_id: revoke.object_id,
671                });
672                return;
673            }
674            _ => {}
675        }
676
677        self.core.registry.record(&message, Some(now));
678
679        if let Some(id) = message.instruction_id() {
680            let seen = self.core.acks.seen_ids();
681            let explanation = {
682                let ctx = self.core.registry.context(
683                    self.core.profile,
684                    EnergyManagementRole::Cem,
685                    self.core.state.phase(),
686                    self.core.s2_connect,
687                    now,
688                    &seen,
689                    self.core.skew_tolerance,
690                );
691                explain(&message, &ctx)
692            };
693            if let Some(explanation) = explanation {
694                self.events
695                    .push_back(RmEvent::Instruction(Box::new(Instructed {
696                        id,
697                        kind: message.kind(),
698                        message,
699                        explanation,
700                    })));
701            }
702        }
703    }
704
705    fn on_reception_status(
706        &mut self,
707        status: &crate::types::common::ReceptionStatus,
708        now: Timestamp,
709    ) {
710        match self.core.acks.received(status, now) {
711            AckOutcome::Accepted { handle, latency } => {
712                self.core.stats.acked = self.core.stats.acked.saturating_add(1);
713                self.core.stats.record_latency(latency);
714                self.events.push_back(RmEvent::Acked(handle));
715            }
716            AckOutcome::Refused {
717                handle,
718                status,
719                diagnostic,
720                consequence,
721                latency,
722            } => {
723                self.core.stats.nacked = self.core.stats.nacked.saturating_add(1);
724                self.core.stats.record_latency(latency);
725                self.events.push_back(RmEvent::Nacked {
726                    handle,
727                    status,
728                    diagnostic: diagnostic.clone(),
729                    consequence,
730                });
731                if consequence == Consequence::Disconnect {
732                    self.close_with(CloseReason::PermanentError(
733                        diagnostic.unwrap_or_else(|| "no diagnostic".to_string()),
734                    ));
735                }
736            }
737            AckOutcome::TimedOut(handle) => {
738                self.core.stats.ack_timeouts = self.core.stats.ack_timeouts.saturating_add(1);
739                self.events.push_back(RmEvent::AckTimedOut(handle));
740            }
741            AckOutcome::Unmatched { subject, status } => {
742                self.core.stats.unmatched_acks = self.core.stats.unmatched_acks.saturating_add(1);
743                self.events
744                    .push_back(RmEvent::UnmatchedAck { subject, status });
745            }
746        }
747    }
748
749    /// Let time pass: expire acknowledgements and activate scheduled descriptions.
750    pub fn handle_timeout(&mut self, now: Timestamp) {
751        for handle in self.core.acks.expire(now) {
752            self.events.push_back(RmEvent::AckTimedOut(handle));
753        }
754        for message in self.core.registry.activate_due(now) {
755            self.events.push_back(RmEvent::DescriptionActivated {
756                kind: message.kind(),
757            });
758        }
759    }
760
761    /// The transport went away.
762    pub fn transport_closed(&mut self, now: Timestamp) {
763        let _ = now;
764        self.close_with(CloseReason::TransportClosed);
765    }
766
767    /// Send a message.
768    ///
769    /// Refused at the call site when the state table does not allow it, when it does not
770    /// exist in the negotiated profile, or — unless `validate_outbound` is off — when it
771    /// would only earn an `INVALID_CONTENT` in reply.
772    pub fn send(
773        &mut self,
774        message: impl Into<Message>,
775        now: Timestamp,
776    ) -> Result<MessageHandle, SendError> {
777        let message = message.into();
778        let kind = message.kind();
779        if self.core.state.is_closed() {
780            return Err(SendError::Closed);
781        }
782        if !kind.exists_in(self.core.profile) {
783            return Err(SendError::NotInProfile {
784                kind,
785                profile: self.core.profile,
786            });
787        }
788        let allowance =
789            crate::validate::allowed(self.core.state.phase(), EnergyManagementRole::Rm, kind);
790        if !allowance.is_allowed() {
791            return Err(SendError::NotAllowed {
792                kind,
793                state: state_name(&self.core.state),
794            });
795        }
796        if self.config.validate_outbound {
797            let seen = self.core.acks.seen_ids();
798            let report = {
799                let ctx = self.core.registry.context(
800                    self.core.profile,
801                    EnergyManagementRole::Rm,
802                    self.core.state.phase(),
803                    self.core.s2_connect,
804                    now,
805                    &seen,
806                    self.core.skew_tolerance,
807                );
808                message.validate(&ctx)
809            };
810            if let Some(violation) = report.first_error() {
811                return Err(SendError::Invalid(Box::new(violation.clone())));
812            }
813            if !report.is_empty() {
814                self.core.stats.sent_with_warnings =
815                    self.core.stats.sent_with_warnings.saturating_add(1);
816                self.events
817                    .push_back(RmEvent::OutboundWarnings { kind, report });
818            }
819        }
820        self.core.transmit(message, now).ok_or(SendError::Closed)
821    }
822
823    /// Report what became of an instruction.
824    ///
825    /// The second of the two answers an instruction gets: the reception status said the
826    /// message was read, this says what the household did about it.
827    pub fn instruction_status(
828        &mut self,
829        instruction_id: Id,
830        status: InstructionStatus,
831        now: Timestamp,
832    ) -> Result<MessageHandle, SendError> {
833        let message_id = self.core.next_message_id();
834        self.send(
835            InstructionStatusUpdate {
836                message_id,
837                instruction_id,
838                status_type: status,
839                timestamp: now,
840            },
841            now,
842        )
843    }
844
845    /// Ask the peer to end or restart the session.
846    pub fn request_session(
847        &mut self,
848        request: SessionRequestType,
849        diagnostic: Option<String>,
850        now: Timestamp,
851    ) -> Result<MessageHandle, SendError> {
852        let message_id = self.core.next_message_id();
853        let handle = self.send(
854            SessionRequest {
855                message_id,
856                request,
857                diagnostic_label: diagnostic,
858            },
859            now,
860        )?;
861        // Having asked to end the session, this side stops using it. The request is
862        // already queued, so the peer still hears about it.
863        self.close_with(CloseReason::LocallyRequested(request));
864        Ok(handle)
865    }
866
867    /// End the session locally.
868    pub fn close(&mut self) {
869        self.close_with(CloseReason::Local);
870    }
871
872    fn close_with(&mut self, reason: CloseReason) {
873        if self.core.state.is_closed() {
874            return;
875        }
876        let reconnect_after = match &reason {
877            // Nothing to come back to.
878            CloseReason::Local => None,
879            // `RECONNECT` — "Please reconnect the WebSocket session" — is an
880            // instruction to come straight back, whoever sent it.
881            CloseReason::PeerRequested(SessionRequestType::Reconnect)
882            | CloseReason::LocallyRequested(SessionRequestType::Reconnect) => Some(Duration::ZERO),
883            _ => Some(self.backoff.ceiling(self.core.reconnect_attempt)),
884        };
885        self.core.state = SessionState::Closed(reason.clone());
886        self.events.push_back(RmEvent::Closed {
887            reason,
888            reconnect_after,
889        });
890    }
891}
892
893pub(crate) fn state_name(state: &SessionState) -> &'static str {
894    match state {
895        SessionState::Idle => "idle",
896        SessionState::Handshaking => "handshaking",
897        SessionState::Connected => "connected",
898        SessionState::ControlTypeSelected(_) => "control type selected",
899        SessionState::Closed(_) => "closed",
900    }
901}