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