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
use crate::worker::Error as WorkerError;
use futures::channel::oneshot;
use log::error;
use thiserror::Error;
use std::future::Future;
#[derive(Error, Debug)]
pub enum Error {
#[error("Sending the shutdown signal to a worker failed.")]
SendingShutdownSignalFailed,
#[error("Waiting for worker to shut down failed.")]
WaitingforWorkerShutdownFailed(#[from] WorkerError),
}
pub type ShutdownNotifier = oneshot::Sender<()>;
pub type ShutdownListener = oneshot::Receiver<()>;
pub type WorkerShutdown = Box<dyn Future<Output = Result<(), WorkerError>> + Unpin>;
pub type Action = Box<dyn FnOnce()>;
#[derive(Default)]
pub struct Shutdown {
notifiers: Vec<ShutdownNotifier>,
worker_shutdowns: Vec<WorkerShutdown>,
actions: Vec<Action>,
}
impl Shutdown {
pub fn new() -> Self {
Self::default()
}
pub fn add_worker_shutdown(
&mut self,
notifier: ShutdownNotifier,
worker: impl Future<Output = Result<(), WorkerError>> + Unpin + 'static,
) {
self.notifiers.push(notifier);
self.worker_shutdowns.push(Box::new(worker));
}
pub fn add_action(&mut self, action: impl FnOnce() + 'static) {
self.actions.push(Box::new(action));
}
pub async fn execute(mut self) -> Result<(), Error> {
while let Some(notifier) = self.notifiers.pop() {
notifier.send(()).map_err(|_| Error::SendingShutdownSignalFailed)?
}
while let Some(worker_shutdown) = self.worker_shutdowns.pop() {
if let Err(e) = worker_shutdown.await {
error!("Awaiting worker failed: {:?}.", e);
}
}
while let Some(action) = self.actions.pop() {
action();
}
Ok(())
}
}