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
use std::collections::VecDeque;
use std::fmt;
use std::sync::Arc;

use agner_actors::{ActorID, ExitReason};

use crate::fixed::restart_strategy::{Action, Decider, FrequencyPolicy, Instant, RestartStrategy};

use super::FrequencyStats;

#[derive(Debug, Clone, Default)]
pub struct AllForOne {
    pub frequency_policy: FrequencyPolicy,
}

#[derive(Debug)]
pub struct AllForOneDecider {
    sup_id: ActorID,
    ch_ids: Box<[ActorID]>,
    ch_states: Box<[ChState]>,
    failures: Box<[FrequencyStats]>,
    pending: VecDeque<Action>,
}

#[derive(Debug, Clone, Copy)]
enum ChState {
    Down,
    Up,
    ShuttingDown,
}

impl RestartStrategy for AllForOne {
    type Decider = AllForOneDecider;

    fn new_decider(&self, sup_id: ActorID, children: &[ActorID]) -> Self::Decider {
        let failures = children.iter().map(|_| self.frequency_policy.new_stats()).collect();
        let ch_states = children.iter().map(|_| ChState::Up).collect();
        let ch_ids = children.into();
        AllForOneDecider { sup_id, ch_ids, ch_states, failures, pending: Default::default() }
    }
}

impl Decider for AllForOneDecider {
    fn next_action(&mut self) -> Option<super::Action> {
        self.pending.pop_front()
    }
    fn child_up(&mut self, _at: Instant, child_idx: usize, actor_id: ActorID) {
        assert!(matches!(self.ch_states[child_idx], ChState::Down));
        self.ch_ids[child_idx] = actor_id;
        self.ch_states[child_idx] = ChState::Up;
    }
    fn actor_down(&mut self, at: Instant, actor_id: ActorID, exit_reason: ExitReason) {
        if actor_id == self.sup_id {
            log::trace!("[{}] Requested shutdown [reason: {}]", self, exit_reason.pp());
            self.initiate_shutdown(exit_reason)
        } else {
            let idx_opt = self
                .ch_ids
                .iter()
                .enumerate()
                .find(|&(_, &id)| id == actor_id)
                .map(|(idx, _)| idx);

            if let Some(idx) = idx_opt {
                if matches!(self.ch_states[idx], ChState::ShuttingDown) {
                    self.ch_states[idx] = ChState::Down;
                } else if self.failures[idx].report(at) {
                    self.initiate_shutdown(exit_reason)
                } else {
                    self.initiate_restart(exit_reason)
                }
            } else {
                log::info!(
                    "[{}] Unknown linked actor exited. Initiating shutdown. [reason: {}]",
                    self,
                    exit_reason.pp()
                );

                self.initiate_shutdown(ExitReason::Exited(actor_id, exit_reason.into()))
            }
        }
    }
}

impl AllForOneDecider {
    fn initiate_restart(&mut self, cause: ExitReason) {
        let arc_cause = Arc::new(cause);

        self.pending.clear();
        self.pending.extend(
            (0..self.ch_ids.len())
                .rev()
                .filter_map(|idx| {
                    if !matches!(self.ch_states[idx], ChState::Down) {
                        self.ch_states[idx] = ChState::ShuttingDown;
                        Some(Action::Stop(
                            idx,
                            self.ch_ids[idx],
                            ExitReason::Shutdown(Some(arc_cause.to_owned())),
                        ))
                    } else {
                        None
                    }
                })
                .chain((0..self.ch_ids.len()).map(Action::Start)),
        );
    }

    fn initiate_shutdown(&mut self, cause: ExitReason) {
        let arc_exit_reason = Arc::new(cause.to_owned());

        self.pending.clear();
        self.pending.extend(
            (0..self.ch_ids.len())
                .rev()
                .filter_map(|idx| {
                    if !matches!(self.ch_states[idx], ChState::Down) {
                        self.ch_states[idx] = ChState::ShuttingDown;
                        Some(Action::Stop(
                            idx,
                            self.ch_ids[idx],
                            ExitReason::Shutdown(Some(arc_exit_reason.to_owned())),
                        ))
                    } else {
                        None
                    }
                })
                .chain([Action::Exit(cause)]),
        );
    }
}

impl fmt::Display for AllForOne {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "all-for-one: {}", self.frequency_policy)
    }
}

impl fmt::Display for AllForOneDecider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}|all-for-one", self.sup_id)
    }
}