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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use crate::endpoint::{Endpoint};
use crate::resource_id::{ResourceId};
use crate::poll::{Poll};
use crate::adapter::{Adapter, SendStatus};
use crate::remote_addr::{RemoteAddr};
use crate::driver::{AdapterEvent, ActionController, EventProcessor, Driver};
use crate::util::{OTHER_THREAD_ERR};
use std::time::{Duration};
use std::net::{SocketAddr};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use std::thread::{self, JoinHandle};
use std::io::{self};
type ActionControllers = Vec<Box<dyn ActionController + Send>>;
type EventProcessors = Vec<Box<dyn EventProcessor + Send>>;
pub struct AdapterLauncher {
poll: Poll,
controllers: ActionControllers,
processors: EventProcessors,
}
impl Default for AdapterLauncher {
fn default() -> AdapterLauncher {
Self {
poll: Poll::default(),
controllers: (0..ResourceId::MAX_ADAPTERS)
.map(|_| {
Box::new(UnimplementedActionController) as Box<dyn ActionController + Send>
})
.collect::<Vec<_>>(),
processors: (0..ResourceId::MAX_ADAPTERS)
.map(|_| Box::new(UnimplementedEventProcessor) as Box<dyn EventProcessor + Send>)
.collect(),
}
}
}
impl AdapterLauncher {
pub fn mount(&mut self, adapter_id: u8, adapter: impl Adapter + 'static) {
let index = adapter_id as usize;
let driver = Driver::new(adapter, adapter_id, &mut self.poll);
self.controllers[index] = Box::new(driver.clone()) as Box<(dyn ActionController + Send)>;
self.processors[index] = Box::new(driver) as Box<(dyn EventProcessor + Send)>;
}
fn launch(self) -> (Poll, ActionControllers, EventProcessors) {
(self.poll, self.controllers, self.processors)
}
}
pub struct NetworkEngine {
thread: Option<JoinHandle<()>>,
thread_running: Arc<AtomicBool>,
controllers: ActionControllers,
}
impl NetworkEngine {
const NETWORK_SAMPLING_TIMEOUT: u64 = 50;
pub fn new(
launcher: AdapterLauncher,
event_callback: impl Fn(AdapterEvent<'_>) + Send + 'static,
) -> Self
{
let thread_running = Arc::new(AtomicBool::new(true));
let running = thread_running.clone();
let (poll, controllers, processors) = launcher.launch();
let thread = Self::run_processor(running, poll, processors, move |adapter_event| {
match adapter_event {
AdapterEvent::Added(endpoint) => {
log::trace!("Endpoint added: {}", endpoint);
}
AdapterEvent::Data(endpoint, data) => {
log::trace!("Data received from {}, {} bytes", endpoint, data.len());
}
AdapterEvent::Removed(endpoint) => {
log::trace!("Endpoint removed: {}", endpoint);
}
}
event_callback(adapter_event);
});
Self { thread: Some(thread), thread_running, controllers }
}
pub fn run_processor(
running: Arc<AtomicBool>,
mut poll: Poll,
mut processors: EventProcessors,
event_callback: impl Fn(AdapterEvent<'_>) + Send + 'static,
) -> JoinHandle<()>
{
thread::Builder::new()
.name("message-io: event processor".into())
.spawn(move || {
let timeout = Some(Duration::from_millis(Self::NETWORK_SAMPLING_TIMEOUT));
while running.load(Ordering::Relaxed) {
poll.process_event(timeout, |resource_id| {
log::trace!("Resource id {} woke up by an event", resource_id);
processors[resource_id.adapter_id() as usize]
.try_process(resource_id, &event_callback);
});
}
})
.unwrap()
}
pub fn connect(
&mut self,
adapter_id: u8,
addr: RemoteAddr,
) -> io::Result<(Endpoint, SocketAddr)>
{
self.controllers[adapter_id as usize].connect(addr).map(|(endpoint, addr)| {
log::trace!("Connected endpoint {} by {}", endpoint, adapter_id);
(endpoint, addr)
})
}
pub fn listen(
&mut self,
adapter_id: u8,
addr: SocketAddr,
) -> io::Result<(ResourceId, SocketAddr)>
{
self.controllers[adapter_id as usize].listen(addr).map(|(resource_id, addr)| {
log::trace!("New resource {} listening by {}", resource_id, adapter_id);
(resource_id, addr)
})
}
pub fn remove(&mut self, id: ResourceId) -> Option<()> {
self.controllers[id.adapter_id() as usize].remove(id)
}
pub fn send(&mut self, endpoint: Endpoint, data: &[u8]) -> SendStatus {
let status =
self.controllers[endpoint.resource_id().adapter_id() as usize].send(endpoint, data);
log::trace!("Message ({} bytes) sent to {}, {:?}", data.len(), endpoint, status);
status
}
}
impl Drop for NetworkEngine {
fn drop(&mut self) {
self.thread_running.store(false, Ordering::Relaxed);
self.thread.take().unwrap().join().expect(OTHER_THREAD_ERR);
}
}
const UNIMPLEMENTED_ADAPTER_ERR: &str =
"The chosen adapter id doesn't reference an existing adapter";
struct UnimplementedActionController;
impl ActionController for UnimplementedActionController {
fn connect(&mut self, _: RemoteAddr) -> io::Result<(Endpoint, SocketAddr)> {
panic!("{}", UNIMPLEMENTED_ADAPTER_ERR);
}
fn listen(&mut self, _: SocketAddr) -> io::Result<(ResourceId, SocketAddr)> {
panic!("{}", UNIMPLEMENTED_ADAPTER_ERR);
}
fn send(&mut self, _: Endpoint, _: &[u8]) -> SendStatus {
panic!("{}", UNIMPLEMENTED_ADAPTER_ERR);
}
fn remove(&mut self, _: ResourceId) -> Option<()> {
panic!("{}", UNIMPLEMENTED_ADAPTER_ERR);
}
}
struct UnimplementedEventProcessor;
impl EventProcessor for UnimplementedEventProcessor {
fn try_process(&mut self, _: ResourceId, _: &dyn Fn(AdapterEvent<'_>)) {
panic!("{}", UNIMPLEMENTED_ADAPTER_ERR);
}
}