-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
shutdown.rs
executable file
·78 lines (69 loc) · 2 KB
/
shutdown.rs
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
use anyhow::Result;
use std::fmt::{Debug, Formatter};
use tokio::sync::watch;
use tokio::task::JoinSet;
#[derive(Clone)]
pub struct Receiver(watch::Receiver<()>);
impl Receiver {
pub async fn recv(&mut self) {
self.0.changed().await.ok();
self.0.mark_changed();
}
pub fn is_shutting_down(&self) -> bool {
self.0.has_changed().unwrap_or(true)
}
}
impl Debug for Receiver {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Shutdown")
.field(&self.is_shutting_down())
.finish()
}
}
pub fn channel() -> (watch::Sender<()>, Receiver) {
let (tx, rx) = watch::channel(());
(tx, Receiver(rx))
}
pub async fn shutdown_task(mut tasks: JoinSet<Result<()>>, shutdown_done: watch::Sender<()>) {
while let Some(task) = tasks.join_next().await {
match task {
Ok(Ok(())) => (),
Ok(Err(error)) => {
log::error!(
"Task failed: {:?}\n{}",
error,
error.backtrace().to_string()
);
tasks.shutdown().await;
}
Err(error) => {
if error.is_cancelled() {
log::error!("Task cancelled: {}", error);
} else {
log::error!("Task panicked: {}", error);
}
tasks.shutdown().await;
}
}
}
shutdown_done.send(()).ok();
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn shutdown_channel() {
let (tx, mut rx1) = channel();
let rx2 = rx1.clone();
assert!(!rx1.is_shutting_down());
assert!(!rx2.is_shutting_down());
tx.send(()).unwrap();
rx1.recv().await;
assert!(rx1.is_shutting_down());
assert!(rx2.is_shutting_down());
assert!(rx1.is_shutting_down());
assert!(rx2.is_shutting_down());
rx1.recv().await;
assert!(rx1.is_shutting_down());
}
}