Skip to main content

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.
71pub trait TextTransport {
72    /// Send one message.
73    fn send_text(&mut self, text: String) -> impl Future<Output = Result<(), Error>> + Send;
74    /// Wait for one message. `None` when the peer closed cleanly.
75    fn recv_text(&mut self) -> impl Future<Output = Result<Option<String>, Error>> + Send;
76    /// Send a keep-alive, if the transport has one.
77    fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send;
78    /// Close.
79    fn close(&mut self) -> impl Future<Output = ()> + Send;
80}
81
82/// A WebSocket, as S2 Connect specifies it.
83pub struct WebSocket<S> {
84    stream: tokio_tungstenite::WebSocketStream<S>,
85}
86
87impl WebSocket<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>> {
88    /// Connect to a URL, with the bearer token S2 Connect's session initiation issued.
89    ///
90    /// `S2C §Authentication`: "the client **must** authenticate itself using the
91    /// commToken in the authorization header of the websocket connection request".
92    ///
93    /// TLS is verified against the **public** PKI, which is right for a WAN endpoint and
94    /// wrong for a LAN one: a `wss://EVSE1038.local/s2` certificate is self-signed, and
95    /// what makes it trustworthy is the CA pinned during pairing. Use
96    /// [`connect_with_policy`](Self::connect_with_policy) there.
97    pub async fn connect(url: &str, bearer: Option<&str>) -> Result<Self, Error> {
98        Self::dial(url, bearer, None).await
99    }
100
101    /// Connect under a [`TlsPolicy`](crate::connect::tls::TlsPolicy) — which, after a LAN
102    /// pairing, is the CA that pairing pinned.
103    ///
104    /// This is the companion of [`connect::client::Session`](crate::connect::client) and
105    /// the one to use in a LAN. The session initiation that produced the communication
106    /// token ran against the pinned CA; connecting the WebSocket against a bundled root
107    /// list instead would either fail outright — which is what it does — or, worse,
108    /// succeed against a different server.
109    ///
110    /// ```no_run
111    /// # use s2_kit::io::WebSocket;
112    /// # async fn run(paired: s2_kit::connect::client::Paired, url: &str, token: &str)
113    /// # -> Result<(), Box<dyn std::error::Error>> {
114    /// let socket = WebSocket::connect_with_policy(url, Some(token), &paired.policy()).await?;
115    /// # let _ = socket;
116    /// # Ok(())
117    /// # }
118    /// ```
119    #[cfg(feature = "connect-client")]
120    #[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
121    pub async fn connect_with_policy(
122        url: &str,
123        bearer: Option<&str>,
124        policy: &crate::connect::tls::TlsPolicy,
125    ) -> Result<Self, Error> {
126        // A session must never run unauthenticated: the pairing-only policy exists for
127        // the four pairing requests and nothing else.
128        if !policy.authenticates() {
129            return Err(Error::Transport(
130                "a session must not run under the pairing-only TLS policy".to_string(),
131            ));
132        }
133        let client = crate::connect::tls::TlsClient::new(policy)
134            .map_err(|e| Error::Transport(e.to_string()))?;
135        let connector = tokio_tungstenite::Connector::Rustls(client.config());
136        Self::dial(url, bearer, Some(connector)).await
137    }
138
139    async fn dial(
140        url: &str,
141        bearer: Option<&str>,
142        connector: Option<tokio_tungstenite::Connector>,
143    ) -> Result<Self, Error> {
144        let mut request = url
145            .into_client_request()
146            .map_err(|e| Error::Transport(e.to_string()))?;
147        if let Some(token) = bearer {
148            let value = alloc::format!("Bearer {token}")
149                .parse()
150                .map_err(|_| Error::Transport("invalid bearer token".to_string()))?;
151            request.headers_mut().insert("Authorization", value);
152        }
153        let (stream, _) =
154            tokio_tungstenite::connect_async_tls_with_config(request, None, false, connector)
155                .await
156                .map_err(|e| Error::Transport(e.to_string()))?;
157        Ok(Self { stream })
158    }
159}
160
161impl<S> WebSocket<S> {
162    /// Wrap an already-established WebSocket — one a server accepted, for instance.
163    pub fn from_stream(stream: tokio_tungstenite::WebSocketStream<S>) -> Self {
164        Self { stream }
165    }
166}
167
168impl<S> TextTransport for WebSocket<S>
169where
170    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
171{
172    async fn send_text(&mut self, text: String) -> Result<(), Error> {
173        self.stream
174            .send(WsMessage::text(text))
175            .await
176            .map_err(|e| Error::Transport(e.to_string()))
177    }
178
179    #[allow(clippy::match_same_arms)] // grouped by reason; see the comments
180    async fn recv_text(&mut self) -> Result<Option<String>, Error> {
181        loop {
182            match self.stream.next().await {
183                None => return Ok(None),
184                Some(Err(e)) => return Err(Error::Transport(e.to_string())),
185                Some(Ok(WsMessage::Text(text))) => return Ok(Some(text.to_string())),
186                Some(Ok(WsMessage::Close(_))) => return Ok(None),
187                // Ping and pong are handled by the library; a binary frame is not S2.
188                Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_) | WsMessage::Frame(_))) => {}
189                Some(Ok(WsMessage::Binary(_))) => {
190                    return Err(Error::UnexpectedFrame("binary".to_string()));
191                }
192            }
193        }
194    }
195
196    async fn ping(&mut self) -> Result<(), Error> {
197        self.stream
198            .send(WsMessage::Ping(tokio_tungstenite::tungstenite::Bytes::new()))
199            .await
200            .map_err(|e| Error::Transport(e.to_string()))
201    }
202
203    async fn close(&mut self) {
204        let _ = self.stream.close(None).await;
205    }
206}
207
208/// Pumps a session over a transport.
209///
210/// One `step` flushes everything the session wants to send, then waits for whichever
211/// comes first: an inbound frame, the session's next deadline, or the keep-alive
212/// interval. The application keeps the loop, and with it the freedom to do anything else
213/// between steps.
214pub struct Driver<T> {
215    transport: T,
216    ping_interval: Duration,
217    /// The clock. Replaceable so that a test can drive a driver too.
218    now: fn() -> Timestamp,
219    /// When a keep-alive was last sent, or `None` before the first step.
220    ///
221    /// The interval is measured from here rather than from the start of each step. A
222    /// driver that restarts the timer every time it goes round the loop never pings a
223    /// connection that is busy — and `S2C §Keepalive & heartbeat` does not say "ping an
224    /// idle connection", it says an implementation "**must not** wait more than 60
225    /// seconds between sending ping frames".
226    last_ping: Option<Timestamp>,
227}
228
229impl<T: TextTransport> Driver<T> {
230    /// A driver over this transport.
231    pub fn new(transport: T) -> Self {
232        Self {
233            transport,
234            ping_interval: PING_INTERVAL,
235            now: Timestamp::now,
236            last_ping: None,
237        }
238    }
239
240    /// Use a different clock — a virtual one, in a test.
241    #[must_use]
242    pub fn with_clock(mut self, now: fn() -> Timestamp) -> Self {
243        self.now = now;
244        self
245    }
246
247    /// Send pings at a different interval. S2 Connect allows up to sixty seconds.
248    #[must_use]
249    pub fn with_ping_interval(mut self, interval: Duration) -> Self {
250        self.ping_interval = interval;
251        self
252    }
253
254    /// The transport, for a caller that wants to close it itself.
255    pub fn transport_mut(&mut self) -> &mut T {
256        &mut self.transport
257    }
258
259    /// Run one step of a session, whichever role it is.
260    ///
261    /// Flush, wait for the first of {a frame, the session's deadline, the keep-alive
262    /// interval}, feed the result back in, flush again. Everything that decides anything
263    /// is in the session; this function decides only what to wait on.
264    pub async fn step<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
265        self.flush(session).await?;
266        if session.state().is_closed() {
267            self.transport.close().await;
268            return Ok(());
269        }
270        let deadline = session.poll_timeout();
271        match self.wait(deadline).await? {
272            Wake::Text(text) => {
273                let inbound = session.handle_text(&text, (self.now)());
274                crate::trace::event!(
275                    debug,
276                    kind = ?inbound.kind,
277                    status = ?inbound.status,
278                    violations = inbound.report.violations().len(),
279                    "received"
280                );
281                // A refusal is the thing an operator actually needs to see, and the rule
282                // identifier is what makes it greppable across a fleet.
283                if inbound.report.has_errors() {
284                    crate::trace::event!(
285                        warn,
286                        kind = ?inbound.kind,
287                        diagnostic = ?inbound.report.diagnostic_label(),
288                        "refused an inbound message"
289                    );
290                }
291            }
292            Wake::Timeout => {
293                crate::trace::event!(trace, "deadline reached");
294                session.handle_timeout((self.now)());
295            }
296            Wake::Ping => {
297                self.last_ping = Some((self.now)());
298                self.transport.ping().await?;
299            }
300            Wake::Closed => {
301                crate::trace::event!(info, "the transport closed");
302                session.transport_closed((self.now)());
303            }
304        }
305        self.flush(session).await
306    }
307
308    /// Send everything the session has queued.
309    async fn flush<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
310        while let Some(out) = session.poll_transmit() {
311            crate::trace::event!(
312                debug,
313                kind = %out.kind.as_str(),
314                message_id = ?out.message_id,
315                bytes = out.text.len(),
316                "sending"
317            );
318            self.transport.send_text(out.text).await?;
319        }
320        Ok(())
321    }
322
323    /// Run a session to completion: steps until it closes.
324    ///
325    /// The application still sees every event, through the callback, but no longer owns
326    /// the loop. For anything that wants to do other work between steps, use
327    /// [`Self::step`].
328    pub async fn run<S, F>(&mut self, session: &mut S, mut on_event: F) -> Result<(), Error>
329    where
330        S: Session,
331        F: FnMut(S::Event, &mut S),
332    {
333        while !session.state().is_closed() {
334            self.step(session).await?;
335            while let Some(event) = session.poll_event() {
336                on_event(event, session);
337            }
338        }
339        self.flush(session).await?;
340        self.transport.close().await;
341        Ok(())
342    }
343
344    async fn wait(&mut self, deadline: Option<Timestamp>) -> Result<Wake, Error> {
345        let now = (self.now)();
346        // A session with no deadline still has to be woken for the keep-alive, so
347        // "never" is expressed as a span no ping interval will ever exceed rather than
348        // as an infinite sleep.
349        let until_deadline = deadline.map_or(Duration::MAX, |at| at.saturating_duration_since(now));
350        let until_ping = match self.last_ping {
351            // The first step starts the clock rather than pinging immediately: a socket
352            // that has just been opened does not need proof that it is alive.
353            None => {
354                self.last_ping = Some(now);
355                self.ping_interval
356            }
357            Some(last) => self
358                .ping_interval
359                .checked_sub(now.saturating_duration_since(last))
360                .unwrap_or(Duration::ZERO),
361        };
362
363        let (sleep_for, wake) = if until_deadline <= until_ping {
364            (until_deadline, Wake::Timeout)
365        } else {
366            (until_ping, Wake::Ping)
367        };
368
369        tokio::select! {
370            frame = self.transport.recv_text() => match frame? {
371                Some(text) => Ok(Wake::Text(text)),
372                None => Ok(Wake::Closed),
373            },
374            () = tokio::time::sleep(core::time::Duration::from(sleep_for)) => Ok(wake),
375        }
376    }
377}
378
379enum Wake {
380    Text(String),
381    Timeout,
382    Ping,
383    Closed,
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crate::session::{RmConfig, RmSession};
390    use alloc::collections::VecDeque;
391    use alloc::vec::Vec;
392
393    /// A transport that hands back a script and records what was written.
394    struct Scripted {
395        inbound: VecDeque<String>,
396        outbound: Vec<String>,
397        pings: usize,
398    }
399
400    impl TextTransport for Scripted {
401        async fn send_text(&mut self, text: String) -> Result<(), Error> {
402            // A yield point, so the mock behaves like a transport that can be
403            // interleaved rather than one that always completes instantly.
404            tokio::task::yield_now().await;
405            self.outbound.push(text);
406            Ok(())
407        }
408        async fn recv_text(&mut self) -> Result<Option<String>, Error> {
409            if let Some(text) = self.inbound.pop_front() {
410                return Ok(Some(text));
411            }
412            // Nothing more scripted: block for ever, so the timer wins the select.
413            core::future::pending::<()>().await;
414            unreachable!()
415        }
416        async fn ping(&mut self) -> Result<(), Error> {
417            tokio::task::yield_now().await;
418            self.pings += 1;
419            Ok(())
420        }
421        async fn close(&mut self) {
422            tokio::task::yield_now().await;
423        }
424    }
425
426    fn clock() -> Timestamp {
427        "2024-01-01T12:00:00Z"
428            .parse()
429            .unwrap_or(Timestamp::UNIX_EPOCH)
430    }
431
432    #[tokio::test]
433    async fn a_step_flushes_the_outbox_and_feeds_back_what_arrives() {
434        let details = crate::testing::battery_details();
435        let mut rm = RmSession::new(RmConfig::default(), details);
436        rm.open(clock());
437
438        let transport = Scripted {
439            inbound: VecDeque::from([
440                r#"{"message_type":"Handshake","message_id":"c1","role":"CEM","supported_protocol_versions":["1.0.0"]}"#.to_string(),
441            ]),
442            outbound: Vec::new(),
443            pings: 0,
444        };
445        let mut driver = Driver::new(transport).with_clock(clock);
446
447        driver.step(&mut rm).await.unwrap();
448
449        let written = &driver.transport_mut().outbound;
450        assert!(written[0].contains(r#""message_type":"Handshake""#));
451        // And the CEM's handshake was answered.
452        assert!(written.iter().any(|m| m.contains("ReceptionStatus")));
453    }
454
455    /// A transport that answers every `recv_text` after `gap`, for ever.
456    ///
457    /// A connection that is *busy*, as opposed to the silent one the other test uses.
458    struct Chatty {
459        gap: core::time::Duration,
460        pings: usize,
461    }
462
463    impl TextTransport for Chatty {
464        // The trait is async; a mock that drops what it is given is not.
465        #[allow(clippy::unused_async_trait_impl)]
466        async fn send_text(&mut self, _text: String) -> Result<(), Error> {
467            Ok(())
468        }
469        async fn recv_text(&mut self) -> Result<Option<String>, Error> {
470            tokio::time::sleep(self.gap).await;
471            Ok(Some(
472                r#"{"message_type":"PowerMeasurement","message_id":"c1",
473                    "measurement_timestamp":"2024-01-01T12:00:00Z",
474                    "values":[{"commodity_quantity":"ELECTRIC.POWER.L1","value":1.0}]}"#
475                    .to_string(),
476            ))
477        }
478        #[allow(clippy::unused_async_trait_impl)]
479        async fn ping(&mut self) -> Result<(), Error> {
480            self.pings += 1;
481            Ok(())
482        }
483        #[allow(clippy::unused_async_trait_impl)]
484        async fn close(&mut self) {}
485    }
486
487    /// A clock reading tokio's virtual time, so the driver and the runtime agree.
488    fn virtual_clock() -> Timestamp {
489        use std::sync::OnceLock;
490        static START: OnceLock<tokio::time::Instant> = OnceLock::new();
491        let start = *START.get_or_init(tokio::time::Instant::now);
492        let elapsed = tokio::time::Instant::now().saturating_duration_since(start);
493        Timestamp::from_unix(1_700_000_000, 0)
494            .checked_add(Duration::from_millis(
495                u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX),
496            ))
497            .unwrap_or(Timestamp::UNIX_EPOCH)
498    }
499
500    #[tokio::test(start_paused = true)]
501    async fn a_busy_connection_still_gets_a_keep_alive() {
502        // The bug this pins: an interval measured from the start of each step never
503        // elapses on a connection that has traffic, so a driver doing its job stops
504        // pinging — and `S2C §Keepalive & heartbeat` says an implementation "must not
505        // wait more than 60 seconds between sending ping frames", not "unless it is
506        // busy". A frame every hundred milliseconds against a one-second interval is a
507        // connection that is never idle for a whole interval and must be pinged anyway.
508        let details = crate::testing::battery_details();
509        let mut rm = RmSession::new(RmConfig::default(), details);
510        rm.open(virtual_clock());
511
512        let transport = Chatty {
513            gap: core::time::Duration::from_millis(100),
514            pings: 0,
515        };
516        let mut driver = Driver::new(transport)
517            .with_clock(virtual_clock)
518            .with_ping_interval(Duration::from_secs(1));
519
520        // Thirty-odd steps is a little over three seconds of traffic.
521        for _ in 0..34 {
522            driver.step(&mut rm).await.unwrap();
523        }
524        assert!(
525            driver.transport_mut().pings >= 2,
526            "expected the keep-alive to fire about once a second, got {}",
527            driver.transport_mut().pings
528        );
529    }
530
531    #[tokio::test(start_paused = true)]
532    async fn a_quiet_connection_gets_a_keep_alive() {
533        let details = crate::testing::battery_details();
534        let mut rm = RmSession::new(RmConfig::default(), details);
535        rm.open(clock());
536        let transport = Scripted {
537            inbound: VecDeque::new(),
538            outbound: Vec::new(),
539            pings: 0,
540        };
541        let mut driver = Driver::new(transport)
542            .with_clock(clock)
543            .with_ping_interval(Duration::from_secs(1));
544        // The handshake is waiting for an acknowledgement with a five-second deadline,
545        // so the one-second ping interval wins.
546        driver.step(&mut rm).await.unwrap();
547        assert_eq!(driver.transport_mut().pings, 1);
548    }
549}