1use 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
48pub const PING_INTERVAL: Duration = Duration::from_secs(30);
54
55#[derive(Debug, thiserror::Error)]
57#[non_exhaustive]
58pub enum Error {
59 #[error("transport error: {0}")]
61 Transport(String),
62 #[error("the peer closed the connection")]
64 Closed,
65 #[error("unexpected frame: {0}")]
67 UnexpectedFrame(String),
68}
69
70pub trait TextTransport {
72 fn send_text(&mut self, text: String) -> impl Future<Output = Result<(), Error>> + Send;
74 fn recv_text(&mut self) -> impl Future<Output = Result<Option<String>, Error>> + Send;
76 fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send;
78 fn close(&mut self) -> impl Future<Output = ()> + Send;
80}
81
82pub struct WebSocket<S> {
84 stream: tokio_tungstenite::WebSocketStream<S>,
85}
86
87impl WebSocket<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>> {
88 pub async fn connect(url: &str, bearer: Option<&str>) -> Result<Self, Error> {
98 Self::dial(url, bearer, None).await
99 }
100
101 #[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 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 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)] 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 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
208pub struct Driver<T> {
215 transport: T,
216 ping_interval: Duration,
217 now: fn() -> Timestamp,
219 last_ping: Option<Timestamp>,
227}
228
229impl<T: TextTransport> Driver<T> {
230 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 #[must_use]
242 pub fn with_clock(mut self, now: fn() -> Timestamp) -> Self {
243 self.now = now;
244 self
245 }
246
247 #[must_use]
249 pub fn with_ping_interval(mut self, interval: Duration) -> Self {
250 self.ping_interval = interval;
251 self
252 }
253
254 pub fn transport_mut(&mut self) -> &mut T {
256 &mut self.transport
257 }
258
259 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 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 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 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 let until_deadline = deadline.map_or(Duration::MAX, |at| at.saturating_duration_since(now));
350 let until_ping = match self.last_ping {
351 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 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 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 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 assert!(written.iter().any(|m| m.contains("ReceptionStatus")));
453 }
454
455 struct Chatty {
459 gap: core::time::Duration,
460 pings: usize,
461 }
462
463 impl TextTransport for Chatty {
464 #[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 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 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 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 driver.step(&mut rm).await.unwrap();
547 assert_eq!(driver.transport_mut().pings, 1);
548 }
549}