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
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
use async_io::block_on;
use flume::{bounded, unbounded, Sender};
use futures_lite::future::pending;
use once_cell::sync::Lazy;
use std::{
panic::catch_unwind,
process::abort,
ptr::NonNull,
sync::atomic::{AtomicUsize, Ordering},
thread,
};
const MAX_REFCOUNT: usize = (isize::MAX) as usize;
pub type Executor<'a> = async_executor::Executor<'a>;
pub static DEFAULT_EXECUTOR: Lazy<Executor<'_>> = Lazy::new(|| {
let num_threads = num_cpus::get();
for n in 1..=num_threads {
thread::Builder::new()
.name(format!("appliance-{}", n))
.spawn(|| loop {
catch_unwind(|| block_on(DEFAULT_EXECUTOR.run(pending::<()>()))).ok();
})
.expect("cannot spawn an appliance executor thread");
}
Executor::new()
});
#[derive(Debug)]
pub enum Error {
HandlingFailure,
}
#[repr(C)]
struct Inner {
strong: AtomicUsize,
}
unsafe impl Send for Inner {}
unsafe impl Sync for Inner {}
#[derive(Debug)]
pub struct Appliance<M> {
ptr: NonNull<Inner>,
messages_in: Sender<M>,
}
unsafe impl<M> Send for Appliance<M> {}
unsafe impl<M> Sync for Appliance<M> {}
impl<M> Clone for Appliance<M> {
fn clone(&self) -> Self {
let old_size = self.inner().strong.fetch_add(1, Ordering::Relaxed);
if old_size > MAX_REFCOUNT {
abort();
}
Appliance {
ptr: self.ptr,
messages_in: self.messages_in.clone(),
}
}
}
impl<M> Drop for Appliance<M> {
#[inline]
fn drop(&mut self) {
self.inner().strong.fetch_sub(1, Ordering::Release);
}
}
impl<M> Appliance<M> {
pub fn strong_count(this: &Self) -> usize {
this.inner().strong.load(Ordering::SeqCst)
}
#[inline]
fn inner(&self) -> &Inner {
unsafe { self.ptr.as_ref() }
}
}
impl<'a, M: Send + 'a> Appliance<M> {
pub fn new<S: Send + 'a>(
executor: &Executor<'a>,
mut state: S,
handler: impl Fn(&mut S, M) + Send + 'a,
message_bus_size: Option<usize>,
) -> Self {
let (messages_in, messages_out) = if let Some(mbs) = message_bus_size {
bounded(mbs)
} else {
unbounded()
};
let boxed_inner = Box::new(Inner {
strong: AtomicUsize::new(1),
});
let ptr = Box::leak(boxed_inner).into();
let appliance = Appliance { ptr, messages_in };
executor
.spawn(async move {
loop {
match messages_out.recv_async().await {
Ok(message) => handler(&mut state, message),
Err(_) => return,
}
}
})
.detach();
appliance
}
pub fn handle(&self, message: M) -> Result<(), Error> {
match self.messages_in.try_send(message) {
Err(_) => Err(Error::HandlingFailure),
Ok(_) => Ok(()),
}
}
}