s2_kit/io.rs
1//! Driving a session over a real transport.
2//!
3//! The engines are sans-I/O, so this module is thin on purpose: it flushes what a
4//! session wants to send, waits for the next of {a frame, the session's own deadline, a
5//! keep-alive ping}, and feeds whatever arrives back in. Everything that decides
6//! anything is in [`crate::session`].
7//!
8//! The transport is a trait, not a WebSocket. WebSocket is what S2 Connect specifies and
9//! what [`WebSocket`] implements, but S2 itself is transport-agnostic — Victron's Venus
10//! OS carries the same JSON over D-Bus — and keeping the seam here is what stops the
11//! session API quietly growing a socket-shaped assumption.
12//!
13//! ```no_run
14//! use s2_kit::prelude::*;
15//! use s2_kit::io::{Driver, WebSocket};
16//!
17//! # async fn run(details: ResourceManagerDetails) -> Result<(), Box<dyn std::error::Error>> {
18//! let mut rm = RmSession::new(RmConfig::default(), details);
19//! rm.open(Timestamp::now());
20//!
21//! let socket = WebSocket::connect("wss://cem.local/s2", Some("token")).await?;
22//! let mut driver = Driver::new(socket);
23//!
24//! loop {
25//! driver.step(&mut rm).await?;
26//! while let Some(event) = rm.poll_event() {
27//! match event {
28//! RmEvent::Ready { control_type } => { /* send a description */ }
29//! RmEvent::Instruction(i) => { /* i.explanation says what to do */ }
30//! RmEvent::Closed { .. } => return Ok(()),
31//! _ => {}
32//! }
33//! }
34//! }
35//! # }
36//! ```
37
38use alloc::string::{String, ToString};
39use core::future::Future;
40
41use futures_util::{SinkExt, StreamExt};
42use tokio_tungstenite::tungstenite::client::IntoClientRequest;
43use tokio_tungstenite::tungstenite::protocol::Message as WsMessage;
44
45use crate::session::Session;
46use crate::types::{Duration, Timestamp};
47
48/// S2 Connect's keep-alive interval.
49///
50/// `S2C §Keepalive & heartbeat`: "S2 WebSockets implementations **should** send a ping
51/// frame every 30 seconds, and **must not** wait more than 60 seconds between sending
52/// ping frames."
53pub const PING_INTERVAL: Duration = Duration::from_secs(30);
54
55/// Something went wrong at the transport.
56#[derive(Debug, thiserror::Error)]
57#[non_exhaustive]
58pub enum Error {
59 /// The transport failed.
60 #[error("transport error: {0}")]
61 Transport(String),
62 /// The peer closed the connection.
63 #[error("the peer closed the connection")]
64 Closed,
65 /// A frame arrived that is not S2: a binary frame, for instance.
66 #[error("unexpected frame: {0}")]
67 UnexpectedFrame(String),
68}
69
70/// A two-way channel that carries S2 messages as text.
71///
72/// # `recv_text` must be cancel-safe
73///
74/// [`Driver::step`] races `recv_text` against a timer in a `select!`, so the future is
75/// dropped whenever the deadline or the keep-alive wins — which, on a quiet connection, is
76/// every single step. An implementation that has taken a message out of its source and is
77/// holding it in a local when it is dropped **loses that message**, silently, and the
78/// session it was feeding waits for an acknowledgement that was already delivered.
79///
80/// Both transports here are safe because their only await point is a single `next()`/
81/// `recv()` on a stream that is itself cancel-safe and yields the message atomically. An
82/// implementation that buffers, reassembles or decompresses across awaits must hold that
83/// state in `self`, not on the stack.
84pub trait TextTransport {
85 /// Send one message.
86 fn send_text(&mut self, text: String) -> impl Future<Output = Result<(), Error>> + Send;
87 /// Wait for one message. `None` when the peer closed cleanly.
88 ///
89 /// Must be **cancel-safe**: see the trait's own documentation.
90 fn recv_text(&mut self) -> impl Future<Output = Result<Option<String>, Error>> + Send;
91 /// Wait for one frame, reporting the ones that only prove the peer is alive — a pong,
92 /// a ping — as [`Received::Alive`].
93 ///
94 /// The driver's idle limit is measured on this, so a quiet session whose peer still
95 /// answers pings is not mistaken for a dead one. The default reports text only, which
96 /// is correct for a transport with no liveness frames; the WebSocket transports here
97 /// override it. Must be **cancel-safe**, like [`recv_text`](Self::recv_text).
98 fn recv(&mut self) -> impl Future<Output = Result<Option<Received>, Error>> + Send {
99 use futures_util::FutureExt as _;
100 self.recv_text()
101 .map(|frame| frame.map(|text| text.map(Received::Text)))
102 }
103 /// Send a keep-alive, if the transport has one.
104 fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send;
105 /// Close.
106 fn close(&mut self) -> impl Future<Output = ()> + Send;
107}
108
109/// One thing a [`TextTransport`] received.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub enum Received {
112 /// An S2 message.
113 Text(String),
114 /// A frame that carries nothing but proof the peer is there: a ping or a pong.
115 Alive,
116}
117
118/// How long a connection may go without a single frame from the peer — not a message, not
119/// a pong — before the driver treats it as gone.
120///
121/// A half-open TCP connection (a router rebooted, a cable pulled) sends nothing and
122/// reports nothing; without a limit the driver pings into it for ever and reconnection,
123/// which `S2C §Reconnection strategy` says the client "**must**" attempt, never starts.
124/// Three [`PING_INTERVAL`]s: one lost pong is weather, three are a dead link.
125pub const IDLE_LIMIT: Duration = Duration::from_secs(90);
126
127/// A WebSocket, as S2 Connect specifies it.
128pub struct WebSocket<S> {
129 stream: tokio_tungstenite::WebSocketStream<S>,
130}
131
132/// The socket [`WebSocket::connect`] returns.
133///
134/// Long-hand it is `WebSocket<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>`:
135/// three foreign names a struct that stores a driver would otherwise have to write down.
136/// [`tokio_tungstenite`] is re-exported at the crate root for what this alias does not
137/// cover.
138///
139/// ```no_run
140/// struct Gateway {
141/// socket: s2_kit::io::Dialled,
142/// }
143/// # async fn run() -> Result<(), s2_kit::io::Error> {
144/// let gateway = Gateway { socket: s2_kit::io::WebSocket::connect("wss://hub.local/s2", None).await? };
145/// # let _ = gateway;
146/// # Ok(())
147/// # }
148/// ```
149pub type Dialled = WebSocket<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
150
151/// How to open a [`WebSocket`].
152///
153/// The one setting that is not a URL is the size cap, and it is here because it has to be
154/// applied at the handshake: a frame is fully buffered by the WebSocket library before any
155/// of this crate sees it, so a cap enforced afterwards by [`codec`](crate::codec) bounds
156/// what is *parsed* and not what is *held*. Left alone it is
157/// [`DecodeOptions::DEFAULT_MAX_BYTES`](crate::codec::DecodeOptions::DEFAULT_MAX_BYTES) —
158/// the same mebibyte the codec and the session engines use, so the default configuration
159/// is bounded end to end. Raise both together or neither.
160#[derive(Debug, Clone, Default)]
161#[non_exhaustive]
162pub struct WebSocketOptions<'a> {
163 /// The bearer token, which under S2 Connect is the `websocketToken`.
164 pub bearer: Option<&'a str>,
165 /// The largest frame the transport will buffer. `None` is the codec's own default.
166 pub max_message_bytes: Option<usize>,
167 /// How to authenticate the server's certificate. `None` is
168 /// [`TlsPolicy::Web`](crate::connect::tls::TlsPolicy::Web), the public PKI.
169 pub policy: Option<&'a crate::connect::tls::TlsPolicy>,
170 /// Send the bearer over plaintext `ws://`. Off: a bearer is an S2 Connect
171 /// communication token, and `S2C §Encrypted connection` says "S2 **MUST NOT** be sent
172 /// over unencrypted channels". A bare-WebSocket peer with no bearer is unaffected.
173 pub allow_insecure_bearer: bool,
174}
175
176impl<'a> WebSocketOptions<'a> {
177 /// Permit a bearer over `ws://` — for a loopback test and nothing else.
178 #[must_use]
179 pub const fn allow_insecure_bearer(mut self) -> Self {
180 self.allow_insecure_bearer = true;
181 self
182 }
183
184 /// With this bearer token.
185 #[must_use]
186 pub const fn bearer(mut self, bearer: &'a str) -> Self {
187 self.bearer = Some(bearer);
188 self
189 }
190
191 /// Buffer no frame larger than this.
192 #[must_use]
193 pub const fn max_message_bytes(mut self, bytes: usize) -> Self {
194 self.max_message_bytes = Some(bytes);
195 self
196 }
197
198 /// Authenticate the server under this TLS policy.
199 #[must_use]
200 pub const fn policy(mut self, policy: &'a crate::connect::tls::TlsPolicy) -> Self {
201 self.policy = Some(policy);
202 self
203 }
204
205 fn limit(&self) -> usize {
206 self.max_message_bytes
207 .unwrap_or(crate::codec::DecodeOptions::DEFAULT_MAX_BYTES)
208 }
209}
210
211impl Dialled {
212 /// Connect to a URL, with the bearer token S2 Connect's session initiation issued.
213 ///
214 /// `S2C §Authentication`: "the client **must** authenticate itself using the
215 /// commToken in the authorization header of the websocket connection request".
216 ///
217 /// TLS is verified against the **public** PKI, which is right for a WAN endpoint and
218 /// wrong for a LAN one: a `wss://EVSE1038.local/s2` certificate is self-signed, and
219 /// what makes it trustworthy is the CA pinned during pairing. Use
220 /// [`connect_with_policy`](Self::connect_with_policy) there.
221 pub async fn connect(url: &str, bearer: Option<&str>) -> Result<Self, Error> {
222 Self::open(
223 url,
224 &WebSocketOptions {
225 bearer,
226 ..WebSocketOptions::default()
227 },
228 )
229 .await
230 }
231
232 /// Connect with everything spelled out: bearer, size cap and TLS policy.
233 ///
234 /// A `wss://` dial always supplies its own
235 /// [`Connector::Rustls`](tokio_tungstenite::Connector::Rustls), built from
236 /// [`default_provider`](crate::connect::tls::default_provider): the application's
237 /// provider if it installed one, this build's otherwise, and an [`Error::Transport`]
238 /// rather than a panic when there is none. Letting `rustls` resolve its own provider
239 /// panics when no provider feature is on and panics again when two are (D52).
240 pub async fn open(url: &str, options: &WebSocketOptions<'_>) -> Result<Self, Error> {
241 use crate::connect::tls::TlsPolicy;
242
243 // A session must never run unauthenticated: the pairing-only policy exists for the
244 // four pairing requests and nothing else.
245 if let Some(policy) = options.policy
246 && !policy.authenticates()
247 {
248 return Err(Error::Transport(
249 "a session must not run under the pairing-only TLS policy".to_string(),
250 ));
251 }
252 let web = TlsPolicy::Web;
253 let policy = options.policy.unwrap_or(&web);
254 Self::dial(
255 url,
256 options.bearer,
257 policy,
258 options.limit(),
259 options.allow_insecure_bearer,
260 )
261 .await
262 }
263
264 /// Connect under a [`TlsPolicy`](crate::connect::tls::TlsPolicy) — which, after a LAN
265 /// pairing, is the CA that pairing pinned.
266 ///
267 /// This is the one to use in a LAN, with the policy
268 /// `connect::client::Paired::policy` returns. The session initiation that produced the
269 /// communication token ran against the pinned CA; connecting the WebSocket against a
270 /// bundled root list instead would either fail outright — which is what it does — or,
271 /// worse, succeed against a different server.
272 ///
273 /// ```no_run
274 /// # use s2_kit::{connect::tls::TlsPolicy, io::WebSocket};
275 /// # async fn run(policy: &TlsPolicy, url: &str, token: &str)
276 /// # -> Result<(), Box<dyn std::error::Error>> {
277 /// let socket = WebSocket::connect_with_policy(url, Some(token), policy).await?;
278 /// # let _ = socket;
279 /// # Ok(())
280 /// # }
281 /// ```
282 pub async fn connect_with_policy(
283 url: &str,
284 bearer: Option<&str>,
285 policy: &crate::connect::tls::TlsPolicy,
286 ) -> Result<Self, Error> {
287 Self::open(
288 url,
289 &WebSocketOptions {
290 bearer,
291 policy: Some(policy),
292 ..WebSocketOptions::default()
293 },
294 )
295 .await
296 }
297
298 async fn dial(
299 url: &str,
300 bearer: Option<&str>,
301 policy: &crate::connect::tls::TlsPolicy,
302 max_message_bytes: usize,
303 allow_insecure_bearer: bool,
304 ) -> Result<Self, Error> {
305 let mut request = url
306 .into_client_request()
307 .map_err(|e| Error::Transport(e.to_string()))?;
308 // Off the parsed URI rather than off the string: `IntoClientRequest` has already
309 // done the work, and a `ws://` dial should not pay for a certificate verifier it
310 // will never consult.
311 let connector = if request
312 .uri()
313 .scheme_str()
314 .is_some_and(|s| s.eq_ignore_ascii_case("wss"))
315 {
316 let client = crate::connect::tls::TlsClient::new(policy)
317 .map_err(|e| Error::Transport(e.to_string()))?;
318 Some(tokio_tungstenite::Connector::Rustls(client.config()))
319 } else {
320 None
321 };
322 if bearer.is_some() && connector.is_none() && !allow_insecure_bearer {
323 return Err(Error::Transport(
324 "refusing to send a bearer token over plaintext ws:// (S2C §Encrypted connection)"
325 .to_string(),
326 ));
327 }
328 if let Some(token) = bearer {
329 let value = alloc::format!("Bearer {token}")
330 .parse()
331 .map_err(|_| Error::Transport("invalid bearer token".to_string()))?;
332 request.headers_mut().insert("Authorization", value);
333 }
334 // The cap has to be here rather than only in the codec: by the time `decode`
335 // measures a frame, the library has already buffered every byte of it. The
336 // library's own defaults are 64 MiB per message and 16 MiB per frame, which is
337 // sixty-four megabytes an unauthenticated peer can make a gateway hold before
338 // anything of this crate's runs.
339 let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default()
340 .max_message_size(Some(max_message_bytes))
341 .max_frame_size(Some(max_message_bytes));
342 let (stream, _) = tokio_tungstenite::connect_async_tls_with_config(
343 request,
344 Some(config),
345 false,
346 connector,
347 )
348 .await
349 .map_err(|e| Error::Transport(e.to_string()))?;
350 Ok(Self { stream })
351 }
352}
353
354impl<S> WebSocket<S> {
355 /// Wrap an already-established WebSocket — one a server accepted, for instance.
356 pub fn from_stream(stream: tokio_tungstenite::WebSocketStream<S>) -> Self {
357 Self { stream }
358 }
359}
360
361impl<S> TextTransport for WebSocket<S>
362where
363 S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
364{
365 async fn send_text(&mut self, text: String) -> Result<(), Error> {
366 self.stream
367 .send(WsMessage::text(text))
368 .await
369 .map_err(|e| Error::Transport(e.to_string()))
370 }
371
372 #[allow(clippy::match_same_arms)] // grouped by reason; see the comments
373 async fn recv_text(&mut self) -> Result<Option<String>, Error> {
374 loop {
375 match self.recv().await? {
376 None => return Ok(None),
377 Some(Received::Text(text)) => return Ok(Some(text)),
378 Some(Received::Alive) => {}
379 }
380 }
381 }
382
383 async fn recv(&mut self) -> Result<Option<Received>, Error> {
384 loop {
385 match self.stream.next().await {
386 // The stream ended, or the peer said goodbye: the same thing to a session.
387 None | Some(Ok(WsMessage::Close(_))) => return Ok(None),
388 Some(Err(e)) => return Err(Error::Transport(e.to_string())),
389 Some(Ok(WsMessage::Text(text))) => {
390 return Ok(Some(Received::Text(text.to_string())));
391 }
392 // Answering a ping is the library's job; both prove the peer is there.
393 Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => {
394 return Ok(Some(Received::Alive));
395 }
396 Some(Ok(WsMessage::Frame(_))) => {}
397 // A binary frame is not S2.
398 Some(Ok(WsMessage::Binary(_))) => {
399 return Err(Error::UnexpectedFrame("binary".to_string()));
400 }
401 }
402 }
403 }
404
405 async fn ping(&mut self) -> Result<(), Error> {
406 self.stream
407 .send(WsMessage::Ping(tokio_tungstenite::tungstenite::Bytes::new()))
408 .await
409 .map_err(|e| Error::Transport(e.to_string()))
410 }
411
412 async fn close(&mut self) {
413 let _ = self.stream.close(None).await;
414 }
415}
416
417/// Pumps a session over a transport.
418///
419/// One `step` flushes everything the session wants to send, then waits for whichever
420/// comes first: an inbound frame, the session's next deadline, or the keep-alive
421/// interval. The application keeps the loop, and with it the freedom to do anything else
422/// between steps.
423pub struct Driver<T> {
424 transport: T,
425 ping_interval: Duration,
426 /// The clock. Replaceable so that a test can drive a driver too.
427 now: fn() -> Timestamp,
428 /// When a keep-alive was last sent, or `None` before the first step.
429 ///
430 /// The interval is measured from here rather than from the start of each step. A
431 /// driver that restarts the timer every time it goes round the loop never pings a
432 /// connection that is busy — and `S2C §Keepalive & heartbeat` does not say "ping an
433 /// idle connection", it says an implementation "**must not** wait more than 60
434 /// seconds between sending ping frames".
435 last_ping: Option<Timestamp>,
436 /// When the peer was last heard from — any frame at all — or `None` before the first
437 /// step.
438 last_heard: Option<Timestamp>,
439 /// How long silence may last before the transport is treated as closed.
440 idle_limit: Option<Duration>,
441 /// The span every log line of this session is recorded in.
442 ///
443 /// One per driver, so per session: an operator filtering a fleet's logs by a resource
444 /// id set here sees that resource's conversation and nothing else. The state and the
445 /// negotiated version are recorded on it as they change, and each inbound message gets
446 /// a child span keyed by its `message_id` — the key the `ReceptionStatus` carries back.
447 #[cfg(feature = "tracing")]
448 span: tracing::Span,
449 /// The state last recorded on the span, so a transition is logged once.
450 #[cfg(feature = "tracing")]
451 recorded_state: Option<String>,
452}
453
454impl<T: TextTransport> Driver<T> {
455 /// A driver over this transport.
456 pub fn new(transport: T) -> Self {
457 Self {
458 transport,
459 ping_interval: PING_INTERVAL,
460 now: Timestamp::now,
461 last_ping: None,
462 last_heard: None,
463 idle_limit: Some(IDLE_LIMIT),
464 #[cfg(feature = "tracing")]
465 span: tracing::info_span!(
466 "s2.session",
467 state = tracing::field::Empty,
468 version = tracing::field::Empty,
469 ),
470 #[cfg(feature = "tracing")]
471 recorded_state: None,
472 }
473 }
474
475 /// Record this session's log lines in `span` instead of the default `s2.session`.
476 ///
477 /// The way to put a resource id, a peer address or a tenant on every line:
478 ///
479 /// ```ignore
480 /// let driver = Driver::new(socket).with_span(tracing::info_span!(
481 /// "s2.session",
482 /// resource = %resource_id,
483 /// state = tracing::field::Empty,
484 /// version = tracing::field::Empty,
485 /// ));
486 /// ```
487 ///
488 /// Declare `state` and `version` as empty fields to have the driver fill them in;
489 /// `tracing` ignores a record of a field the span did not declare.
490 #[cfg(feature = "tracing")]
491 #[must_use]
492 pub fn with_span(mut self, span: tracing::Span) -> Self {
493 self.span = span;
494 self
495 }
496
497 /// Use a different clock — a virtual one, in a test.
498 #[must_use]
499 pub fn with_clock(mut self, now: fn() -> Timestamp) -> Self {
500 self.now = now;
501 self
502 }
503
504 /// Treat the transport as closed after this long without a frame from the peer, or
505 /// never (`None`). Defaults to [`IDLE_LIMIT`]; keep it a few ping intervals long.
506 #[must_use]
507 pub fn with_idle_limit(mut self, limit: Option<Duration>) -> Self {
508 self.idle_limit = limit;
509 self
510 }
511
512 /// Send pings at a different interval. S2 Connect allows up to sixty seconds.
513 #[must_use]
514 pub fn with_ping_interval(mut self, interval: Duration) -> Self {
515 self.ping_interval = interval;
516 self
517 }
518
519 /// The transport, for a caller that wants to close it itself.
520 pub fn transport_mut(&mut self) -> &mut T {
521 &mut self.transport
522 }
523
524 /// Run one step of a session, whichever role it is.
525 ///
526 /// Flush, wait for the first of {a frame, the session's deadline, the keep-alive
527 /// interval}, feed the result back in, flush again. Everything that decides anything
528 /// is in the session; this function decides only what to wait on.
529 pub async fn step<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
530 #[cfg(feature = "tracing")]
531 {
532 use tracing::Instrument as _;
533 let span = self.span.clone();
534 let result = self.step_inner(session).instrument(span).await;
535 self.record_state(session);
536 result
537 }
538 #[cfg(not(feature = "tracing"))]
539 self.step_inner(session).await
540 }
541
542 /// Record a state transition on the session span, once per transition.
543 #[cfg(feature = "tracing")]
544 fn record_state<S: Session>(&mut self, session: &S) {
545 let state = alloc::format!("{:?}", session.state());
546 if self.recorded_state.as_deref() == Some(state.as_str()) {
547 return;
548 }
549 self.span.record("state", state.as_str());
550 if let Some(version) = session.negotiated_version() {
551 self.span.record("version", version.as_str());
552 }
553 self.span
554 .in_scope(|| tracing::info!(state = %state, "session state"));
555 self.recorded_state = Some(state);
556 }
557
558 async fn step_inner<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
559 self.flush(session).await?;
560 if session.state().is_closed() {
561 self.transport.close().await;
562 return Ok(());
563 }
564 let deadline = session.poll_timeout();
565 match self.wait(deadline).await? {
566 Wake::Text(text) => {
567 let inbound = session.handle_text(&text, (self.now)());
568 // Never the payload: a message body can carry a household's consumption,
569 // and the identifiers are enough to find the exchange in a capture.
570 crate::trace::event!(
571 debug,
572 message_id = ?inbound.message_id,
573 kind = ?inbound.kind,
574 status = ?inbound.status,
575 violations = inbound.report.violations().len(),
576 "received"
577 );
578 // A refusal is the thing an operator actually needs to see, and the rule
579 // identifier is what makes it greppable across a fleet.
580 if !inbound.accepted() {
581 crate::trace::event!(
582 warn,
583 message_id = ?inbound.message_id,
584 kind = ?inbound.kind,
585 status = ?inbound.status,
586 diagnostic = ?inbound.report.diagnostic_label(),
587 "refused an inbound message"
588 );
589 }
590 }
591 Wake::Timeout => {
592 crate::trace::event!(trace, "deadline reached");
593 session.handle_timeout((self.now)());
594 }
595 Wake::Ping => {
596 self.last_ping = Some((self.now)());
597 self.transport.ping().await?;
598 }
599 Wake::Alive => {}
600 Wake::Closed => {
601 crate::trace::event!(info, "the transport closed");
602 session.transport_closed((self.now)());
603 }
604 Wake::Idle => {
605 crate::trace::event!(warn, "nothing heard from the peer within the idle limit");
606 self.transport.close().await;
607 session.transport_closed((self.now)());
608 }
609 }
610 self.flush(session).await
611 }
612
613 /// Send everything the session has queued.
614 async fn flush<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
615 while let Some(out) = session.poll_transmit() {
616 crate::trace::event!(
617 debug,
618 kind = %out.kind.as_str(),
619 message_id = ?out.message_id,
620 bytes = out.text.len(),
621 "sending"
622 );
623 self.transport.send_text(out.text).await?;
624 }
625 Ok(())
626 }
627
628 /// Run a session to completion: steps until it closes.
629 ///
630 /// The application still sees every event, through the callback, but no longer owns
631 /// the loop. For anything that wants to do other work between steps, use
632 /// [`Self::step`].
633 pub async fn run<S, F>(&mut self, session: &mut S, mut on_event: F) -> Result<(), Error>
634 where
635 S: Session,
636 F: FnMut(S::Event, &mut S),
637 {
638 while !session.state().is_closed() {
639 self.step(session).await?;
640 while let Some(event) = session.poll_event() {
641 on_event(event, session);
642 }
643 }
644 self.flush(session).await?;
645 self.transport.close().await;
646 Ok(())
647 }
648
649 async fn wait(&mut self, deadline: Option<Timestamp>) -> Result<Wake, Error> {
650 let now = (self.now)();
651 // A session with no deadline still has to be woken for the keep-alive, so
652 // "never" is expressed as a span no ping interval will ever exceed rather than
653 // as an infinite sleep.
654 let until_deadline = deadline.map_or(Duration::MAX, |at| at.saturating_duration_since(now));
655 let until_ping = match self.last_ping {
656 // The first step starts the clock rather than pinging immediately: a socket
657 // that has just been opened does not need proof that it is alive.
658 None => {
659 self.last_ping = Some(now);
660 self.ping_interval
661 }
662 Some(last) => self
663 .ping_interval
664 .checked_sub(now.saturating_duration_since(last))
665 .unwrap_or(Duration::ZERO),
666 };
667
668 let until_idle = match (self.idle_limit, self.last_heard) {
669 (None, _) => Duration::MAX,
670 // As with the ping, the first step starts the clock.
671 (Some(limit), None) => {
672 self.last_heard = Some(now);
673 limit
674 }
675 (Some(limit), Some(heard)) => limit
676 .checked_sub(now.saturating_duration_since(heard))
677 .unwrap_or(Duration::ZERO),
678 };
679
680 let (sleep_for, wake) = [
681 (until_deadline, Wake::Timeout),
682 (until_ping, Wake::Ping),
683 (until_idle, Wake::Idle),
684 ]
685 .into_iter()
686 .min_by_key(|(after, _)| *after)
687 .unwrap_or((until_deadline, Wake::Timeout));
688
689 tokio::select! {
690 frame = self.transport.recv() => {
691 let frame = frame?;
692 if frame.is_some() {
693 self.last_heard = Some((self.now)());
694 }
695 Ok(match frame {
696 Some(Received::Text(text)) => Wake::Text(text),
697 Some(Received::Alive) => Wake::Alive,
698 None => Wake::Closed,
699 })
700 },
701 () = tokio::time::sleep(core::time::Duration::from(sleep_for)) => Ok(wake),
702 }
703 }
704}
705
706enum Wake {
707 Text(String),
708 Timeout,
709 Ping,
710 Alive,
711 Closed,
712 Idle,
713}
714
715#[cfg(test)]
716mod tests {
717 use super::*;
718 use crate::session::{RmConfig, RmSession};
719 use alloc::collections::VecDeque;
720 use alloc::vec::Vec;
721
722 /// A transport that hands back a script and records what was written.
723 struct Scripted {
724 inbound: VecDeque<String>,
725 outbound: Vec<String>,
726 pings: usize,
727 }
728
729 impl TextTransport for Scripted {
730 async fn send_text(&mut self, text: String) -> Result<(), Error> {
731 // A yield point, so the mock behaves like a transport that can be
732 // interleaved rather than one that always completes instantly.
733 tokio::task::yield_now().await;
734 self.outbound.push(text);
735 Ok(())
736 }
737 async fn recv_text(&mut self) -> Result<Option<String>, Error> {
738 if let Some(text) = self.inbound.pop_front() {
739 return Ok(Some(text));
740 }
741 // Nothing more scripted: block for ever, so the timer wins the select.
742 core::future::pending::<()>().await;
743 unreachable!()
744 }
745 async fn ping(&mut self) -> Result<(), Error> {
746 tokio::task::yield_now().await;
747 self.pings += 1;
748 Ok(())
749 }
750 async fn close(&mut self) {
751 tokio::task::yield_now().await;
752 }
753 }
754
755 fn clock() -> Timestamp {
756 "2024-01-01T12:00:00Z"
757 .parse()
758 .unwrap_or(Timestamp::UNIX_EPOCH)
759 }
760
761 #[tokio::test]
762 async fn a_step_flushes_the_outbox_and_feeds_back_what_arrives() {
763 let details = crate::testing::battery_details();
764 let mut rm = RmSession::new(RmConfig::default(), details);
765 rm.open(clock());
766
767 let transport = Scripted {
768 inbound: VecDeque::from([
769 r#"{"message_type":"Handshake","message_id":"c1","role":"CEM","supported_protocol_versions":["1.0.0"]}"#.to_string(),
770 ]),
771 outbound: Vec::new(),
772 pings: 0,
773 };
774 let mut driver = Driver::new(transport).with_clock(clock);
775
776 driver.step(&mut rm).await.unwrap();
777
778 let written = &driver.transport_mut().outbound;
779 assert!(written[0].contains(r#""message_type":"Handshake""#));
780 // And the CEM's handshake was answered.
781 assert!(written.iter().any(|m| m.contains("ReceptionStatus")));
782 }
783
784 #[tokio::test(start_paused = true)]
785 async fn a_link_that_goes_silent_is_closed_rather_than_pinged_for_ever() {
786 // A half-open TCP connection answers nothing — not a message, not a pong. Without
787 // a limit the driver pings into it indefinitely and reconnection never starts.
788 let details = crate::testing::battery_details();
789 let mut rm = RmSession::new(RmConfig::default(), details);
790 rm.open(virtual_clock());
791 let transport = Scripted {
792 inbound: VecDeque::new(),
793 outbound: Vec::new(),
794 pings: 0,
795 };
796 let mut driver = Driver::new(transport)
797 .with_clock(virtual_clock)
798 .with_ping_interval(Duration::from_secs(1))
799 .with_idle_limit(Some(Duration::from_secs(3)));
800 for _ in 0..64 {
801 driver.step(&mut rm).await.unwrap();
802 if rm.state().is_closed() {
803 break;
804 }
805 }
806 assert!(
807 rm.state().is_closed(),
808 "silence past the limit must end the session"
809 );
810 assert!(driver.transport_mut().pings >= 2, "it was pinged first");
811 }
812
813 /// A transport that answers every `recv_text` after `gap`, for ever.
814 ///
815 /// A connection that is *busy*, as opposed to the silent one the other test uses.
816 struct Chatty {
817 gap: core::time::Duration,
818 pings: usize,
819 }
820
821 impl TextTransport for Chatty {
822 // The trait is async; a mock that drops what it is given is not.
823 #[allow(clippy::unused_async_trait_impl)]
824 async fn send_text(&mut self, _text: String) -> Result<(), Error> {
825 Ok(())
826 }
827 async fn recv_text(&mut self) -> Result<Option<String>, Error> {
828 tokio::time::sleep(self.gap).await;
829 Ok(Some(
830 r#"{"message_type":"PowerMeasurement","message_id":"c1",
831 "measurement_timestamp":"2024-01-01T12:00:00Z",
832 "values":[{"commodity_quantity":"ELECTRIC.POWER.L1","value":1.0}]}"#
833 .to_string(),
834 ))
835 }
836 #[allow(clippy::unused_async_trait_impl)]
837 async fn ping(&mut self) -> Result<(), Error> {
838 self.pings += 1;
839 Ok(())
840 }
841 #[allow(clippy::unused_async_trait_impl)]
842 async fn close(&mut self) {}
843 }
844
845 /// A clock reading tokio's virtual time, so the driver and the runtime agree.
846 fn virtual_clock() -> Timestamp {
847 use std::sync::OnceLock;
848 static START: OnceLock<tokio::time::Instant> = OnceLock::new();
849 let start = *START.get_or_init(tokio::time::Instant::now);
850 let elapsed = tokio::time::Instant::now().saturating_duration_since(start);
851 Timestamp::from_unix(1_700_000_000, 0)
852 .checked_add(Duration::from_millis(
853 u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX),
854 ))
855 .unwrap_or(Timestamp::UNIX_EPOCH)
856 }
857
858 #[tokio::test(start_paused = true)]
859 async fn a_busy_connection_still_gets_a_keep_alive() {
860 // The bug this pins: an interval measured from the start of each step never
861 // elapses on a connection that has traffic, so a driver doing its job stops
862 // pinging — and `S2C §Keepalive & heartbeat` says an implementation "must not
863 // wait more than 60 seconds between sending ping frames", not "unless it is
864 // busy". A frame every hundred milliseconds against a one-second interval is a
865 // connection that is never idle for a whole interval and must be pinged anyway.
866 let details = crate::testing::battery_details();
867 let mut rm = RmSession::new(RmConfig::default(), details);
868 rm.open(virtual_clock());
869
870 let transport = Chatty {
871 gap: core::time::Duration::from_millis(100),
872 pings: 0,
873 };
874 let mut driver = Driver::new(transport)
875 .with_clock(virtual_clock)
876 .with_ping_interval(Duration::from_secs(1));
877
878 // Thirty-odd steps is a little over three seconds of traffic.
879 for _ in 0..34 {
880 driver.step(&mut rm).await.unwrap();
881 }
882 assert!(
883 driver.transport_mut().pings >= 2,
884 "expected the keep-alive to fire about once a second, got {}",
885 driver.transport_mut().pings
886 );
887 }
888
889 #[tokio::test(start_paused = true)]
890 async fn a_quiet_connection_gets_a_keep_alive() {
891 let details = crate::testing::battery_details();
892 let mut rm = RmSession::new(RmConfig::default(), details);
893 rm.open(clock());
894 let transport = Scripted {
895 inbound: VecDeque::new(),
896 outbound: Vec::new(),
897 pings: 0,
898 };
899 let mut driver = Driver::new(transport)
900 .with_clock(clock)
901 .with_ping_interval(Duration::from_secs(1));
902 // The handshake is waiting for an acknowledgement with a five-second deadline,
903 // so the one-second ping interval wins.
904 driver.step(&mut rm).await.unwrap();
905 assert_eq!(driver.transport_mut().pings, 1);
906 }
907}