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
use futures::{
channel::{
mpsc::{channel, Receiver, Sender},
oneshot::{
channel as one_shot_channel, Receiver as OneShotReceiver, Sender as OneShotSender,
},
},
lock::Mutex,
sink::SinkExt,
};
use std::{
hash::{Hash, Hasher},
sync::Arc,
};
use tokio::sync::watch::{
channel as watchChannel, Receiver as WatchReceiver, Sender as WatchSender,
};
#[derive(Debug)]
pub enum ResourceStatus {
Dead,
}
type TaskID = usize;
pub type ResourceStatusSender = Sender<ResourceStatus>;
#[derive(Clone)]
pub struct TaskManager<Context> {
task_id: TaskID,
dependency_tx: ResourceStatusSender,
readiness_tx: Arc<Mutex<Option<OneShotSender<()>>>>,
termination_rx: WatchReceiver<Option<()>>,
pub context: Context,
}
pub type JobManager = TaskManager<()>;
impl<Context> TaskManager<Context> {
pub fn new(
task_id: TaskID,
context: Context,
) -> (
Self,
Receiver<ResourceStatus>,
OneShotReceiver<()>,
WatchSender<Option<()>>,
) {
let (dependency_tx, dependency_rx) = channel(16);
let (readiness_tx, readiness_rx) = one_shot_channel();
let (termination_tx, termination_rx) = watchChannel(None);
let manager = Self {
task_id,
dependency_tx,
readiness_tx: Arc::new(Mutex::new(Some(readiness_tx))),
termination_rx,
context,
};
(manager, dependency_rx, readiness_rx, termination_tx)
}
pub fn create_resource_handle(&self) -> TaskResourceHandle {
TaskResourceHandle {
task_id: self.task_id,
dependency_tx: self.dependency_tx.clone(),
}
}
pub fn termination_signal(&self) -> impl futures::Future<Output = ()> {
let mut rx = self.termination_rx.clone();
async move {
rx.changed().await.ok();
}
}
pub fn termination_signal_triggered(&self) -> bool {
*self.termination_rx.borrow() == Some(())
}
pub async fn ready(&self) {
if let Some(tx) = self.readiness_tx.lock().await.take() {
tx.send(()).ok();
}
}
}
#[derive(Clone)]
pub struct TaskResourceHandle {
task_id: TaskID,
dependency_tx: ResourceStatusSender,
}
impl TaskResourceHandle {
pub fn stub() -> Self {
let (dependency_tx, _) = channel(0);
Self {
task_id: 0,
dependency_tx,
}
}
pub async fn resource_died(&mut self) {
self.dependency_tx.send(ResourceStatus::Dead).await.ok();
}
}
impl PartialEq for TaskResourceHandle {
fn eq(&self, other: &Self) -> bool {
self.task_id == other.task_id
}
}
impl Eq for TaskResourceHandle {}
impl Hash for TaskResourceHandle {
fn hash<H: Hasher>(&self, state: &mut H) {
self.task_id.hash(state);
}
}