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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
use std::marker::PhantomData;

use crate::ap::handlers::{DeferredRequest, Request};
use crate::ap::{
    AbstractProcess, Config, DeferredRequestHandler, DeferredResponse, ProcessRef, RequestHandler,
    State,
};
use crate::function::process::{process_name, ProcessType};
use crate::serializer::Bincode;
use crate::{host, Tag};

/// A `Supervisor` can detect failures (panics) inside
/// [`AbstractProcesses`](AbstractProcess) and restart them.
///
/// # Example
///
/// ```
/// struct Sup;
/// impl Supervisor for Sup {
///     type Arg = ();
///     // Start 3 `Counters` and monitor them for failures.
///     type Children = (Counter, Counter, Counter);
///
///     fn init(config: &mut SupervisorConfig<Self>, _: ()) {
///         // If a child fails, just restart it.
///         config.set_strategy(SupervisorStrategy::OneForOne);
///         // Start each `Counter` with a state of `0` & name last child "hello".
///         config.children_args((0, None),(0, None),(0, "hello".to_owned()));
///     }
/// }
///
/// let sup = Sup::start((), None);
/// let children = sup.children();
/// let count1 = children.2.request(Count);
/// // Get reference to named child.
/// let hello = ProcessRef::<Counter>::lookup("hello").unwrap();
/// let count2 = hello.request(Count);
/// assert_eq!(count1, count2);
/// ```
pub trait Supervisor
where
    Self: Sized,
{
    /// The argument received by the `init` function.
    ///
    /// This argument is sent from the parent to the child and needs to be
    /// serializable.
    type Arg: serde::Serialize + serde::de::DeserializeOwned;

    /// A tuple of types that implement `AbstractProcess`.
    ///
    /// They will be spawned as children. This can also include other
    /// supervisors.
    type Children: Supervisable<Self>;

    /// Entry function of the supervisor.
    ///
    /// It's used to configure the supervisor. The function
    /// `config.children_args()` must be called to provide arguments & names
    /// for children. If it's not called the supervisor will panic.
    fn init(config: &mut SupervisorConfig<Self>, arg: Self::Arg);
}

impl<T> AbstractProcess for T
where
    T: Supervisor,
{
    type Arg = T::Arg;
    type State = SupervisorConfig<T>;
    type Serializer = Bincode;
    type Handlers = (Request<GetChildren>, DeferredRequest<ShutdownSubscribe>);
    type StartupError = ();

    fn init(config: Config<Self>, arg: T::Arg) -> Result<Self::State, ()> {
        // Supervisor shouldn't die if the children die
        config.die_if_link_dies(false);

        let mut sup_config = SupervisorConfig::default();
        <T as Supervisor>::init(&mut sup_config, arg);

        // Check if children arguments are configured inside of supervisor's `init`
        // call.
        if sup_config.children_args.is_none() {
            panic!(
                "SupervisorConfig<{0}>::children_args not set inside `{0}:init` function.",
                std::any::type_name::<T>()
            );
        }

        sup_config.start_link();

        Ok(sup_config)
    }

    fn terminate(config: SupervisorConfig<T>) {
        config.terminate();
    }

    fn handle_link_death(mut sup_config: State<Self>, tag: Tag) {
        T::Children::handle_failure(&mut sup_config, tag);
    }
}

impl<T> ProcessRef<T>
where
    T: Supervisor,
    T: AbstractProcess<State = SupervisorConfig<T>, Serializer = Bincode>,
{
    /// Blocks until the Supervisor shuts down.
    ///
    /// This function will not request a shutdown, just wait until someone else
    /// shuts the supervisor down.
    ///
    /// A tagged message will be sent to the supervisor process as a request
    /// and the subscription will be registered. When the supervisor process
    /// shuts down, the subscribers will be each notified by a response
    /// message and therefore be unblocked after having received the awaited
    /// message.
    pub fn wait_on_shutdown(&self) {
        self.deferred_request(ShutdownSubscribe);
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
pub struct ShutdownSubscribe;
impl<T> DeferredRequestHandler<ShutdownSubscribe> for T
where
    T: Supervisor,
    T: AbstractProcess<State = SupervisorConfig<T>, Serializer = Bincode>,
{
    type Response = ();

    fn handle(
        mut state: State<Self>,
        _: ShutdownSubscribe,
        subscriber: DeferredResponse<(), Self>,
    ) {
        state.subscribe_shutdown(subscriber)
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
pub struct GetChildren;
impl<T> RequestHandler<GetChildren> for T
where
    T: Supervisor,
    T: AbstractProcess<State = SupervisorConfig<T>, Serializer = Bincode>,
{
    type Response = <<T as Supervisor>::Children as Supervisable<T>>::Processes;

    fn handle(state: State<Self>, _: GetChildren) -> Self::Response {
        state.get_children()
    }
}

impl<T> ProcessRef<T>
where
    T: Supervisor,
    T: AbstractProcess<State = SupervisorConfig<T>, Serializer = Bincode>,
{
    pub fn children(&self) -> <<T as Supervisor>::Children as Supervisable<T>>::Processes {
        self.request(GetChildren)
    }
}

pub enum SupervisorStrategy {
    OneForOne,
    OneForAll,
    RestForOne,
}

pub struct SupervisorConfig<T>
where
    T: Supervisor,
{
    strategy: SupervisorStrategy,
    children: Option<<<T as Supervisor>::Children as Supervisable<T>>::Processes>,
    children_args: Option<<<T as Supervisor>::Children as Supervisable<T>>::Args>,
    children_names: Option<<<T as Supervisor>::Children as Supervisable<T>>::Names>,
    children_configs: Option<<<T as Supervisor>::Children as Supervisable<T>>::Configs>,
    children_tags: Option<<<T as Supervisor>::Children as Supervisable<T>>::Tags>,
    terminate_subscribers: Vec<DeferredResponse<(), T>>,
    phantom: PhantomData<T>,
}

impl<T> SupervisorConfig<T>
where
    T: Supervisor,
{
    pub fn set_strategy(&mut self, strategy: SupervisorStrategy) {
        self.strategy = strategy;
    }

    pub fn set_args(&mut self, args: <<T as Supervisor>::Children as Supervisable<T>>::Args) {
        self.children_args = Some(args);
    }

    pub fn set_names(&mut self, names: <<T as Supervisor>::Children as Supervisable<T>>::Names) {
        self.children_names = Some(names);
    }

    pub fn set_configs(
        &mut self,
        configs: <<T as Supervisor>::Children as Supervisable<T>>::Configs,
    ) {
        self.children_configs = Some(configs);
    }

    pub(crate) fn get_children(
        &self,
    ) -> <<T as Supervisor>::Children as Supervisable<T>>::Processes {
        self.children.as_ref().unwrap().clone()
    }

    pub fn start_link(&mut self) {
        T::Children::start_links(self);
    }

    fn terminate(mut self) {
        self.terminate_subscribers
            .drain(..)
            .for_each(|sub| sub.send_response(()));
        T::Children::terminate(self);
    }

    pub(crate) fn subscribe_shutdown(&mut self, subscriber: DeferredResponse<(), T>) {
        self.terminate_subscribers.push(subscriber);
    }
}

impl<T> Default for SupervisorConfig<T>
where
    T: Supervisor,
{
    fn default() -> Self {
        SupervisorConfig {
            phantom: PhantomData,
            children: None,
            children_args: None,
            children_names: None,
            children_configs: None,
            children_tags: None,
            terminate_subscribers: vec![],
            strategy: SupervisorStrategy::OneForOne,
        }
    }
}

pub trait Supervisable<T>
where
    T: Supervisor,
{
    type Processes: serde::Serialize + serde::de::DeserializeOwned + Clone;
    type Args: Clone;
    type Names;
    type Configs;
    type Tags;

    fn start_links(config: &mut SupervisorConfig<T>);
    fn terminate(config: SupervisorConfig<T>);
    fn handle_failure(config: &mut SupervisorConfig<T>, tag: Tag);
}

// Implement Supervisable for tuples with up to 12 children.
macros::impl_supervisable!();
macros::impl_supervisable!(T0 0);
macros::impl_supervisable!(T0 0, T1 1);
macros::impl_supervisable!(T0 0, T1 1, T2 2);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10, T11 11);
macros::impl_supervisable!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10, T11 11, T12 12);

mod macros {
    // Replace any identifier with `Tag`
    macro_rules! tag {
        ($t:ident) => {
            Tag
        };
    }

    macro_rules! ignore_type {
        ($_:ident, $ret:ty) => {
            $ret
        };
    }

    macro_rules! ignore_expr {
        ($_:ident, $ret:expr) => {
            $ret
        };
    }

    macro_rules! reverse_shutdown {
        // reverse_shutdown!(config, [...]) shuts down all children in reverse order
        ($config:ident, []) => {}; // base case
        ($config:ident, [$head_i:tt $($rest_i:tt)*]) => { // recursive case
            macros::reverse_shutdown!($config, [$($rest_i)*]);
            $config.children.as_ref().unwrap().$head_i.shutdown();
        };
        // reverse_shutdown!(config, skip tag, [...]) shuts down all children with unmatched tags
        ($config:ident, skip $tag:ident, []) => {}; // base case
        ($config:ident, skip $tag:ident, [$head_i:tt $($rest_i:tt)*]) => { // recursive case
            macros::reverse_shutdown!($config, skip $tag, [$($rest_i)*]);
            if $tag != $config.children_tags.as_ref().unwrap().$head_i {
                $config.children.as_ref().unwrap().$head_i.shutdown();
            }
        };
        // reverse_shutdown!(config, after tag, [...]) shuts down the children after the tag
        ($config:ident, after $tag:ident, []) => {}; // base case
        ($config:ident, after $tag:ident, [$head_i:tt $($rest_i:tt)*]) => { // recursive case
            if $tag == $config.children_tags.as_ref().unwrap().$head_i {
                macros::reverse_shutdown!($config, [$($rest_i)*]);
            } else {
                macros::reverse_shutdown!($config, after $tag, [$($rest_i)*]);
            }
        };
    }

    macro_rules! impl_supervisable {
        ($($t:ident $i:tt),*) => {
            paste::paste! {
                impl<$($t,)* K> Supervisable<K> for ($($t,)*)
                where
                    K: Supervisor<Children = Self>,
                    $(
                        $t : AbstractProcess,
                        $t ::Arg : Clone,
                    )*
                {
                    type Processes = ($(ProcessRef<$t>,)*);
                    type Args = ($($t ::Arg,)*);
                    type Names = ($(macros::ignore_type!($t, Option<String>),)*);
                    type Configs = ($(macros::ignore_type!($t, Option<crate::ProcessConfig>),)*);
                    type Tags = ($(macros::tag!($t),)*);

                    #[allow(unused_variables)]
                    fn start_links(config: &mut SupervisorConfig<K>) {
                        let args = config.children_args.clone().unwrap();
                        let names = match &config.children_names {
                            Some(names) => names,
                            None => { &( $(macros::ignore_expr!($t, None),)* ) }
                        };
                        let configs = match &config.children_configs {
                            Some(configs) => configs,
                            None => { &( $(macros::ignore_expr!($t, None),)* ) }
                        };

                        $(
                            let [<tag$i>] = Tag::new();
                            let proc_builder = $t::link_with([<tag$i>]);
                            let proc_builder = if let Some(config) = &configs.$i {
                                proc_builder.configure(&config)
                            } else {
                                proc_builder
                            };
                            let result = match &names.$i {
                                Some(name) => proc_builder.start_as(name, args.$i),
                                None => proc_builder.start(args.$i),
                            };
                            let [<proc$i>] = match result {
                                Ok(proc) => proc,
                                Err(err) => panic!("Supervisor failed to start child `{:?}`", err),
                            };
                        )*
                        config.children = Some(($([<proc$i>],)*));
                        config.children_tags = Some(($([<tag$i>],)*));
                    }

                    #[allow(unused_variables)]
                    fn terminate(config: SupervisorConfig<K>) {
                        macros::reverse_shutdown!(config, [ $($i)* ]);
                    }

                    #[allow(unused_variables)]
                    fn handle_failure(config: &mut SupervisorConfig<K>, tag: Tag) {
                        match config.strategy {
                            // After a failure, just restart the same process.
                            SupervisorStrategy::OneForOne => {
                                $(

                                    if tag == config.children_tags.unwrap().$i {
                                        let args = config.children_args.as_ref().unwrap().$i.clone();
                                        let name = match &config.children_names {
                                            Some(names) => &names.$i,
                                            None => &None
                                        };
                                        let proc_config = match &config.children_configs {
                                            Some(configs) => &configs.$i,
                                            None => &None
                                        };

                                        let link_tag = Tag::new();
                                        let proc_builder = $t::link_with(link_tag);
                                        let proc_builder = if let Some(config) = proc_config {
                                            proc_builder.configure(&config)
                                        } else {
                                            proc_builder
                                        };
                                        let result = match &name {
                                            Some(name) => {
                                                // Remove first the previous registration
                                                let remove = process_name::<$t, $t::Serializer>(ProcessType::ProcessRef, &name);
                                                unsafe { host::api::registry::remove(remove.as_ptr(), remove.len()) };
                                                proc_builder.start_as(name, args)
                                            },
                                            None => proc_builder.start(args),
                                        };
                                        let proc = match result {
                                            Ok(proc) => proc,
                                            Err(err) => panic!("Supervisor failed to start child `{:?}`", err),
                                        };
                                        config.children.as_mut().unwrap().$i = proc;
                                        config.children_tags.as_mut().unwrap().$i = link_tag;
                                    } else

                                )*

                                {
                                    panic!(
                                        "Supervisor {} received link death signal not belonging to a child",
                                        std::any::type_name::<K>()
                                    );
                                }
                            }
                            // After a failure, restart all children
                            SupervisorStrategy::OneForAll => {
                                // check if the tag belongs to one of the children
                                $(
                                    if tag == config.children_tags.unwrap().$i { } else
                                )*
                                {
                                    panic!(
                                        "Supervisor {} received link death signal not belonging to a child",
                                        std::any::type_name::<K>()
                                    );
                                }

                                // shutdown children in reversed start order
                                macros::reverse_shutdown!(config, skip tag, [ $($i)* ]);

                                // restart all
                                $(

                                    let args = config.children_args.as_ref().unwrap().$i.clone();
                                    let name = match &config.children_names {
                                        Some(names) => &names.$i,
                                        None => &None
                                    };
                                    let proc_config = match &config.children_configs {
                                        Some(configs) => &configs.$i,
                                        None => &None
                                    };

                                    let link_tag = Tag::new();
                                    let proc_builder = $t::link_with(link_tag);
                                    let proc_builder = if let Some(config) = proc_config {
                                        proc_builder.configure(&config)
                                    } else {
                                        proc_builder
                                    };
                                    let result = match name {
                                        Some(name) => {
                                            // Remove first the previous registration
                                            let remove = process_name::<$t, $t::Serializer>(ProcessType::ProcessRef, &name);
                                            unsafe { host::api::registry::remove(remove.as_ptr(), remove.len()) };
                                            proc_builder.start_as(name, args)
                                        },
                                        None => proc_builder.start(args),
                                    };
                                    let proc = match result {
                                        Ok(proc) => proc,
                                        Err(err) => panic!("Supervisor failed to start child `{:?}`", err),
                                    };
                                    config.children.as_mut().unwrap().$i = proc;
                                    config.children_tags.as_mut().unwrap().$i = link_tag;

                                )*
                            }
                            // If a child process terminates, the rest of the child processes (that is,
                            // the child processes after the terminated process in start order)
                            // are terminated. Then the terminated child process and the rest of the
                            // child processes are restarted.
                            SupervisorStrategy::RestForOne => {
                                // check if the tag belongs to one of the children
                                $(
                                    if tag == config.children_tags.unwrap().$i { } else
                                )*
                                {
                                    panic!(
                                        "Supervisor {} received link death signal not belonging to a child",
                                        std::any::type_name::<K>()
                                    );
                                }

                                // shutdown children after the tag in reversed start order
                                macros::reverse_shutdown!(config, after tag, [ $($i)* ]);

                                // restart children starting at the tag
                                #[allow(unused_assignments, unused_variables, unreachable_code)]
                                {
                                    let mut seen_tag = false;
                                    $(

                                        if seen_tag == true || tag == config.children_tags.unwrap().$i {
                                            seen_tag = true;

                                            let args = config.children_args.as_ref().unwrap().$i.clone();
                                            let name = match &config.children_names {
                                                Some(names) => &names.$i,
                                                None => &None
                                            };
                                            let proc_config = match &config.children_configs {
                                                Some(configs) => &configs.$i,
                                                None => &None
                                            };

                                            let link_tag = Tag::new();
                                            let proc_builder = $t::link_with(link_tag);
                                            let proc_builder = if let Some(config) = proc_config {
                                                proc_builder.configure(config)
                                            } else {
                                                proc_builder
                                            };
                                            let result = match name {
                                                Some(name) => {
                                                    // Remove first the previous registration
                                                    let remove = process_name::<$t, $t::Serializer>(ProcessType::ProcessRef, &name);
                                                    unsafe { host::api::registry::remove(remove.as_ptr(), remove.len()) };
                                                    proc_builder.start_as(name, args)
                                                },
                                                None => proc_builder.start(args),
                                            };
                                            let proc = match result {
                                                Ok(proc) => proc,
                                                Err(err) => panic!("Supervisor failed to start child `{:?}`", err),
                                            };
                                            config.children.as_mut().unwrap().$i = proc;
                                            config.children_tags.as_mut().unwrap().$i = link_tag;

                                        }

                                    )*
                                }
                            }
                        }
                    }
                }
            }
        };
    }

    pub(crate) use {ignore_expr, ignore_type, impl_supervisable, reverse_shutdown, tag};
}

#[cfg(test)]
mod tests {
    use lunatic_test::test;

    use super::{Supervisor, SupervisorConfig};
    use crate::ap::{AbstractProcess, Config};
    use crate::serializer::Bincode;

    struct SimpleServer;

    impl AbstractProcess for SimpleServer {
        type Arg = ();
        type State = Self;
        type Serializer = Bincode;
        type Handlers = ();
        type StartupError = ();

        fn init(_: Config<Self>, _arg: ()) -> Result<Self, ()> {
            Ok(SimpleServer)
        }
    }

    struct SimpleSup;

    impl Supervisor for SimpleSup {
        type Arg = ();
        type Children = (SimpleServer,);

        fn init(config: &mut SupervisorConfig<Self>, _: ()) {
            config.set_args(((),));
        }
    }

    #[test]
    fn supervisor_test() {
        SimpleSup::link().start(()).unwrap();
    }
}