-
Notifications
You must be signed in to change notification settings - Fork 4
/
subscriber.rs
172 lines (154 loc) · 5.35 KB
/
subscriber.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use std::{
any::Any,
io::ErrorKind,
net::{SocketAddr, UdpSocket},
sync::atomic::{self, Ordering},
sync::{atomic::AtomicBool, Arc},
thread::JoinHandle,
time::Duration,
};
use crate::{timestamp, ControlMessage, ControllerHandle, Handler, Packet, MTU};
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_millis(1_000);
pub struct UdpSubscriberConfig {
pub client_addr: SocketAddr,
pub read_timeout: Duration,
/// Drop events which came out of sequence
pub drop_out_of_sequence: bool,
}
impl UdpSubscriberConfig {
pub fn new(client_addr: SocketAddr) -> Self {
Self {
client_addr,
read_timeout: DEFAULT_READ_TIMEOUT,
drop_out_of_sequence: false,
}
}
}
pub struct UdpSubscriber<MessageHandler> {
sock: UdpSocket,
config: UdpSubscriberConfig,
shutdown_flag: Arc<AtomicBool>,
handler: MessageHandler,
}
pub struct UdpSubscriberHandle<MessageHandler> {
handle: JoinHandle<MessageHandler>,
shutdown: Arc<AtomicBool>,
sock: UdpSocket,
}
impl<MessageHandler> UdpSubscriberHandle<MessageHandler> {
pub fn join(self) -> Result<MessageHandler, Box<dyn Any + Send + 'static>> {
self.handle.join()
}
pub fn shutdown(self) -> Result<MessageHandler, Box<dyn Any + Send + 'static>> {
self.shutdown.store(true, atomic::Ordering::Relaxed);
self.join()
}
pub fn socket(&self) -> &UdpSocket {
&self.sock
}
}
impl<MessageHandler: Handler> UdpSubscriber<MessageHandler> {
pub fn new(
config: UdpSubscriberConfig,
handler: MessageHandler,
) -> Result<Self, std::io::Error> {
let client_addr = config.client_addr;
let sock = UdpSocket::bind(client_addr)?;
Ok(Self {
config,
sock: sock.try_clone()?,
shutdown_flag: Arc::default(),
handler,
})
}
pub fn set_nonblocking(&mut self, nonblocking: bool) -> Result<(), std::io::Error> {
self.sock.set_nonblocking(nonblocking)
}
pub fn run(mut self) -> MessageHandler {
// Blocking way of polling socket
assert!(!self.config.read_timeout.is_zero());
self.sock
.set_read_timeout(Some(self.config.read_timeout))
.unwrap();
let mut buf = [0u8; MTU];
let last_server_ts = 0;
loop {
match self.sock.recv(&mut buf) {
Ok(len) => {
let ts = timestamp();
let msg: Packet<MessageHandler::Message> =
bincode::deserialize(&buf[..len]).unwrap();
if self.config.drop_out_of_sequence && last_server_ts > msg.sent_ts {
continue;
}
// Pass message packet to handler
self.handler.handle(msg, ts);
}
Err(err)
if err.kind() == ErrorKind::WouldBlock || err.kind() == ErrorKind::TimedOut => {
}
Err(err) => todo!("Receive failed: {err}"),
}
if self.shutdown_flag.load(atomic::Ordering::Relaxed) {
break;
}
#[cfg(feature = "cooperative_waiting")]
std::thread::yield_now();
#[cfg(not(feature = "cooperative_waiting"))]
for i in 0..128 {
std::hint::spin_loop();
}
}
self.handler
}
}
impl<MessageHandler: Handler + Send + 'static> UdpSubscriber<MessageHandler> {
pub fn spawn(
self,
bind_to_core: Option<usize>,
) -> Result<UdpSubscriberHandle<MessageHandler>, std::io::Error> {
let shutdown = self.shutdown_flag.clone();
let sock = self.sock.try_clone()?;
let handle = std::thread::Builder::new()
.name(format!("udp_sub:{}", self.config.client_addr))
.spawn(move || {
if let Some(core) = bind_to_core {
crate::pin_to_core(core);
}
self.run()
})?;
Ok(UdpSubscriberHandle {
handle,
shutdown,
sock,
})
}
pub fn spawn_controller(
&self,
server_addr: SocketAddr,
) -> Result<ControllerHandle, std::io::Error> {
let shutdown_controller = Arc::new(AtomicBool::default());
let shutdown = shutdown_controller.clone();
let server_socket = self.sock.try_clone()?;
let handle = std::thread::Builder::new()
.name("udp_sub_controller".into())
.spawn(move || {
if let Err(err) = server_socket.connect(server_addr) {
shutdown.store(true, Ordering::Relaxed);
log::error!("Failed to connect to {} {err}", server_addr);
}
let subscribe = bincode::serialize(&ControlMessage::Subscribe).unwrap();
while !shutdown.load(Ordering::Relaxed) {
if let Err(err) = server_socket.send(&subscribe) {
shutdown.store(true, Ordering::Relaxed);
log::error!("Failed to receive message {err}");
}
std::thread::sleep(Duration::from_secs(1));
}
})?;
Ok(ControllerHandle {
handle,
shutdown: shutdown_controller,
})
}
}