Skip to main content

s2_kit/session/
mod.rs

1//! Sans-I/O session engines for both roles.
2//!
3//! A session is driven by four calls in and three out:
4//!
5//! ```text
6//! session.handle_text(&text, now)      session.poll_transmit()
7//! session.handle_message(message, now) session.poll_event()
8//! session.handle_timeout(now)          session.poll_timeout()
9//! session.transport_closed(now)
10//! ```
11//!
12//! No sockets, no clock, no tasks. `now` is a parameter, which is what makes a
13//! five-second acknowledgement timeout, a description that becomes valid at midnight and
14//! a timer that blocks a transition into ordinary unit tests rather than things you wait
15//! for.
16//!
17//! # What the engine does that an application would otherwise have to
18//!
19//! * **Acknowledges everything, synchronously.** `S2J` requires a `ReceptionStatus` for
20//!   every message except a `ReceptionStatus`, and the engine chooses it inside
21//!   `handle_text` — `INVALID_DATA` or `INVALID_MESSAGE` from the codec,
22//!   `INVALID_CONTENT` from the state table or the validator (with the failing rule's
23//!   identifier in the `diagnostic_label`), otherwise `OK`. Nothing is held across an
24//!   `await`, so the deadlock `[s2-json #22]` describes cannot happen.
25//! * **Tracks what is outstanding.** Every message sent enters a ledger with a deadline;
26//!   the matching acknowledgement resolves it, and a deadline that passes produces an
27//!   event rather than a stall.
28//! * **Enforces the state table.** `S2C §State of communication` says what may be sent
29//!   when; the engine refuses outbound messages at the call site and answers inbound ones
30//!   with `INVALID_CONTENT`.
31//! * **Resolves instructions.** An [`Instructed`] event carries the actuator, the
32//!   operation mode, the factor, the power it implies and any timer in the way — so a
33//!   Resource Manager never looks an identifier up by hand.
34//! * **Remembers.** Descriptions, constraints, profiles, instruction statuses, timers
35//!   and the active operation mode of every actuator, in a bounded [`Registry`].
36//!
37//! # Both roles, one core
38//!
39//! [`RmSession`] and [`CemSession`] are built on the same [`SessionCore`], so a CEM and
40//! an RM from this crate can be wired back to back in memory — which is how the
41//! standard's own documented conversations are tested.
42
43mod analyze;
44mod cem;
45pub mod core;
46mod rm;
47mod set;
48
49use alloc::string::String;
50
51pub use analyze::{Analyzer, Observed};
52pub use cem::{CemConfig, CemEvent, CemSession};
53pub use core::{
54    AckLedger, AckOutcome, Backoff, CloseReason, MessageHandle, Negotiation, OutOfOrderPolicy,
55    Outgoing, Registry, SendError, SessionCore, SessionState, Stats,
56};
57pub use rm::{Instructed, RmConfig, RmEvent, RmSession};
58pub use set::SessionSet;
59
60use crate::message::Message;
61use crate::message::MessageKind;
62use crate::types::common::ReceptionStatusValues;
63use crate::types::{ProtocolVersion, Timestamp};
64use crate::validate::Report;
65
66/// What both engines have in common: four calls in, three out, and a clock that is always
67/// a parameter.
68///
69/// The trait exists so that code which only pumps a session — [`SessionSet`],
70/// [`crate::io::Driver`], a test harness — does not need to know which role it is pumping.
71/// Neither engine is written against it; it describes what they already are.
72///
73/// It is deliberately not object-safe in spirit but is in fact: [`Self::Event`] keeps the
74/// two event enums distinct, because a CEM that receives `RmEvent::Instruction` would be
75/// a confusion, not a convenience.
76pub trait Session {
77    /// What this side tells its application about.
78    type Event;
79
80    /// Begin. Has no effect on a session that is already open.
81    fn open(&mut self, now: Timestamp);
82
83    /// Feed in one frame as it arrived from the transport.
84    fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound;
85
86    /// Feed in one already-decoded message.
87    fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound;
88
89    /// Tell the session the time has reached [`Self::poll_timeout`].
90    fn handle_timeout(&mut self, now: Timestamp);
91
92    /// Tell the session its transport has gone.
93    fn transport_closed(&mut self, now: Timestamp);
94
95    /// Take the next frame to send, if any.
96    fn poll_transmit(&mut self) -> Option<Outgoing>;
97
98    /// Take the next event for the application, if any.
99    fn poll_event(&mut self) -> Option<Self::Event>;
100
101    /// When the session next needs to be woken, if ever.
102    fn poll_timeout(&self) -> Option<Timestamp>;
103
104    /// Where the session has got to.
105    fn state(&self) -> &SessionState;
106
107    /// The version string the handshake settled on, once it has.
108    fn negotiated_version(&self) -> Option<&ProtocolVersion>;
109
110    /// Everything the session has learned about its peer.
111    fn registry(&self) -> &Registry;
112
113    /// What this session has done, for an operator's metrics.
114    fn stats(&self) -> Stats;
115
116    /// Queue a close.
117    fn close(&mut self);
118}
119
120macro_rules! impl_session {
121    ($ty:ty, $event:ty) => {
122        impl Session for $ty {
123            type Event = $event;
124
125            fn open(&mut self, now: Timestamp) {
126                <$ty>::open(self, now);
127            }
128            fn handle_text(&mut self, text: &str, now: Timestamp) -> Inbound {
129                <$ty>::handle_text(self, text, now)
130            }
131            fn handle_message(&mut self, message: Message, now: Timestamp) -> Inbound {
132                <$ty>::handle_message(self, message, now)
133            }
134            fn handle_timeout(&mut self, now: Timestamp) {
135                <$ty>::handle_timeout(self, now);
136            }
137            fn transport_closed(&mut self, now: Timestamp) {
138                <$ty>::transport_closed(self, now);
139            }
140            fn poll_transmit(&mut self) -> Option<Outgoing> {
141                <$ty>::poll_transmit(self)
142            }
143            fn poll_event(&mut self) -> Option<$event> {
144                <$ty>::poll_event(self)
145            }
146            fn poll_timeout(&self) -> Option<Timestamp> {
147                <$ty>::poll_timeout(self)
148            }
149            fn state(&self) -> &SessionState {
150                <$ty>::state(self)
151            }
152            fn negotiated_version(&self) -> Option<&ProtocolVersion> {
153                <$ty>::negotiated_version(self)
154            }
155            fn registry(&self) -> &Registry {
156                <$ty>::registry(self)
157            }
158            fn stats(&self) -> Stats {
159                <$ty>::stats(self)
160            }
161            fn close(&mut self) {
162                <$ty>::close(self);
163            }
164        }
165    };
166}
167
168impl_session!(RmSession, RmEvent);
169impl_session!(CemSession, CemEvent);
170
171/// What an engine did with one inbound message.
172#[derive(Debug, Clone, PartialEq)]
173pub struct Inbound {
174    /// What the message claimed to be, where that could be read at all.
175    pub kind: Option<MessageKind>,
176    /// The message's own `message_id`, where it had a readable one.
177    ///
178    /// `None` for a `ReceptionStatus`, which has no identifier of its own, and for a frame
179    /// too broken to read one from. It is the key that joins an operator's log line, the
180    /// `ReceptionStatus` this side sent, and the peer's own record of the exchange.
181    pub message_id: Option<crate::types::Id>,
182    /// The reception status that was queued in reply.
183    pub status: ReceptionStatusValues,
184    /// Everything the validator found, errors and warnings alike.
185    pub report: Report,
186}
187
188impl Inbound {
189    pub(crate) fn ignored(kind: MessageKind, message_id: Option<crate::types::Id>) -> Self {
190        Self {
191            kind: Some(kind),
192            message_id,
193            status: ReceptionStatusValues::Ok,
194            report: Report::new(),
195        }
196    }
197
198    /// Whether the message was accepted.
199    #[must_use]
200    pub fn accepted(&self) -> bool {
201        self.status == ReceptionStatusValues::Ok
202    }
203}
204
205/// A hook consulted before an inbound message is acknowledged.
206///
207/// The engine chooses every reception status itself, because an acknowledgement that an
208/// application can forget is one that will be forgotten. This is the exception: the two
209/// statuses that are about the *receiver* rather than the message —
210/// `TEMPORARY_ERROR` ("Receiver encountered an error", so try again) and
211/// `PERMANENT_ERROR` ("an error which it cannot recover from", so disconnect) — are
212/// things only the application knows about.
213///
214/// It is called synchronously, inside `handle_text`, and must not block.
215///
216/// ```
217/// use s2_kit::prelude::*;
218/// use s2_kit::session::InboundPolicy;
219///
220/// struct RefuseWhenStorageIsDown {
221///     storage_available: bool,
222/// }
223///
224/// impl InboundPolicy for RefuseWhenStorageIsDown {
225///     fn review(&mut self, message: &Message) -> Option<(ReceptionStatusValues, String)> {
226///         if !self.storage_available && message.is_instruction() {
227///             return Some((
228///                 ReceptionStatusValues::TemporaryError,
229///                 "the device is not reachable right now".into(),
230///             ));
231///         }
232///         None
233///     }
234/// }
235/// ```
236pub trait InboundPolicy {
237    /// Refuse the message, or `None` to let the engine decide.
238    fn review(&mut self, message: &crate::Message) -> Option<(ReceptionStatusValues, String)>;
239}
240
241impl<F> InboundPolicy for F
242where
243    F: FnMut(&crate::Message) -> Option<(ReceptionStatusValues, String)>,
244{
245    fn review(&mut self, message: &crate::Message) -> Option<(ReceptionStatusValues, String)> {
246        self(message)
247    }
248}