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
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
use std::{error, fmt, panic::catch_unwind, thread};
use {
async_io::block_on,
event_listener::Event,
flume::{bounded, unbounded, Sender, TrySendError},
futures_lite::future::pending,
once_cell::sync::Lazy,
};
#[derive(Debug)]
pub enum Error {
FullBuffer,
Stopped,
}
impl error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::FullBuffer => write!(f, "appliance buffer is full"),
Error::Stopped => write!(f, "appliance is stopped"),
}
}
}
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 struct Appliance<M> {
in_: Sender<(M, Option<Event>)>,
}
impl<'a, M: Send + 'static> Appliance<M> {
pub fn new_bounded<S: Send + 'a>(
executor: &Executor<'a>,
state: S,
handler: impl Fn(&mut S, M) + Send + 'a,
size: usize,
) -> Self {
Self::new(executor, state, handler, Some(size))
}
pub fn new_unbounded<S: Send + 'a>(
executor: &Executor<'a>,
state: S,
handler: impl Fn(&mut S, M) + Send + 'a,
) -> Self {
Self::new(executor, state, handler, None)
}
pub fn send(&self, message: M) -> Result<(), Error> {
to_result(self.in_.try_send((message, None)))
}
pub fn send_and_wait(&self, message: M) -> Result<(), Error> {
let event = Event::new();
let event_listener = event.listen();
let result = to_result(self.in_.try_send((message, Some(event))));
if result.is_ok() {
event_listener.wait();
}
result
}
fn new<S: Send + 'a>(
executor: &Executor<'a>,
mut state: S,
handler: impl Fn(&mut S, M) + Send + 'a,
size: Option<usize>,
) -> Self {
let (in_, out_) = if let Some(mbs) = size {
bounded(mbs)
} else {
unbounded()
};
let appliance = Appliance { in_ };
executor
.spawn(async move {
loop {
match out_.recv_async().await {
Ok((message, event)) => {
handler(&mut state, message);
if let Some(event) = event {
event.notify(1);
}
}
_ => return,
}
}
})
.detach();
appliance
}
}
fn to_result<T>(res: Result<(), TrySendError<T>>) -> Result<(), Error> {
match res {
Err(TrySendError::Full(_)) => Err(Error::FullBuffer),
Err(TrySendError::Disconnected(_)) => Err(Error::Stopped),
_ => Ok(()),
}
}