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