s2-kit 0.4.0

The S2 energy flexibility standard (EN 50491-12-2) in Rust: the S2 JSON data model, a semantic validator, sans-IO Resource Manager and Customer Energy Manager session engines, and S2 Connect
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Driving a session over a real transport.
//!
//! The engines are sans-I/O, so this module is thin on purpose: it flushes what a
//! session wants to send, waits for the next of {a frame, the session's own deadline, a
//! keep-alive ping}, and feeds whatever arrives back in. Everything that decides
//! anything is in [`crate::session`].
//!
//! The transport is a trait, not a WebSocket. WebSocket is what S2 Connect specifies and
//! what [`WebSocket`] implements, but S2 itself is transport-agnostic — Victron's Venus
//! OS carries the same JSON over D-Bus — and keeping the seam here is what stops the
//! session API quietly growing a socket-shaped assumption.
//!
//! ```no_run
//! use s2_kit::prelude::*;
//! use s2_kit::io::{Driver, WebSocket};
//!
//! # async fn run(details: ResourceManagerDetails) -> Result<(), Box<dyn std::error::Error>> {
//! let mut rm = RmSession::new(RmConfig::default(), details);
//! rm.open(Timestamp::now());
//!
//! let socket = WebSocket::connect("wss://cem.local/s2", Some("token")).await?;
//! let mut driver = Driver::new(socket);
//!
//! loop {
//!     driver.step(&mut rm).await?;
//!     while let Some(event) = rm.poll_event() {
//!         match event {
//!             RmEvent::Ready { control_type } => { /* send a description */ }
//!             RmEvent::Instruction(i) => { /* i.explanation says what to do */ }
//!             RmEvent::Closed { .. } => return Ok(()),
//!             _ => {}
//!         }
//!     }
//! }
//! # }
//! ```

use alloc::string::{String, ToString};
use core::future::Future;

use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::protocol::Message as WsMessage;

use crate::session::Session;
use crate::types::{Duration, Timestamp};

/// S2 Connect's keep-alive interval.
///
/// `S2C §Keepalive & heartbeat`: "S2 WebSockets implementations **should** send a ping
/// frame every 30 seconds, and **must not** wait more than 60 seconds between sending
/// ping frames."
pub const PING_INTERVAL: Duration = Duration::from_secs(30);

/// Something went wrong at the transport.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The transport failed.
    #[error("transport error: {0}")]
    Transport(String),
    /// The peer closed the connection.
    #[error("the peer closed the connection")]
    Closed,
    /// A frame arrived that is not S2: a binary frame, for instance.
    #[error("unexpected frame: {0}")]
    UnexpectedFrame(String),
}

/// A two-way channel that carries S2 messages as text.
///
/// # `recv_text` must be cancel-safe
///
/// [`Driver::step`] races `recv_text` against a timer in a `select!`, so the future is
/// dropped whenever the deadline or the keep-alive wins — which, on a quiet connection, is
/// every single step. An implementation that has taken a message out of its source and is
/// holding it in a local when it is dropped **loses that message**, silently, and the
/// session it was feeding waits for an acknowledgement that was already delivered.
///
/// Both transports here are safe because their only await point is a single `next()`/
/// `recv()` on a stream that is itself cancel-safe and yields the message atomically. An
/// implementation that buffers, reassembles or decompresses across awaits must hold that
/// state in `self`, not on the stack.
pub trait TextTransport {
    /// Send one message.
    fn send_text(&mut self, text: String) -> impl Future<Output = Result<(), Error>> + Send;
    /// Wait for one message. `None` when the peer closed cleanly.
    ///
    /// Must be **cancel-safe**: see the trait's own documentation.
    fn recv_text(&mut self) -> impl Future<Output = Result<Option<String>, Error>> + Send;
    /// Wait for one frame, reporting the ones that only prove the peer is alive — a pong,
    /// a ping — as [`Received::Alive`].
    ///
    /// The driver's idle limit is measured on this, so a quiet session whose peer still
    /// answers pings is not mistaken for a dead one. The default reports text only, which
    /// is correct for a transport with no liveness frames; the WebSocket transports here
    /// override it. Must be **cancel-safe**, like [`recv_text`](Self::recv_text).
    fn recv(&mut self) -> impl Future<Output = Result<Option<Received>, Error>> + Send {
        use futures_util::FutureExt as _;
        self.recv_text()
            .map(|frame| frame.map(|text| text.map(Received::Text)))
    }
    /// Send a keep-alive, if the transport has one.
    fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send;
    /// Close.
    fn close(&mut self) -> impl Future<Output = ()> + Send;
}

/// One thing a [`TextTransport`] received.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Received {
    /// An S2 message.
    Text(String),
    /// A frame that carries nothing but proof the peer is there: a ping or a pong.
    Alive,
}

/// How long a connection may go without a single frame from the peer — not a message, not
/// a pong — before the driver treats it as gone.
///
/// A half-open TCP connection (a router rebooted, a cable pulled) sends nothing and
/// reports nothing; without a limit the driver pings into it for ever and reconnection,
/// which `S2C §Reconnection strategy` says the client "**must**" attempt, never starts.
/// Three [`PING_INTERVAL`]s: one lost pong is weather, three are a dead link.
pub const IDLE_LIMIT: Duration = Duration::from_secs(90);

/// A WebSocket, as S2 Connect specifies it.
pub struct WebSocket<S> {
    stream: tokio_tungstenite::WebSocketStream<S>,
}

/// The socket [`WebSocket::connect`] returns.
///
/// Long-hand it is `WebSocket<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>`:
/// three foreign names a struct that stores a driver would otherwise have to write down.
/// [`tokio_tungstenite`] is re-exported at the crate root for what this alias does not
/// cover.
///
/// ```no_run
/// struct Gateway {
///     socket: s2_kit::io::Dialled,
/// }
/// # async fn run() -> Result<(), s2_kit::io::Error> {
/// let gateway = Gateway { socket: s2_kit::io::WebSocket::connect("wss://hub.local/s2", None).await? };
/// # let _ = gateway;
/// # Ok(())
/// # }
/// ```
pub type Dialled = WebSocket<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;

/// How to open a [`WebSocket`].
///
/// The one setting that is not a URL is the size cap, and it is here because it has to be
/// applied at the handshake: a frame is fully buffered by the WebSocket library before any
/// of this crate sees it, so a cap enforced afterwards by [`codec`](crate::codec) bounds
/// what is *parsed* and not what is *held*. Left alone it is
/// [`DecodeOptions::DEFAULT_MAX_BYTES`](crate::codec::DecodeOptions::DEFAULT_MAX_BYTES) —
/// the same mebibyte the codec and the session engines use, so the default configuration
/// is bounded end to end. Raise both together or neither.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct WebSocketOptions<'a> {
    /// The bearer token, which under S2 Connect is the `websocketToken`.
    pub bearer: Option<&'a str>,
    /// The largest frame the transport will buffer. `None` is the codec's own default.
    pub max_message_bytes: Option<usize>,
    /// How to authenticate the server's certificate. `None` is
    /// [`TlsPolicy::Web`](crate::connect::tls::TlsPolicy::Web), the public PKI.
    pub policy: Option<&'a crate::connect::tls::TlsPolicy>,
    /// Send the bearer over plaintext `ws://`. Off: a bearer is an S2 Connect
    /// communication token, and `S2C §Encrypted connection` says "S2 **MUST NOT** be sent
    /// over unencrypted channels". A bare-WebSocket peer with no bearer is unaffected.
    pub allow_insecure_bearer: bool,
}

impl<'a> WebSocketOptions<'a> {
    /// Permit a bearer over `ws://` — for a loopback test and nothing else.
    #[must_use]
    pub const fn allow_insecure_bearer(mut self) -> Self {
        self.allow_insecure_bearer = true;
        self
    }

    /// With this bearer token.
    #[must_use]
    pub const fn bearer(mut self, bearer: &'a str) -> Self {
        self.bearer = Some(bearer);
        self
    }

    /// Buffer no frame larger than this.
    #[must_use]
    pub const fn max_message_bytes(mut self, bytes: usize) -> Self {
        self.max_message_bytes = Some(bytes);
        self
    }

    /// Authenticate the server under this TLS policy.
    #[must_use]
    pub const fn policy(mut self, policy: &'a crate::connect::tls::TlsPolicy) -> Self {
        self.policy = Some(policy);
        self
    }

    fn limit(&self) -> usize {
        self.max_message_bytes
            .unwrap_or(crate::codec::DecodeOptions::DEFAULT_MAX_BYTES)
    }
}

impl Dialled {
    /// Connect to a URL, with the bearer token S2 Connect's session initiation issued.
    ///
    /// `S2C §Authentication`: "the client **must** authenticate itself using the
    /// commToken in the authorization header of the websocket connection request".
    ///
    /// TLS is verified against the **public** PKI, which is right for a WAN endpoint and
    /// wrong for a LAN one: a `wss://EVSE1038.local/s2` certificate is self-signed, and
    /// what makes it trustworthy is the CA pinned during pairing. Use
    /// [`connect_with_policy`](Self::connect_with_policy) there.
    pub async fn connect(url: &str, bearer: Option<&str>) -> Result<Self, Error> {
        Self::open(
            url,
            &WebSocketOptions {
                bearer,
                ..WebSocketOptions::default()
            },
        )
        .await
    }

    /// Connect with everything spelled out: bearer, size cap and TLS policy.
    ///
    /// A `wss://` dial always supplies its own
    /// [`Connector::Rustls`](tokio_tungstenite::Connector::Rustls), built from
    /// [`default_provider`](crate::connect::tls::default_provider): the application's
    /// provider if it installed one, this build's otherwise, and an [`Error::Transport`]
    /// rather than a panic when there is none. Letting `rustls` resolve its own provider
    /// panics when no provider feature is on and panics again when two are (D52).
    pub async fn open(url: &str, options: &WebSocketOptions<'_>) -> Result<Self, Error> {
        use crate::connect::tls::TlsPolicy;

        // A session must never run unauthenticated: the pairing-only policy exists for the
        // four pairing requests and nothing else.
        if let Some(policy) = options.policy
            && !policy.authenticates()
        {
            return Err(Error::Transport(
                "a session must not run under the pairing-only TLS policy".to_string(),
            ));
        }
        let web = TlsPolicy::Web;
        let policy = options.policy.unwrap_or(&web);
        Self::dial(
            url,
            options.bearer,
            policy,
            options.limit(),
            options.allow_insecure_bearer,
        )
        .await
    }

    /// Connect under a [`TlsPolicy`](crate::connect::tls::TlsPolicy) — which, after a LAN
    /// pairing, is the CA that pairing pinned.
    ///
    /// This is the one to use in a LAN, with the policy
    /// `connect::client::Paired::policy` returns. The session initiation that produced the
    /// communication token ran against the pinned CA; connecting the WebSocket against a
    /// bundled root list instead would either fail outright — which is what it does — or,
    /// worse, succeed against a different server.
    ///
    /// ```no_run
    /// # use s2_kit::{connect::tls::TlsPolicy, io::WebSocket};
    /// # async fn run(policy: &TlsPolicy, url: &str, token: &str)
    /// # -> Result<(), Box<dyn std::error::Error>> {
    /// let socket = WebSocket::connect_with_policy(url, Some(token), policy).await?;
    /// # let _ = socket;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect_with_policy(
        url: &str,
        bearer: Option<&str>,
        policy: &crate::connect::tls::TlsPolicy,
    ) -> Result<Self, Error> {
        Self::open(
            url,
            &WebSocketOptions {
                bearer,
                policy: Some(policy),
                ..WebSocketOptions::default()
            },
        )
        .await
    }

    async fn dial(
        url: &str,
        bearer: Option<&str>,
        policy: &crate::connect::tls::TlsPolicy,
        max_message_bytes: usize,
        allow_insecure_bearer: bool,
    ) -> Result<Self, Error> {
        let mut request = url
            .into_client_request()
            .map_err(|e| Error::Transport(e.to_string()))?;
        // Off the parsed URI rather than off the string: `IntoClientRequest` has already
        // done the work, and a `ws://` dial should not pay for a certificate verifier it
        // will never consult.
        let connector = if request
            .uri()
            .scheme_str()
            .is_some_and(|s| s.eq_ignore_ascii_case("wss"))
        {
            let client = crate::connect::tls::TlsClient::new(policy)
                .map_err(|e| Error::Transport(e.to_string()))?;
            Some(tokio_tungstenite::Connector::Rustls(client.config()))
        } else {
            None
        };
        if bearer.is_some() && connector.is_none() && !allow_insecure_bearer {
            return Err(Error::Transport(
                "refusing to send a bearer token over plaintext ws:// (S2C §Encrypted connection)"
                    .to_string(),
            ));
        }
        if let Some(token) = bearer {
            let value = alloc::format!("Bearer {token}")
                .parse()
                .map_err(|_| Error::Transport("invalid bearer token".to_string()))?;
            request.headers_mut().insert("Authorization", value);
        }
        // The cap has to be here rather than only in the codec: by the time `decode`
        // measures a frame, the library has already buffered every byte of it. The
        // library's own defaults are 64 MiB per message and 16 MiB per frame, which is
        // sixty-four megabytes an unauthenticated peer can make a gateway hold before
        // anything of this crate's runs.
        let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default()
            .max_message_size(Some(max_message_bytes))
            .max_frame_size(Some(max_message_bytes));
        let (stream, _) = tokio_tungstenite::connect_async_tls_with_config(
            request,
            Some(config),
            false,
            connector,
        )
        .await
        .map_err(|e| Error::Transport(e.to_string()))?;
        Ok(Self { stream })
    }
}

impl<S> WebSocket<S> {
    /// Wrap an already-established WebSocket — one a server accepted, for instance.
    pub fn from_stream(stream: tokio_tungstenite::WebSocketStream<S>) -> Self {
        Self { stream }
    }
}

impl<S> TextTransport for WebSocket<S>
where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
{
    async fn send_text(&mut self, text: String) -> Result<(), Error> {
        self.stream
            .send(WsMessage::text(text))
            .await
            .map_err(|e| Error::Transport(e.to_string()))
    }

    #[allow(clippy::match_same_arms)] // grouped by reason; see the comments
    async fn recv_text(&mut self) -> Result<Option<String>, Error> {
        loop {
            match self.recv().await? {
                None => return Ok(None),
                Some(Received::Text(text)) => return Ok(Some(text)),
                Some(Received::Alive) => {}
            }
        }
    }

    async fn recv(&mut self) -> Result<Option<Received>, Error> {
        loop {
            match self.stream.next().await {
                // The stream ended, or the peer said goodbye: the same thing to a session.
                None | Some(Ok(WsMessage::Close(_))) => return Ok(None),
                Some(Err(e)) => return Err(Error::Transport(e.to_string())),
                Some(Ok(WsMessage::Text(text))) => {
                    return Ok(Some(Received::Text(text.to_string())));
                }
                // Answering a ping is the library's job; both prove the peer is there.
                Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => {
                    return Ok(Some(Received::Alive));
                }
                Some(Ok(WsMessage::Frame(_))) => {}
                // A binary frame is not S2.
                Some(Ok(WsMessage::Binary(_))) => {
                    return Err(Error::UnexpectedFrame("binary".to_string()));
                }
            }
        }
    }

    async fn ping(&mut self) -> Result<(), Error> {
        self.stream
            .send(WsMessage::Ping(tokio_tungstenite::tungstenite::Bytes::new()))
            .await
            .map_err(|e| Error::Transport(e.to_string()))
    }

    async fn close(&mut self) {
        let _ = self.stream.close(None).await;
    }
}

/// Pumps a session over a transport.
///
/// One `step` flushes everything the session wants to send, then waits for whichever
/// comes first: an inbound frame, the session's next deadline, or the keep-alive
/// interval. The application keeps the loop, and with it the freedom to do anything else
/// between steps.
pub struct Driver<T> {
    transport: T,
    ping_interval: Duration,
    /// The clock. Replaceable so that a test can drive a driver too.
    now: fn() -> Timestamp,
    /// When a keep-alive was last sent, or `None` before the first step.
    ///
    /// The interval is measured from here rather than from the start of each step. A
    /// driver that restarts the timer every time it goes round the loop never pings a
    /// connection that is busy — and `S2C §Keepalive & heartbeat` does not say "ping an
    /// idle connection", it says an implementation "**must not** wait more than 60
    /// seconds between sending ping frames".
    last_ping: Option<Timestamp>,
    /// When the peer was last heard from — any frame at all — or `None` before the first
    /// step.
    last_heard: Option<Timestamp>,
    /// How long silence may last before the transport is treated as closed.
    idle_limit: Option<Duration>,
    /// The span every log line of this session is recorded in.
    ///
    /// One per driver, so per session: an operator filtering a fleet's logs by a resource
    /// id set here sees that resource's conversation and nothing else. The state and the
    /// negotiated version are recorded on it as they change, and each inbound message gets
    /// a child span keyed by its `message_id` — the key the `ReceptionStatus` carries back.
    #[cfg(feature = "tracing")]
    span: tracing::Span,
    /// The state last recorded on the span, so a transition is logged once.
    #[cfg(feature = "tracing")]
    recorded_state: Option<String>,
}

impl<T: TextTransport> Driver<T> {
    /// A driver over this transport.
    pub fn new(transport: T) -> Self {
        Self {
            transport,
            ping_interval: PING_INTERVAL,
            now: Timestamp::now,
            last_ping: None,
            last_heard: None,
            idle_limit: Some(IDLE_LIMIT),
            #[cfg(feature = "tracing")]
            span: tracing::info_span!(
                "s2.session",
                state = tracing::field::Empty,
                version = tracing::field::Empty,
            ),
            #[cfg(feature = "tracing")]
            recorded_state: None,
        }
    }

    /// Record this session's log lines in `span` instead of the default `s2.session`.
    ///
    /// The way to put a resource id, a peer address or a tenant on every line:
    ///
    /// ```ignore
    /// let driver = Driver::new(socket).with_span(tracing::info_span!(
    ///     "s2.session",
    ///     resource = %resource_id,
    ///     state = tracing::field::Empty,
    ///     version = tracing::field::Empty,
    /// ));
    /// ```
    ///
    /// Declare `state` and `version` as empty fields to have the driver fill them in;
    /// `tracing` ignores a record of a field the span did not declare.
    #[cfg(feature = "tracing")]
    #[must_use]
    pub fn with_span(mut self, span: tracing::Span) -> Self {
        self.span = span;
        self
    }

    /// Use a different clock — a virtual one, in a test.
    #[must_use]
    pub fn with_clock(mut self, now: fn() -> Timestamp) -> Self {
        self.now = now;
        self
    }

    /// Treat the transport as closed after this long without a frame from the peer, or
    /// never (`None`). Defaults to [`IDLE_LIMIT`]; keep it a few ping intervals long.
    #[must_use]
    pub fn with_idle_limit(mut self, limit: Option<Duration>) -> Self {
        self.idle_limit = limit;
        self
    }

    /// Send pings at a different interval. S2 Connect allows up to sixty seconds.
    #[must_use]
    pub fn with_ping_interval(mut self, interval: Duration) -> Self {
        self.ping_interval = interval;
        self
    }

    /// The transport, for a caller that wants to close it itself.
    pub fn transport_mut(&mut self) -> &mut T {
        &mut self.transport
    }

    /// Run one step of a session, whichever role it is.
    ///
    /// Flush, wait for the first of {a frame, the session's deadline, the keep-alive
    /// interval}, feed the result back in, flush again. Everything that decides anything
    /// is in the session; this function decides only what to wait on.
    pub async fn step<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
        #[cfg(feature = "tracing")]
        {
            use tracing::Instrument as _;
            let span = self.span.clone();
            let result = self.step_inner(session).instrument(span).await;
            self.record_state(session);
            result
        }
        #[cfg(not(feature = "tracing"))]
        self.step_inner(session).await
    }

    /// Record a state transition on the session span, once per transition.
    #[cfg(feature = "tracing")]
    fn record_state<S: Session>(&mut self, session: &S) {
        let state = alloc::format!("{:?}", session.state());
        if self.recorded_state.as_deref() == Some(state.as_str()) {
            return;
        }
        self.span.record("state", state.as_str());
        if let Some(version) = session.negotiated_version() {
            self.span.record("version", version.as_str());
        }
        self.span
            .in_scope(|| tracing::info!(state = %state, "session state"));
        self.recorded_state = Some(state);
    }

    async fn step_inner<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
        self.flush(session).await?;
        if session.state().is_closed() {
            self.transport.close().await;
            return Ok(());
        }
        let deadline = session.poll_timeout();
        match self.wait(deadline).await? {
            Wake::Text(text) => {
                let inbound = session.handle_text(&text, (self.now)());
                // Never the payload: a message body can carry a household's consumption,
                // and the identifiers are enough to find the exchange in a capture.
                crate::trace::event!(
                    debug,
                    message_id = ?inbound.message_id,
                    kind = ?inbound.kind,
                    status = ?inbound.status,
                    violations = inbound.report.violations().len(),
                    "received"
                );
                // A refusal is the thing an operator actually needs to see, and the rule
                // identifier is what makes it greppable across a fleet.
                if !inbound.accepted() {
                    crate::trace::event!(
                        warn,
                        message_id = ?inbound.message_id,
                        kind = ?inbound.kind,
                        status = ?inbound.status,
                        diagnostic = ?inbound.report.diagnostic_label(),
                        "refused an inbound message"
                    );
                }
            }
            Wake::Timeout => {
                crate::trace::event!(trace, "deadline reached");
                session.handle_timeout((self.now)());
            }
            Wake::Ping => {
                self.last_ping = Some((self.now)());
                self.transport.ping().await?;
            }
            Wake::Alive => {}
            Wake::Closed => {
                crate::trace::event!(info, "the transport closed");
                session.transport_closed((self.now)());
            }
            Wake::Idle => {
                crate::trace::event!(warn, "nothing heard from the peer within the idle limit");
                self.transport.close().await;
                session.transport_closed((self.now)());
            }
        }
        self.flush(session).await
    }

    /// Send everything the session has queued.
    async fn flush<S: Session>(&mut self, session: &mut S) -> Result<(), Error> {
        while let Some(out) = session.poll_transmit() {
            crate::trace::event!(
                debug,
                kind = %out.kind.as_str(),
                message_id = ?out.message_id,
                bytes = out.text.len(),
                "sending"
            );
            self.transport.send_text(out.text).await?;
        }
        Ok(())
    }

    /// Run a session to completion: steps until it closes.
    ///
    /// The application still sees every event, through the callback, but no longer owns
    /// the loop. For anything that wants to do other work between steps, use
    /// [`Self::step`].
    pub async fn run<S, F>(&mut self, session: &mut S, mut on_event: F) -> Result<(), Error>
    where
        S: Session,
        F: FnMut(S::Event, &mut S),
    {
        while !session.state().is_closed() {
            self.step(session).await?;
            while let Some(event) = session.poll_event() {
                on_event(event, session);
            }
        }
        self.flush(session).await?;
        self.transport.close().await;
        Ok(())
    }

    async fn wait(&mut self, deadline: Option<Timestamp>) -> Result<Wake, Error> {
        let now = (self.now)();
        // A session with no deadline still has to be woken for the keep-alive, so
        // "never" is expressed as a span no ping interval will ever exceed rather than
        // as an infinite sleep.
        let until_deadline = deadline.map_or(Duration::MAX, |at| at.saturating_duration_since(now));
        let until_ping = match self.last_ping {
            // The first step starts the clock rather than pinging immediately: a socket
            // that has just been opened does not need proof that it is alive.
            None => {
                self.last_ping = Some(now);
                self.ping_interval
            }
            Some(last) => self
                .ping_interval
                .checked_sub(now.saturating_duration_since(last))
                .unwrap_or(Duration::ZERO),
        };

        let until_idle = match (self.idle_limit, self.last_heard) {
            (None, _) => Duration::MAX,
            // As with the ping, the first step starts the clock.
            (Some(limit), None) => {
                self.last_heard = Some(now);
                limit
            }
            (Some(limit), Some(heard)) => limit
                .checked_sub(now.saturating_duration_since(heard))
                .unwrap_or(Duration::ZERO),
        };

        let (sleep_for, wake) = [
            (until_deadline, Wake::Timeout),
            (until_ping, Wake::Ping),
            (until_idle, Wake::Idle),
        ]
        .into_iter()
        .min_by_key(|(after, _)| *after)
        .unwrap_or((until_deadline, Wake::Timeout));

        tokio::select! {
            frame = self.transport.recv() => {
                let frame = frame?;
                if frame.is_some() {
                    self.last_heard = Some((self.now)());
                }
                Ok(match frame {
                    Some(Received::Text(text)) => Wake::Text(text),
                    Some(Received::Alive) => Wake::Alive,
                    None => Wake::Closed,
                })
            },
            () = tokio::time::sleep(core::time::Duration::from(sleep_for)) => Ok(wake),
        }
    }
}

enum Wake {
    Text(String),
    Timeout,
    Ping,
    Alive,
    Closed,
    Idle,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{RmConfig, RmSession};
    use alloc::collections::VecDeque;
    use alloc::vec::Vec;

    /// A transport that hands back a script and records what was written.
    struct Scripted {
        inbound: VecDeque<String>,
        outbound: Vec<String>,
        pings: usize,
    }

    impl TextTransport for Scripted {
        async fn send_text(&mut self, text: String) -> Result<(), Error> {
            // A yield point, so the mock behaves like a transport that can be
            // interleaved rather than one that always completes instantly.
            tokio::task::yield_now().await;
            self.outbound.push(text);
            Ok(())
        }
        async fn recv_text(&mut self) -> Result<Option<String>, Error> {
            if let Some(text) = self.inbound.pop_front() {
                return Ok(Some(text));
            }
            // Nothing more scripted: block for ever, so the timer wins the select.
            core::future::pending::<()>().await;
            unreachable!()
        }
        async fn ping(&mut self) -> Result<(), Error> {
            tokio::task::yield_now().await;
            self.pings += 1;
            Ok(())
        }
        async fn close(&mut self) {
            tokio::task::yield_now().await;
        }
    }

    fn clock() -> Timestamp {
        "2024-01-01T12:00:00Z"
            .parse()
            .unwrap_or(Timestamp::UNIX_EPOCH)
    }

    #[tokio::test]
    async fn a_step_flushes_the_outbox_and_feeds_back_what_arrives() {
        let details = crate::testing::battery_details();
        let mut rm = RmSession::new(RmConfig::default(), details);
        rm.open(clock());

        let transport = Scripted {
            inbound: VecDeque::from([
                r#"{"message_type":"Handshake","message_id":"c1","role":"CEM","supported_protocol_versions":["1.0.0"]}"#.to_string(),
            ]),
            outbound: Vec::new(),
            pings: 0,
        };
        let mut driver = Driver::new(transport).with_clock(clock);

        driver.step(&mut rm).await.unwrap();

        let written = &driver.transport_mut().outbound;
        assert!(written[0].contains(r#""message_type":"Handshake""#));
        // And the CEM's handshake was answered.
        assert!(written.iter().any(|m| m.contains("ReceptionStatus")));
    }

    #[tokio::test(start_paused = true)]
    async fn a_link_that_goes_silent_is_closed_rather_than_pinged_for_ever() {
        // A half-open TCP connection answers nothing — not a message, not a pong. Without
        // a limit the driver pings into it indefinitely and reconnection never starts.
        let details = crate::testing::battery_details();
        let mut rm = RmSession::new(RmConfig::default(), details);
        rm.open(virtual_clock());
        let transport = Scripted {
            inbound: VecDeque::new(),
            outbound: Vec::new(),
            pings: 0,
        };
        let mut driver = Driver::new(transport)
            .with_clock(virtual_clock)
            .with_ping_interval(Duration::from_secs(1))
            .with_idle_limit(Some(Duration::from_secs(3)));
        for _ in 0..64 {
            driver.step(&mut rm).await.unwrap();
            if rm.state().is_closed() {
                break;
            }
        }
        assert!(
            rm.state().is_closed(),
            "silence past the limit must end the session"
        );
        assert!(driver.transport_mut().pings >= 2, "it was pinged first");
    }

    /// A transport that answers every `recv_text` after `gap`, for ever.
    ///
    /// A connection that is *busy*, as opposed to the silent one the other test uses.
    struct Chatty {
        gap: core::time::Duration,
        pings: usize,
    }

    impl TextTransport for Chatty {
        // The trait is async; a mock that drops what it is given is not.
        #[allow(clippy::unused_async_trait_impl)]
        async fn send_text(&mut self, _text: String) -> Result<(), Error> {
            Ok(())
        }
        async fn recv_text(&mut self) -> Result<Option<String>, Error> {
            tokio::time::sleep(self.gap).await;
            Ok(Some(
                r#"{"message_type":"PowerMeasurement","message_id":"c1",
                    "measurement_timestamp":"2024-01-01T12:00:00Z",
                    "values":[{"commodity_quantity":"ELECTRIC.POWER.L1","value":1.0}]}"#
                    .to_string(),
            ))
        }
        #[allow(clippy::unused_async_trait_impl)]
        async fn ping(&mut self) -> Result<(), Error> {
            self.pings += 1;
            Ok(())
        }
        #[allow(clippy::unused_async_trait_impl)]
        async fn close(&mut self) {}
    }

    /// A clock reading tokio's virtual time, so the driver and the runtime agree.
    fn virtual_clock() -> Timestamp {
        use std::sync::OnceLock;
        static START: OnceLock<tokio::time::Instant> = OnceLock::new();
        let start = *START.get_or_init(tokio::time::Instant::now);
        let elapsed = tokio::time::Instant::now().saturating_duration_since(start);
        Timestamp::from_unix(1_700_000_000, 0)
            .checked_add(Duration::from_millis(
                u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX),
            ))
            .unwrap_or(Timestamp::UNIX_EPOCH)
    }

    #[tokio::test(start_paused = true)]
    async fn a_busy_connection_still_gets_a_keep_alive() {
        // The bug this pins: an interval measured from the start of each step never
        // elapses on a connection that has traffic, so a driver doing its job stops
        // pinging — and `S2C §Keepalive & heartbeat` says an implementation "must not
        // wait more than 60 seconds between sending ping frames", not "unless it is
        // busy". A frame every hundred milliseconds against a one-second interval is a
        // connection that is never idle for a whole interval and must be pinged anyway.
        let details = crate::testing::battery_details();
        let mut rm = RmSession::new(RmConfig::default(), details);
        rm.open(virtual_clock());

        let transport = Chatty {
            gap: core::time::Duration::from_millis(100),
            pings: 0,
        };
        let mut driver = Driver::new(transport)
            .with_clock(virtual_clock)
            .with_ping_interval(Duration::from_secs(1));

        // Thirty-odd steps is a little over three seconds of traffic.
        for _ in 0..34 {
            driver.step(&mut rm).await.unwrap();
        }
        assert!(
            driver.transport_mut().pings >= 2,
            "expected the keep-alive to fire about once a second, got {}",
            driver.transport_mut().pings
        );
    }

    #[tokio::test(start_paused = true)]
    async fn a_quiet_connection_gets_a_keep_alive() {
        let details = crate::testing::battery_details();
        let mut rm = RmSession::new(RmConfig::default(), details);
        rm.open(clock());
        let transport = Scripted {
            inbound: VecDeque::new(),
            outbound: Vec::new(),
            pings: 0,
        };
        let mut driver = Driver::new(transport)
            .with_clock(clock)
            .with_ping_interval(Duration::from_secs(1));
        // The handshake is waiting for an acknowledgement with a five-second deadline,
        // so the one-second ping interval wins.
        driver.step(&mut rm).await.unwrap();
        assert_eq!(driver.transport_mut().pings, 1);
    }
}