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
use crate::{Id, Signal};
use futures::channel::mpsc;
use std::fmt;
use std::hash::{Hash, Hasher};
use tokio::sync::watch;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
Alive,
Done,
}
#[derive(Clone)]
pub struct Controller {
id: Id,
status_rx: watch::Receiver<Status>,
op_tx: mpsc::UnboundedSender<Signal>,
}
impl fmt::Debug for Controller {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Controller").field(&self.id).finish()
}
}
impl PartialEq for Controller {
fn eq(&self, other: &Self) -> bool {
self.id.eq(&other.id)
}
}
impl Eq for Controller {}
impl Hash for Controller {
fn hash<H: Hasher>(&self, state: &mut H)
where
Self: Sized,
{
self.id.hash(state);
}
}
impl Controller {
pub(super) fn new(
id: Id,
status_rx: watch::Receiver<Status>,
op_tx: mpsc::UnboundedSender<Signal>,
) -> Self {
Self {
id,
status_rx,
op_tx,
}
}
pub fn id(&self) -> Id {
self.id.clone()
}
pub fn shutdown(&mut self) {
let operation = Signal::Shutdown;
self.send_op(operation);
}
pub async fn join(&mut self) {
while self.status_rx.recv().await.is_some() {
if *self.status_rx.borrow() == Status::Done {
break;
}
}
}
pub(crate) fn send_op(&mut self, operation: Signal) {
let res = self.op_tx.unbounded_send(operation);
if let Err(err) = res {
log::error!("Can't send {:?} to {:?}", err.into_inner(), self.id);
}
}
}