Skip to main content

fritz_sim/
callmonitor.rs

1//! A fake call monitor: a TCP listener on loopback that sends scripted
2//! lines, like the one of a device on port 1012.
3
4use std::io;
5use std::net::{Ipv4Addr, SocketAddr};
6use std::sync::Arc;
7use std::sync::atomic::{AtomicUsize, Ordering};
8
9use tokio::io::AsyncWriteExt as _;
10use tokio::net::TcpListener;
11use tokio::task::JoinHandle;
12
13/// A running call monitor. It stops when dropped.
14#[derive(Debug)]
15pub struct CallMonitor {
16    address: SocketAddr,
17    connections: Arc<AtomicUsize>,
18    server: JoinHandle<()>,
19}
20
21impl CallMonitor {
22    /// Listens on a free port of the loopback interface. Each connection
23    /// gets the lines of the next session, each ended with `\r\n` like the
24    /// device does, and is closed after them, except the one of the last
25    /// session, which stays open. Lines can be anything, like events that
26    /// are not valid; sessions can repeat the lines of the one before, like
27    /// a device that would send them again.
28    ///
29    /// # Errors
30    ///
31    /// The errors of binding the port.
32    ///
33    /// # Panics
34    ///
35    /// The server task panics if it cannot accept a connection on loopback.
36    pub async fn start(sessions: Vec<Vec<String>>) -> io::Result<Self> {
37        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?;
38        let address = listener.local_addr()?;
39        let connections = Arc::new(AtomicUsize::new(0));
40        let count = Arc::clone(&connections);
41        let server = tokio::spawn(async move {
42            let mut open = Vec::new();
43            loop {
44                let (mut stream, _) = listener.accept().await.expect("accepts on loopback");
45                let index = count.fetch_add(1, Ordering::SeqCst);
46                let lines = sessions.get(index).cloned().unwrap_or_default();
47                for line in lines {
48                    let _ = stream.write_all(format!("{line}\r\n").as_bytes()).await;
49                }
50                if index + 1 >= sessions.len() {
51                    open.push(stream);
52                }
53            }
54        });
55        Ok(Self {
56            address,
57            connections,
58            server,
59        })
60    }
61
62    /// The port it listens on.
63    pub fn port(&self) -> u16 {
64        self.address.port()
65    }
66
67    /// How many connections it accepted so far.
68    pub fn connections(&self) -> usize {
69        self.connections.load(Ordering::SeqCst)
70    }
71}
72
73impl Drop for CallMonitor {
74    fn drop(&mut self) {
75        self.server.abort();
76    }
77}