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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) enum CallbackType {
    AfterRestart,
    AfterStop,
    BeforeRestart,
    BeforeStart,
}

#[derive(Default, Clone)]
/// A set of methods that will get called at different states of
/// a [`Supervisor`] or [`Children`] life.
///
/// # Example
///
/// ```rust
/// # use bastion::prelude::*;
/// #
/// # Bastion::init();
/// #
/// Bastion::children(|children| {
///     let callbacks = Callbacks::new()
///         .with_before_start(|| println!("Children group started."))
///         .with_after_stop(|| println!("Children group stopped."));
///
///     children
///         .with_callbacks(callbacks)
///         .with_exec(|ctx| {
///             // -- Children group started.
///             async move {
///                 // ...
///                 # Ok(())
///             }
///             // -- Children group stopped.
///         })
/// }).expect("Couldn't create the children group.");
/// #
/// # Bastion::start();
/// # Bastion::stop();
/// # Bastion::block_until_stopped();
/// ```
///
/// [`Supervisor`]: supervisor/struct.Supervisor.html
/// [`Children`]: children/struct.Children.html
pub struct Callbacks {
    before_start: Option<Arc<dyn Fn() + Send + Sync>>,
    before_restart: Option<Arc<dyn Fn() + Send + Sync>>,
    after_restart: Option<Arc<dyn Fn() + Send + Sync>>,
    after_stop: Option<Arc<dyn Fn() + Send + Sync>>,
}

impl Callbacks {
    /// Creates a new instance of `Callbacks` for
    /// [`Supervisor::with_callbacks`] or [`Children::with_callbacks`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # Bastion::init();
    /// #
    /// Bastion::children(|children| {
    ///     let callbacks = Callbacks::new()
    ///         .with_before_start(|| println!("Children group started."))
    ///         .with_after_stop(|| println!("Children group stopped."));
    ///
    ///     children
    ///         .with_callbacks(callbacks)
    ///         .with_exec(|ctx| {
    ///             // -- Children group started.
    ///             async move {
    ///                 // ...
    ///                 # Ok(())
    ///             }
    ///             // -- Children group stopped.
    ///         })
    /// }).expect("Couldn't create the children group.");
    /// #
    /// # Bastion::start();
    /// # Bastion::stop();
    /// # Bastion::block_until_stopped();
    /// ```
    ///
    /// [`Supervisor::with_callbacks`]: supervisor/struct.Supervisor.html#method.with_callbacks
    /// [`Children::with_callbacks`]: children/struct.Children.html#method.with_callbacks
    pub fn new() -> Self {
        Callbacks::default()
    }

    /// Sets the method that will get called before the [`Supervisor`]
    /// or [`Children`] is launched if:
    /// - it was never called before
    /// - or the supervisor of the supervised element using this callback
    ///     (or the system) decided to restart it and it was already
    ///     stopped or killed
    /// - or the supervisor of the supervised element using this callback
    ///     (or the system) decided to restart it and it wasn't already
    ///     stopped or killed but did not have a callback defined using
    ///     [`with_after_restart`]
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # Bastion::init();
    /// #
    /// # Bastion::supervisor(|supervisor| {
    /// supervisor.children(|children| {
    ///     let callbacks = Callbacks::new()
    ///         .with_before_start(|| println!("Children group started."))
    ///         .with_before_restart(|| println!("Children group restarting."))
    ///         .with_after_restart(|| println!("Children group restarted."))
    ///         .with_after_stop(|| println!("Children group stopped."));
    ///
    ///     children
    ///         .with_exec(|ctx| {
    ///             // -- Children group started.
    ///             async move {
    ///                 // ...
    ///
    ///                 // This will stop the children group...
    ///                 Ok(())
    ///                 // Note that because the children group stopped by itself,
    ///                 // if its supervisor restarts it, its `before_start` callback
    ///                 // will get called and not `after_restart`.
    ///             }
    ///             // -- Children group stopped.
    ///         })
    ///         .with_callbacks(callbacks)
    /// })
    /// # }).unwrap();
    /// #
    /// # Bastion::start();
    /// # Bastion::stop();
    /// # Bastion::block_until_stopped();
    /// ```
    ///
    /// [`Supervisor`]: supervisor/struct.Supervisor.html
    /// [`Children`]: children/struct.Children.html
    /// [`with_after_restart`]: #method.with_after_start
    pub fn with_before_start<C>(mut self, before_start: C) -> Self
    where
        C: Fn() + Send + Sync + 'static,
    {
        let before_start = Arc::new(before_start);
        self.before_start = Some(before_start);
        self
    }

    /// Sets the method that will get called before the [`Supervisor`]
    /// or [`Children`] is reset if:
    /// - the supervisor of the supervised element using this callback
    ///     (or the system) decided to restart it and it wasn't already
    ///     stopped or killed
    ///
    /// Note that if this callback isn't defined but one was defined using
    /// [`with_after_stop`], it will get called instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # Bastion::init();
    /// #
    /// # Bastion::supervisor(|supervisor| {
    /// supervisor.children(|children| {
    ///     let callbacks = Callbacks::new()
    ///         .with_before_start(|| println!("Children group started."))
    ///         .with_before_restart(|| println!("Children group restarting."))
    ///         .with_after_restart(|| println!("Children group restarted."))
    ///         .with_after_stop(|| println!("Children group stopped."));
    ///
    ///     children
    ///         .with_exec(|ctx| {
    ///             // Once -- Children group started.
    ///             // and then -- Children group restarted.
    ///             async move {
    ///                 // ...
    ///
    ///                 // This will make the children group fault and get
    ///                 // restarted by its supervisor...
    ///                 Err(())
    ///             }
    ///             // -- Children group restarting.
    ///             // Note that if a `before_restart` wasn't specified for
    ///             // this children group, `after_stop` would get called
    ///             // instead.
    ///         })
    ///         .with_callbacks(callbacks)
    /// })
    /// # }).unwrap();
    /// #
    /// # Bastion::start();
    /// # Bastion::stop();
    /// # Bastion::block_until_stopped();
    /// ```
    ///
    /// [`Supervisor`]: supervisor/struct.Supervisor.html
    /// [`Children`]: children/struct.Children.html
    /// [`with_after_stop`]: #method.with_after_stop
    pub fn with_before_restart<C>(mut self, before_restart: C) -> Self
    where
        C: Fn() + Send + Sync + 'static,
    {
        let before_restart = Arc::new(before_restart);
        self.before_restart = Some(before_restart);
        self
    }

    /// Sets the method that will get called before the [`Supervisor`]
    /// or [`Children`] is launched if:
    /// - the supervisor of the supervised element using this callback
    ///     (or the system) decided to restart it and it wasn't already
    ///     stopped or killed
    ///
    /// Note that if this callback isn't defined but one was defined using
    /// [`with_before_start`], it will get called instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # Bastion::init();
    /// #
    /// # Bastion::supervisor(|supervisor| {
    /// supervisor.children(|children| {
    ///     let callbacks = Callbacks::new()
    ///         .with_before_start(|| println!("Children group started."))
    ///         .with_before_restart(|| println!("Children group restarting."))
    ///         .with_after_restart(|| println!("Children group restarted."))
    ///         .with_after_stop(|| println!("Children group stopped."));
    ///
    ///     children
    ///         .with_exec(|ctx| {
    ///             // Once -- Children group started.
    ///             // and then -- Children group restarted.
    ///             // Note that if a `after_restart` callback wasn't specified
    ///             // for this children group, `before_restart` would get called
    ///             // instead.
    ///             async move {
    ///                 // ...
    ///
    ///                 // This will make the children group fault and get
    ///                 // restarted by its supervisor...
    ///                 Err(())
    ///             }
    ///             // -- Children group restarting.
    ///         })
    ///         .with_callbacks(callbacks)
    /// })
    /// # }).unwrap();
    /// #
    /// # Bastion::start();
    /// # Bastion::stop();
    /// # Bastion::block_until_stopped();
    /// ```
    ///
    /// [`Supervisor`]: supervisor/struct.Supervisor.html
    /// [`Children`]: children/struct.Children.html
    /// [`with_before_start`]: #method.with_before_start
    pub fn with_after_restart<C>(mut self, after_restart: C) -> Self
    where
        C: Fn() + Send + Sync + 'static,
    {
        let after_restart = Arc::new(after_restart);
        self.after_restart = Some(after_restart);
        self
    }

    /// Sets the method that will get called after the [`Supervisor`]
    /// or [`Children`] is stopped or killed if:
    /// - the supervisor of the supervised element using this callback
    ///     (or the system) decided to stop (not restart nor kill) it and
    ///     it wasn't already stopped or killed
    /// - or the supervisor or children group using this callback
    ///     stopped or killed itself or was stopped or killed by a
    ///     reference to it
    /// - or the supervisor of the supervised element using this callback
    ///     (or the system) decided to restart it and it wasn't already
    ///     stopped or killed but did not have a callback defined using
    ///     [`with_before_restart`]
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # Bastion::init();
    /// #
    /// # Bastion::supervisor(|supervisor| {
    /// supervisor.children(|children| {
    ///     let callbacks = Callbacks::new()
    ///         .with_before_start(|| println!("Children group started."))
    ///         .with_before_restart(|| println!("Children group restarting."))
    ///         .with_after_restart(|| println!("Children group restarted."))
    ///         .with_after_stop(|| println!("Children group stopped."));
    ///
    ///     children
    ///         .with_exec(|ctx| {
    ///             // -- Children group started.
    ///             async move {
    ///                 // ...
    ///
    ///                 // This will stop the children group...
    ///                 Ok(())
    ///             }
    ///             // -- Children group stopped.
    ///             // Note that because the children group stopped by itself,
    ///             // it its supervisor restarts it, its `before_restart` callback
    ///             // will not get called.
    ///         })
    ///         .with_callbacks(callbacks)
    /// })
    /// # }).unwrap();
    /// #
    /// # Bastion::start();
    /// # Bastion::stop();
    /// # Bastion::block_until_stopped();
    /// ```
    ///
    /// [`Supervisor`]: supervisor/struct.Supervisor.html
    /// [`Children`]: children/struct.Children.html
    /// [`with_before_restart`]: #method.with_before_restart
    pub fn with_after_stop<C>(mut self, after_stop: C) -> Self
    where
        C: Fn() + Send + Sync + 'static,
    {
        let after_stop = Arc::new(after_stop);
        self.after_stop = Some(after_stop);
        self
    }

    /// Returns whether a callback was defined using [`with_before_start`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// let callbacks = Callbacks::new()
    ///     .with_before_start(|| println!("Children group started."));
    ///
    /// assert!(callbacks.has_before_start());
    /// ```
    ///
    /// [`with_before_start`]: #method.with_before_start
    pub fn has_before_start(&self) -> bool {
        self.before_start.is_some()
    }

    /// Returns whether a callback was defined using [`with_before_restart`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// let callbacks = Callbacks::new()
    ///     .with_before_restart(|| println!("Children group restarting."));
    ///
    /// assert!(callbacks.has_before_restart());
    /// ```
    ///
    /// [`with_before_restart`]: #method.with_before_restart
    pub fn has_before_restart(&self) -> bool {
        self.before_restart.is_some()
    }

    /// Returns whether a callback was defined using [`with_after_restart`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// let callbacks = Callbacks::new()
    ///     .with_after_restart(|| println!("Children group restarted."));
    ///
    /// assert!(callbacks.has_after_restart());
    /// ```
    ///
    /// [`with_after_restart`]: #method.with_after_restart
    pub fn has_after_restart(&self) -> bool {
        self.after_restart.is_some()
    }

    /// Returns whether a callback was defined using [`with_after_stop`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// let callbacks = Callbacks::new()
    ///     .with_after_stop(|| println!("Children group stopped."));
    ///
    /// assert!(callbacks.has_after_stop());
    /// ```
    ///
    /// [`with_after_stop`]: #method.with_after_stop
    pub fn has_after_stop(&self) -> bool {
        self.after_stop.is_some()
    }

    pub(crate) fn before_start(&self) {
        if let Some(before_start) = &self.before_start {
            before_start()
        }
    }

    pub(crate) fn before_restart(&self) {
        if let Some(before_restart) = &self.before_restart {
            before_restart()
        } else {
            self.after_stop()
        }
    }

    pub(crate) fn after_restart(&self) {
        if let Some(after_restart) = &self.after_restart {
            after_restart()
        } else {
            self.before_start()
        }
    }

    pub(crate) fn after_stop(&self) {
        if let Some(after_stop) = &self.after_stop {
            after_stop()
        }
    }
}

impl Debug for Callbacks {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        fmt.debug_struct("Callbacks")
            .field("before_start", &self.before_start.is_some())
            .field("before_restart", &self.before_start.is_some())
            .field("after_restart", &self.before_start.is_some())
            .field("after_stop", &self.before_start.is_some())
            .finish()
    }
}