-
Notifications
You must be signed in to change notification settings - Fork 8
/
actor.rs
398 lines (341 loc) · 11.4 KB
/
actor.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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use std::sync::{
atomic::{self, AtomicBool},
Arc,
};
use lazy_static::lazy_static;
use crate::infrastructure::error::{DdsError, DdsResult};
lazy_static! {
pub static ref THE_RUNTIME: tokio::runtime::Runtime =
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("Failed to create Tokio runtime");
}
pub trait Mail {
type Result;
}
pub trait MailHandler<M>
where
M: Mail,
Self: Sized,
{
fn handle(&mut self, mail: M) -> M::Result;
}
pub trait CommandHandler<M> {
fn handle(&mut self, mail: M);
}
#[derive(Debug)]
pub struct ActorAddress<A> {
sender: tokio::sync::mpsc::UnboundedSender<Box<dyn GenericHandler<A> + Send>>,
}
impl<A> Clone for ActorAddress<A> {
fn clone(&self) -> Self {
Self {
sender: self.sender.clone(),
}
}
}
impl<A> PartialEq for ActorAddress<A> {
fn eq(&self, other: &Self) -> bool {
self.sender.same_channel(&other.sender)
}
}
impl<A> Eq for ActorAddress<A> {}
impl<A> ActorAddress<A> {
pub fn send_blocking<M>(&self, mail: M) -> DdsResult<M::Result>
where
A: MailHandler<M>,
M: Mail + Send + 'static,
M::Result: Send,
{
let (response_sender, response_receiver) = tokio::sync::oneshot::channel();
self.sender
.send(Box::new(SyncMail::new(mail, response_sender)))
.map_err(|_| DdsError::AlreadyDeleted)?;
response_receiver
.blocking_recv()
.map_err(|_| DdsError::AlreadyDeleted)
}
pub fn send_command<M>(&self, command: M) -> DdsResult<()>
where
A: CommandHandler<M>,
M: Send + 'static,
{
self.sender
.send(Box::new(CommandMail::new(command)))
.map_err(|_| DdsError::AlreadyDeleted)
}
}
trait GenericHandler<A> {
fn handle(&mut self, actor: &mut A);
}
struct SyncMail<M>
where
M: Mail,
{
// Both fields have to be inside an option because later on the contents
// have to be moved out and the struct. Because the struct is passed as a Boxed
// trait object this is only feasible by using the Option fields.
mail: Option<M>,
sender: Option<tokio::sync::oneshot::Sender<M::Result>>,
}
impl<M> SyncMail<M>
where
M: Mail,
{
fn new(message: M, sender: tokio::sync::oneshot::Sender<M::Result>) -> Self {
Self {
mail: Some(message),
sender: Some(sender),
}
}
}
impl<A, M> GenericHandler<A> for SyncMail<M>
where
A: MailHandler<M>,
M: Mail,
{
fn handle(&mut self, actor: &mut A) {
let result = <A as MailHandler<M>>::handle(
actor,
self.mail
.take()
.expect("Mail should be processed only once"),
);
self.sender
.take()
.expect("Mail should be processed only once")
.send(result)
.map_err(|_| "Failed to send message on type withou Debug")
.expect("Sending should never fail");
}
}
struct CommandMail<M> {
mail: Option<M>,
}
impl<M> CommandMail<M> {
fn new(mail: M) -> Self {
Self { mail: Some(mail) }
}
}
impl<A, M> GenericHandler<A> for CommandMail<M>
where
A: CommandHandler<M>,
{
fn handle(&mut self, actor: &mut A) {
<A as CommandHandler<M>>::handle(
actor,
self.mail
.take()
.expect("Mail should be processed only once"),
);
}
}
pub struct Actor<A> {
address: ActorAddress<A>,
join_handle: tokio::task::JoinHandle<()>,
cancellation_token: Arc<AtomicBool>,
}
impl<A> Actor<A> {
pub fn address(&self) -> &ActorAddress<A> {
&self.address
}
}
impl<A> Drop for Actor<A> {
fn drop(&mut self) {
self.cancellation_token
.store(true, atomic::Ordering::Release);
self.join_handle.abort();
}
}
struct SpawnedActor<A> {
value: A,
mailbox: tokio::sync::mpsc::UnboundedReceiver<Box<dyn GenericHandler<A> + Send>>,
}
pub fn spawn_actor<A>(actor: A) -> Actor<A>
where
A: Send + 'static,
{
let (sender, mailbox) = tokio::sync::mpsc::unbounded_channel();
let address = ActorAddress { sender };
let mut actor_obj = SpawnedActor {
value: actor,
mailbox,
};
let cancellation_token = Arc::new(AtomicBool::new(false));
let cancellation_token_cloned = cancellation_token.clone();
let join_handle = THE_RUNTIME.spawn(async move {
while let Some(mut m) = actor_obj.mailbox.recv().await {
if !cancellation_token_cloned.load(atomic::Ordering::Acquire) {
m.handle(&mut actor_obj.value);
} else {
break;
}
}
});
Actor {
address,
join_handle,
cancellation_token,
}
}
// Macro to create both a function for the method and the equivalent wrapper for the actor
macro_rules! mailbox_function {
// Match a function definition with return type
($type_name:ident, pub fn $fn_name:ident(&$($self_:ident)+ $(, $arg_name:ident:$arg_type:ty)* $(,)?) -> $ret_type:ty $body:block) => {
impl $type_name {
#[allow(clippy::too_many_arguments)]
pub fn $fn_name(&$($self_)+ $(, $arg_name:$arg_type)*) -> $ret_type{
$body
}
}
impl crate::implementation::utils::actor::ActorAddress<$type_name> {
#[allow(clippy::too_many_arguments)]
pub fn $fn_name(&self $(, $arg_name:$arg_type)*) -> crate::infrastructure::error::DdsResult<$ret_type> {
#[allow(non_camel_case_types)]
struct $fn_name {
$($arg_name:$arg_type,)*
}
impl crate::implementation::utils::actor::Mail for $fn_name {
type Result = $ret_type;
}
impl crate::implementation::utils::actor::MailHandler<$fn_name> for $type_name {
#[allow(unused_variables)]
fn handle(&mut self, mail: $fn_name) -> $ret_type {
self.$fn_name($(mail.$arg_name,)*)
}
}
self.send_blocking($fn_name{
$($arg_name, )*
})
}
}
};
// Match a function definition without return type
($type_name:ident, pub fn $fn_name:ident(&$($self_:ident)+ $(, $arg_name:ident:$arg_type:ty)* $(,)?) $body:block ) => {
impl $type_name {
#[allow(clippy::too_many_arguments)]
pub fn $fn_name(&$($self_)+ $(, $arg_name:$arg_type)* ) {
$body
}
}
impl crate::implementation::utils::actor::ActorAddress<$type_name> {
#[allow(clippy::too_many_arguments)]
pub fn $fn_name(&self $(, $arg_name:$arg_type)*) -> crate::infrastructure::error::DdsResult<()> {
#[allow(non_camel_case_types)]
struct $fn_name {
$($arg_name:$arg_type,)*
}
impl crate::implementation::utils::actor::Mail for $fn_name {
type Result = ();
}
impl crate::implementation::utils::actor::MailHandler<$fn_name> for $type_name {
#[allow(unused_variables)]
fn handle(&mut self, mail: $fn_name) {
self.$fn_name($(mail.$arg_name,)*)
}
}
self.send_blocking($fn_name{
$($arg_name, )*
})
}
}
};
}
pub(crate) use mailbox_function;
// This macro should wrap an impl block and create the actor address wrapper methods with exactly the same interface
// It is kept around the "impl" block because otherwise there is no way to find the type name it refers to ($type_name)
macro_rules! actor_mailbox_interface {
(impl $type_name:ident {
$(
pub fn $fn_name:ident(&$($self_:ident)+ $(, $arg_name:ident:$arg_type:ty)* $(,)?) $(-> $ret_type:ty)?
$body:block
)+
}) => {
$(crate::implementation::utils::actor::mailbox_function!($type_name, pub fn $fn_name(&$($self_)+ $(, $arg_name:$arg_type)*) $(-> $ret_type)? $body );)+
};
}
pub(crate) use actor_mailbox_interface;
macro_rules! command_function {
// Commands are only valid for functions without return
($type_name:ident, pub fn $fn_name:ident(&$($self_:ident)+ $(, $arg_name:ident:$arg_type:ty)* $(,)?) $body:block ) => {
impl $type_name {
pub fn $fn_name(&$($self_)+ $(, $arg_name:$arg_type)* ) {
$body
}
}
impl crate::implementation::utils::actor::ActorAddress<$type_name> {
pub fn $fn_name(&self $(, $arg_name:$arg_type)*) -> crate::infrastructure::error::DdsResult<()> {
#[allow(non_camel_case_types)]
struct $fn_name {
$($arg_name:$arg_type,)*
}
impl crate::implementation::utils::actor::CommandHandler<$fn_name> for $type_name {
#[allow(unused_variables)]
fn handle(&mut self, mail: $fn_name) {
self.$fn_name($(mail.$arg_name,)*)
}
}
self.send_command($fn_name{
$($arg_name, )*
})
}
}
};
}
pub(crate) use command_function;
macro_rules! actor_command_interface {
(impl $type_name:ident {
$(
pub fn $fn_name:ident(&$($self_:ident)+ $(, $arg_name:ident:$arg_type:ty)* $(,)?)
$body:block
)+
}) => {
$(crate::implementation::utils::actor::command_function!($type_name, pub fn $fn_name(&$($self_)+ $(, $arg_name:$arg_type)*) $body );)+
};
}
pub(crate) use actor_command_interface;
#[cfg(test)]
mod tests {
use super::*;
pub struct MyData {
data: u8,
}
actor_mailbox_interface!(
impl MyData {
pub fn increment(&mut self, value: u8) -> u8 {
self.data += value;
self.data
}
pub fn decrement(&mut self) {
self.data -= 1;
}
pub fn try_increment(&mut self) -> DdsResult<()> {
self.data -= 1;
Ok(())
}
}
);
pub struct DataInterface(ActorAddress<MyData>);
impl DataInterface {
pub fn increment(&self, value: u8) -> DdsResult<u8> {
self.0.increment(value)
}
}
#[test]
fn actor_increment() {
let my_data = MyData { data: 0 };
let actor = spawn_actor(my_data);
let data_interface = DataInterface(actor.address().clone());
assert_eq!(data_interface.increment(10).unwrap(), 10)
}
#[test]
fn actor_already_deleted() {
let my_data = MyData { data: 0 };
let actor = spawn_actor(my_data);
let data_interface = DataInterface(actor.address().clone());
std::mem::drop(actor);
std::thread::sleep(std::time::Duration::from_millis(100));
assert_eq!(data_interface.increment(10), Err(DdsError::AlreadyDeleted));
}
}