monocoque_core/
monitor.rs1use crate::endpoint::Endpoint;
7use std::fmt;
8
9#[derive(Debug, Clone)]
11pub enum SocketEvent {
12 Connected(Endpoint),
14
15 Disconnected(Endpoint),
17
18 Bound(Endpoint),
20
21 BindFailed { endpoint: Endpoint, reason: String },
23
24 ConnectFailed { endpoint: Endpoint, reason: String },
26
27 Listening(Endpoint),
29
30 Accepted(Endpoint),
32}
33
34impl fmt::Display for SocketEvent {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 match self {
37 Self::Connected(ep) => write!(f, "Connected to {ep}"),
38 Self::Disconnected(ep) => write!(f, "Disconnected from {ep}"),
39 Self::Bound(ep) => write!(f, "Bound to {ep}"),
40 Self::BindFailed { endpoint, reason } => {
41 write!(f, "Bind failed for {endpoint}: {reason}")
42 }
43 Self::ConnectFailed { endpoint, reason } => {
44 write!(f, "Connect failed for {endpoint}: {reason}")
45 }
46 Self::Listening(ep) => write!(f, "Listening on {ep}"),
47 Self::Accepted(ep) => write!(f, "Accepted connection from {ep}"),
48 }
49 }
50}
51
52pub type SocketMonitor = flume::Receiver<SocketEvent>;
56
57pub type SocketEventSender = flume::Sender<SocketEvent>;
61
62pub const MONITOR_CHANNEL_CAP: usize = 256;
69
70#[must_use]
77pub fn create_monitor() -> (SocketEventSender, SocketMonitor) {
78 flume::bounded(MONITOR_CHANNEL_CAP)
79}
80
81pub fn emit(sender: &SocketEventSender, event: SocketEvent) {
87 let _ = sender.try_send(event);
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 use std::net::SocketAddr;
94
95 #[test]
96 fn test_socket_event_display() {
97 let addr: SocketAddr = "127.0.0.1:5555".parse().unwrap();
98 let event = SocketEvent::Connected(Endpoint::Tcp(addr));
99 assert_eq!(event.to_string(), "Connected to tcp://127.0.0.1:5555");
100 }
101
102 #[test]
103 fn test_monitor_channel() {
104 let (sender, receiver) = create_monitor();
105 let addr: SocketAddr = "127.0.0.1:5555".parse().unwrap();
106 emit(&sender, SocketEvent::Connected(Endpoint::Tcp(addr)));
107
108 let event = receiver.recv().unwrap();
109 assert!(matches!(event, SocketEvent::Connected(_)));
110 }
111
112 #[test]
113 fn emit_is_bounded_and_never_blocks_when_undrained() {
114 let (sender, receiver) = create_monitor();
117 let addr: SocketAddr = "127.0.0.1:5555".parse().unwrap();
118 for _ in 0..(MONITOR_CHANNEL_CAP * 4) {
119 emit(&sender, SocketEvent::Connected(Endpoint::Tcp(addr)));
120 }
121 assert_eq!(
122 receiver.len(),
123 MONITOR_CHANNEL_CAP,
124 "monitor channel must stay bounded at its cap when undrained"
125 );
126 }
127}