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