-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsignal.rs
More file actions
73 lines (63 loc) · 2.23 KB
/
Copy pathsignal.rs
File metadata and controls
73 lines (63 loc) · 2.23 KB
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
use snafu::{ResultExt, Snafu};
use tokio::{
signal::unix::{SignalKind, signal},
sync::watch,
};
#[derive(Debug, Snafu)]
#[snafu(display("failed to construct signal watcher"))]
pub struct SignalError {
source: std::io::Error,
}
/// Watches for the incoming signal and multiplies it by sending it to all acquired handles.
pub struct SignalWatcher<T>
where
T: Send + Sync + 'static,
{
watch_rx: watch::Receiver<T>,
}
impl<T> SignalWatcher<T>
where
T: Default + Send + Sync + 'static,
{
/// Watches the provided `signal` and multiplies the signal by sending it to all acquired handles
/// constructed through [`SignalWatcher::handle`].
pub fn new<F>(signal: F) -> Self
where
F: Future<Output = T> + Send + Sync + 'static,
{
let (watch_tx, watch_rx) = watch::channel(T::default());
tokio::spawn(async move {
let value = signal.await;
watch_tx.send(value)
});
Self { watch_rx }
}
/// Acquire a new handle which will complete once a `SIGTERM` signal is received.
///
/// This handle can be cheaply cloned to be able to gracefully shutdown multiple concurrent
/// tasks.
pub fn handle(&self) -> impl Future<Output = ()> + use<T> {
let mut watch_rx = self.watch_rx.clone();
async move {
watch_rx.changed().await.ok();
}
}
}
impl SignalWatcher<()> {
/// Watches the `SIGTERM` signal and multiplies the signal by sending it to all acquired handlers
/// constructed through [`SignalWatcher::handle`].
//
// NOTE (@Techassi): Note Accepting a generic Future<Output = ()> here is possible, but
// `Signal::recv` borrows instead of consuming which clashes with the 'static lifetime
// requirement of `tokio::spawn`. That's why I opted for watching for a particular signal
// internally instead of requiring users to pass the signal to this function.
pub fn sigterm() -> Result<Self, SignalError> {
let mut sigterm = signal(SignalKind::terminate()).context(SignalSnafu)?;
let (watch_tx, watch_rx) = watch::channel(());
tokio::spawn(async move {
sigterm.recv().await;
watch_tx.send(())
});
Ok(Self { watch_rx })
}
}