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
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use async_trait::async_trait;
use tokio::signal;
use tokio::signal::unix::SignalKind;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::time::error::Elapsed;
pub type BoxedStop = Box<dyn Stop>;
pub type BoxedLifecycle = Box<dyn Lifecycle<S = BoxedStop>>;
#[async_trait]
pub trait Stop: Send {
async fn stop(self);
fn boxed(self) -> BoxedStop
where
Self: Sized + 'static,
{
Box::new(self)
}
}
#[async_trait]
pub trait Lifecycle: Send + 'static {
type S: Stop;
async fn start(self) -> Self::S;
fn boxed(self) -> BoxedLifecycle
where
Self: Sized,
{
Box::new(move || async move { self.start().await.boxed() })
}
}
#[async_trait]
impl Lifecycle for BoxedLifecycle {
type S = Box<dyn Stop>;
async fn start(self) -> Self::S {
Box::new(self.start().await)
}
}
#[async_trait]
impl Stop for BoxedStop {
async fn stop(self) {
self.stop().await;
}
}
pub fn seq<A, B>(a: A, b: B) -> impl Lifecycle
where
A: Lifecycle,
B: Lifecycle,
{
lifecycle!(state, { (a.start().await, b.start().await) }, {
let (a_stop, b_stop) = state;
b_stop.stop().await;
a_stop.stop().await;
})
}
pub fn parallel<A, B>(a: A, b: B) -> impl Lifecycle
where
A: Lifecycle,
B: Lifecycle,
{
lifecycle!(state, { tokio::join!(a.start(), b.start()) }, {
let (a_stop, b_stop) = state;
let _ = tokio::join!(a_stop.stop(), b_stop.stop());
})
}
#[macro_export]
macro_rules! parallel {
($x:expr $(,)?) => ($x);
($x:expr, $($y:expr),+ $(,)?) => (
simple_life::parallel($x, simple_life::parallel!($($y),+))
)
}
#[macro_export]
macro_rules! seq {
($x:expr $(,)?) => ($x);
($x:expr, $($y:expr),+ $(,)?) => (
simple_life::seq($x, simple_life::seq!($($y),+))
)
}
#[macro_export]
macro_rules! lifecycle {
(mut $state:ident, $start:block, $stop:block) => {
move || async move {
let mut $state = $start;
move || async move { $stop }
}
};
($state:ident, $start:block, $stop:block) => {
move || async move {
let $state = $start;
move || async move { $stop }
}
};
($start:block, $stop:block) => {
simple_life::lifecycle!(_state, $start, $stop)
};
}
#[macro_export]
macro_rules! start {
($x:block) => {
simple_life::lifecycle!($x, {})
};
}
#[macro_export]
macro_rules! stop {
($x:block) => {
simple_life::lifecycle!({}, $x)
};
}
#[async_trait]
impl<F, R, O> Lifecycle for F
where
F: FnOnce() -> R + 'static + Send,
R: Future<Output = O> + Send,
O: Stop,
{
type S = O;
async fn start(self) -> Self::S {
self().await
}
}
#[async_trait]
impl<F, R> Stop for F
where
F: FnOnce() -> R + Send,
R: Future<Output = ()> + Send,
{
async fn stop(self) {
self().await
}
}
pub fn spawn_interval<S, F, R>(s: S, period: Duration, fun: F) -> impl Lifecycle
where
S: Clone + 'static + Send + Sync,
F: Fn(S) -> R + Send + Sync + 'static,
R: Future<Output = ()> + Send,
{
spawn_with_shutdown(move |mut sig| async move {
let sleep = tokio::time::sleep(period);
tokio::pin!(sleep);
loop {
tokio::select! {
_ = &mut sleep => {
fun(s.clone()).await;
sleep.as_mut().reset(tokio::time::Instant::now() + period);
},
_ = &mut sig => {
return;
}
}
}
})
}
pub struct ShutdownSignal(tokio::sync::oneshot::Receiver<()>);
impl Future for ShutdownSignal {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.0).poll(cx).map(|r| r.unwrap())
}
}
pub fn spawn_with_shutdown<F, R>(fun: F) -> impl Lifecycle
where
F: FnOnce(ShutdownSignal) -> R + Send + 'static,
R: Future<Output = ()> + Send,
{
lifecycle!(
chans,
{
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
let jh = tokio::spawn(async move {
let _ = fun(ShutdownSignal(shutdown_rx)).await;
});
(shutdown_tx, jh)
},
{
let (shutdown_tx, jh) = chans;
shutdown_tx.send(()).unwrap();
let _ = jh.await;
}
)
}
pub async fn run_until_shutdown_sig(
life: impl Lifecycle,
timeout: Duration,
) -> Result<(), Elapsed> {
let stopper = life.start().await;
std_unix_shutdown_sigs().await;
tokio::time::timeout(timeout, stopper.stop()).await
}
async fn std_unix_shutdown_sigs() {
let mut kill_sig = signal::unix::signal(SignalKind::terminate()).unwrap();
tokio::select! {
_ = signal::ctrl_c() => {},
_ = kill_sig.recv() => {},
}
}
#[derive(Clone)]
pub struct LazyStarter {
tx: Sender<Box<dyn Lifecycle<S = Box<dyn Stop>>>>,
}
impl LazyStarter {
fn new() -> (impl Lifecycle, LazyStarter) {
let (tx, rx) = tokio::sync::mpsc::channel(5);
(LazyStarter::lifecycle(rx), LazyStarter { tx })
}
fn lifecycle(mut rx: Receiver<BoxedLifecycle>) -> impl Lifecycle {
spawn_with_shutdown(|sig| async move {
let mut stoppers = vec![];
tokio::pin!(sig);
loop {
tokio::select! {
_ = &mut sig => {
break;
},
lc = rx.recv() => {
if let Some(lc) = lc {
stoppers.push(lc.start().await);
} else {
break;
}
},
}
}
let _ = sig.await;
if let Some(fut) = stoppers.into_iter().map(Stop::stop).reduce(|a, b| {
Box::pin(async {
tokio::join!(a, b);
})
}) {
fut.await;
}
})
}
pub async fn start(&self, life: impl Lifecycle) {
let _ = self.tx.send(life.boxed()).await;
}
}
pub fn lazy_start() -> (impl Lifecycle, LazyStarter) {
LazyStarter::new()
}
#[derive(Eq, PartialEq, Debug)]
pub struct NoStop;
#[async_trait]
impl Stop for NoStop {
async fn stop(self) {}
}