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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use std::{
    sync::{
        Arc,
        Mutex,
    },
    time::Duration,
};
use futures::{
    Future,
    future::{
        select,
        join_all,
    },
    StreamExt,
};
use loga::Log;
use tokio::{
    select,
    signal::{
        unix::{
            signal,
            SignalKind,
        },
    },
    spawn,
    sync::Notify,
    time::sleep,
    task::JoinHandle,
};
use waitgroup::WaitGroup;

struct Permanotify_ {
    fired: bool,
    notify: Arc<Notify>,
}

struct Permanotify(Mutex<Permanotify_>);

impl Permanotify {
    fn new() -> Permanotify {
        Permanotify(Mutex::new(Permanotify_ {
            fired: false,
            notify: Arc::new(Notify::new()),
        }))
    }

    async fn wait(&self) {
        let p = {
            let p = self.0.lock().unwrap();
            if p.fired {
                return;
            }
            p.notify.clone()
        };
        p.notified().await
    }

    fn yes(&self) -> bool {
        return !self.0.lock().unwrap().fired;
    }

    fn no(&self) {
        let mut p = self.0.lock().unwrap();
        p.fired = true;
        p.notify.notify_waiters();
    }
}

struct TaskManagerInner {
    alive: Permanotify,
    critical: Mutex<Option<Vec<JoinHandle<Result<(), loga::Error>>>>>,
    wg: Mutex<Option<WaitGroup>>,
}

#[derive(Clone)]
pub struct TaskManager(Arc<TaskManagerInner>);

impl TaskManager {
    pub fn new() -> TaskManager {
        let tm = TaskManager(Arc::new(TaskManagerInner {
            alive: Permanotify::new(),
            critical: Mutex::new(Some(Vec::new())),
            wg: Mutex::new(Some(WaitGroup::new())),
        }));
        let tm1 = tm.clone();
        spawn(async move {
            let mut sig1 = signal(SignalKind::interrupt()).unwrap();
            let mut sig2 = signal(SignalKind::terminate()).unwrap();
            match tm1.if_alive(select(Box::pin(sig1.recv()), Box::pin(sig2.recv()))).await {
                Some(_) => {
                    println!("Got signal, terminating.");
                    tm1.terminate();
                },
                None => { },
            };
        });
        tm
    }

    /// Create a sub-taskmanager, which can be independently terminated but will be
    /// stopped automatically when the parent task manager is terminated.  The log is
    /// used to provide context to the the child's join within the parent's management.
    pub fn sub(&self, log: Log) -> TaskManager {
        let tm = Self::new();
        let tm_child = tm.clone();
        let tm_parent = self.clone();
        self.critical_task(async move {
            select!{
                _ = tm_child.until_terminate() => {
                },
                _ = tm_parent.until_terminate() => {
                    tm_child.terminate();
                    tm_child.join(log).await?;
                },
            };

            let r: Result<(), loga::Error> = Ok(());
            r
        });
        tm
    }

    /// Wait until graceful shutdown is initiated (doesn't wait for all tasks to
    /// finish; use join for that).
    pub async fn until_terminate(&self) {
        self.0.alive.wait().await;
    }

    /// Wraps a future and cancels it if a graceful shutdown is initiated. If the
    /// cancel occurs, returns None, otherwise Some(original future return).
    pub async fn if_alive<O, T: Future<Output = O> + Send>(&self, future: T) -> Option<O> {
        let n = self.0.alive.wait();

        select!{
            _ = n => None,
            v = future => Some(v),
        }
    }

    /// Runs a future in the background, and terminates the manager when it exits.
    /// Callers should clone the task manager and use`if_alive` for any long `.await`s
    /// within the future so that the task is aborted if shutdown is initiated.
    pub fn critical_task<T, E>(&self, future: T)
    where
        E: Into<loga::Error>,
        T: Future<Output = Result<(), E>> + Send + 'static {
        self.0.critical.lock().unwrap().as_mut().unwrap().push(spawn(async move {
            future.await.map_err(|e| loga::errors("Critical task exited with error", vec![e.into()]))
        }));
    }

    /// Runs a future in the background. Callers should clone the task manager and
    /// use`if_alive` for any long `.await`s within the future so that the task is
    /// aborted if shutdown is initiated.
    pub fn task<T>(&self, future: T)
    where
        T: Future<Output = ()> + Send + 'static {
        let w = match self.0.wg.lock().unwrap().as_ref() {
            Some(w) => w.worker(),
            None => {
                return;
            },
        };
        spawn(async move {
            let _w = w;
            future.await;
        });
    }

    /// Calls f with a sleep of period between invocations.  There's no concept of
    /// missed invocations.
    pub fn periodic<
        F: FnMut() -> T + Send + 'static,
        T: Future<Output = ()> + Send + 'static,
    >(&self, period: Duration, mut f: F) {
        let tm0 = self.clone();
        let manager = self.clone();
        spawn(async move {
            loop {
                let _w = match tm0.0.wg.lock().unwrap().as_ref() {
                    Some(w) => w.worker(),
                    None => break,
                };
                f().await;
                drop(_w);
                let n = manager.0.alive.wait();

                select!{
                    _ = n => {
                        break;
                    }
                    _ = sleep(period) => {
                    }
                };
            }
        });
    }

    /// Calls handler for each element in stream, until the stream ends or the graceful
    /// shutdown is initiated.
    pub fn stream<
        T,
        S: StreamExt<Item = T> + Send + 'static + Unpin,
        Hn: FnMut(T) -> F + Send + 'static,
        F: Future<Output = ()> + Send + 'static,
    >(&self, mut stream: S, mut handler: Hn) {
        let tm0 = self.clone();
        let manager = self.clone();
        spawn(async move {
            loop {
                // Convoluted to work around poor rust lifetime analysis
                // https://github.com/rust-lang/rust/issues/63768
                let n = manager.0.alive.wait();
                let f = {
                    let e = select!{
                        _ = n => {
                            break;
                        }
                        e = stream.next() => {
                            e
                        }
                    };
                    match e {
                        Some(x) => handler(x),
                        None => break,
                    }
                };
                let _w = match tm0.0.wg.lock().unwrap().as_ref() {
                    Some(w) => w.worker(),
                    None => break,
                };
                f.await;
                drop(_w);
            }
        });
    }

    /// Initiates a graceful shutdown. Doesn't block.
    pub fn terminate(&self) {
        self.0.alive.no();
    }

    /// Check if the task manager has requested shutdown.
    pub fn alive(&self) -> bool {
        return self.0.alive.yes();
    }

    /// Waits for all internal managed activities to exit. Critical tasks cannot be
    /// started after this is called.  The log is used to provide context to errors
    /// while shutting down.
    pub async fn join(self, log: Log) -> Result<(), loga::Error> {
        let critical_tasks = self.0.critical.lock().unwrap().take().unwrap();
        let errs = join_all(critical_tasks).await.into_iter().filter_map(|r| match r {
            Ok(r) => match r {
                Ok(_) => None,
                Err(e) => Some(e),
            },
            Err(e) => Some(loga::err!(log, "Critical task panicked", err = e)),
        }).collect::<Vec<loga::Error>>();
        loga::log_debug!(log, "Join, done waiting on critical tasks");
        let wg = self.0.wg.lock().unwrap().take().unwrap();
        loga::log_debug!(log, "Join, done waiting on wait group");
        wg.wait().await;
        if !errs.is_empty() {
            return Err(loga::errors("The task manager exited after critical tasks failed", errs));
        }
        loga::log_debug!(log, "Join, done");
        return Ok(())
    }
}