Skip to main content

proxy_pilot/engine/
state.rs

1use crate::config::ProfileConfig;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum ProfileHealth {
5    Healthy,
6    Degraded { consecutive_failures: u32 },
7    Unhealthy,
8}
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum FailoverAction {
12    Stay,
13    Degraded { failures: u32 },
14    SwitchTo { from: String, to: ProfileConfig },
15    AllUnhealthy { failed: String },
16}
17
18pub struct FailoverState {
19    profiles: Vec<ProfileConfig>,
20    health: Vec<ProfileHealth>,
21    active_index: usize,
22    failure_threshold: u32,
23}
24
25impl FailoverState {
26    pub fn new(mut profiles: Vec<ProfileConfig>, failure_threshold: u32) -> Self {
27        profiles.sort_by_key(|p| p.priority);
28        let len = profiles.len();
29        Self {
30            profiles,
31            health: vec![ProfileHealth::Healthy; len],
32            active_index: 0,
33            failure_threshold: failure_threshold.max(1),
34        }
35    }
36
37    pub fn active_profile(&self) -> Option<&ProfileConfig> {
38        self.profiles.get(self.active_index)
39    }
40
41    /// Reorder profiles and refresh health states from a non-disruptive background benchmark.
42    ///
43    /// Keeps the currently active profile if it is still healthy (zero disruption). If the
44    /// active profile is unhealthy and a healthy candidate exists, switches `active_index` to
45    /// the fastest healthy profile and returns it so the caller can activate it.
46    pub fn apply_benchmark_order(
47        &mut self,
48        ranked: Vec<(ProfileConfig, bool)>,
49    ) -> Option<ProfileConfig> {
50        if ranked.is_empty() {
51            return None;
52        }
53        let current_tag = self
54            .profiles
55            .get(self.active_index)
56            .map(|p| p.outbound_tag.clone());
57
58        self.profiles = ranked.iter().map(|(p, _)| p.clone()).collect();
59        self.health = ranked
60            .iter()
61            .map(|(_, healthy)| {
62                if *healthy {
63                    ProfileHealth::Healthy
64                } else {
65                    ProfileHealth::Unhealthy
66                }
67            })
68            .collect();
69
70        if let Some(tag) = current_tag
71            && let Some(idx) = self.profiles.iter().position(|p| p.outbound_tag == tag)
72            && matches!(self.health[idx], ProfileHealth::Healthy)
73        {
74            self.active_index = idx;
75            return None;
76        }
77
78        if let Some(idx) = self
79            .health
80            .iter()
81            .position(|state| matches!(state, ProfileHealth::Healthy))
82        {
83            self.active_index = idx;
84            return Some(self.profiles[idx].clone());
85        }
86
87        self.active_index = 0;
88        None
89    }
90
91    pub fn record_probe(&mut self, healthy: bool) -> FailoverAction {
92        if self.profiles.is_empty() {
93            return FailoverAction::Stay;
94        }
95        if healthy {
96            self.health[self.active_index] = ProfileHealth::Healthy;
97            return FailoverAction::Stay;
98        }
99
100        let failures = match self.health[self.active_index] {
101            ProfileHealth::Degraded {
102                consecutive_failures,
103            } => consecutive_failures + 1,
104            _ => 1,
105        };
106
107        if failures < self.failure_threshold {
108            self.health[self.active_index] = ProfileHealth::Degraded {
109                consecutive_failures: failures,
110            };
111            return FailoverAction::Degraded { failures };
112        }
113
114        self.health[self.active_index] = ProfileHealth::Unhealthy;
115        let failed_name = self.profiles[self.active_index].name.clone();
116
117        if let Some(next_idx) = self.next_healthy_index() {
118            self.active_index = next_idx;
119            return FailoverAction::SwitchTo {
120                from: failed_name,
121                to: self.profiles[next_idx].clone(),
122            };
123        }
124
125        FailoverAction::AllUnhealthy {
126            failed: failed_name,
127        }
128    }
129
130    fn next_healthy_index(&self) -> Option<usize> {
131        self.health
132            .iter()
133            .enumerate()
134            .find(|(idx, state)| {
135                *idx != self.active_index && matches!(state, ProfileHealth::Healthy)
136            })
137            .map(|(idx, _)| idx)
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    fn sample_profiles() -> Vec<ProfileConfig> {
146        vec![
147            ProfileConfig {
148                name: "finland".into(),
149                outbound_tag: "fi-2".into(),
150                priority: 2,
151            },
152            ProfileConfig {
153                name: "germany".into(),
154                outbound_tag: "de-1".into(),
155                priority: 1,
156            },
157        ]
158    }
159
160    #[test]
161    fn enforces_anti_flapping_before_failover() {
162        let mut state = FailoverState::new(sample_profiles(), 3);
163        assert_eq!(state.active_profile().unwrap().name, "germany");
164
165        assert_eq!(
166            state.record_probe(false),
167            FailoverAction::Degraded { failures: 1 }
168        );
169        assert_eq!(
170            state.record_probe(false),
171            FailoverAction::Degraded { failures: 2 }
172        );
173
174        let action = state.record_probe(false);
175        assert_eq!(
176            action,
177            FailoverAction::SwitchTo {
178                from: "germany".into(),
179                to: ProfileConfig {
180                    name: "finland".into(),
181                    outbound_tag: "fi-2".into(),
182                    priority: 2,
183                },
184            }
185        );
186        assert_eq!(state.active_profile().unwrap().name, "finland");
187    }
188
189    #[test]
190    fn reports_all_unhealthy_when_no_candidates_remain() {
191        let mut state = FailoverState::new(sample_profiles(), 1);
192        assert!(matches!(
193            state.record_probe(false),
194            FailoverAction::SwitchTo { .. }
195        ));
196        assert_eq!(
197            state.record_probe(false),
198            FailoverAction::AllUnhealthy {
199                failed: "finland".into()
200            }
201        );
202    }
203
204    #[test]
205    fn apply_benchmark_order_preserves_healthy_active_and_recovers_when_active_unhealthy() {
206        let mut state = FailoverState::new(sample_profiles(), 1);
207        assert_eq!(state.active_profile().unwrap().outbound_tag, "de-1");
208
209        // Reorder so fi-2 is faster, while active de-1 is still healthy -> no forced switch.
210        let switched = state.apply_benchmark_order(vec![
211            (
212                ProfileConfig {
213                    name: "finland".into(),
214                    outbound_tag: "fi-2".into(),
215                    priority: 1,
216                },
217                true,
218            ),
219            (
220                ProfileConfig {
221                    name: "germany".into(),
222                    outbound_tag: "de-1".into(),
223                    priority: 2,
224                },
225                true,
226            ),
227        ]);
228        assert!(switched.is_none());
229        assert_eq!(state.active_profile().unwrap().outbound_tag, "de-1");
230
231        // Now active de-1 is unhealthy in benchmark -> auto-recovers to fastest healthy fi-2.
232        let recovered = state.apply_benchmark_order(vec![
233            (
234                ProfileConfig {
235                    name: "finland".into(),
236                    outbound_tag: "fi-2".into(),
237                    priority: 1,
238                },
239                true,
240            ),
241            (
242                ProfileConfig {
243                    name: "germany".into(),
244                    outbound_tag: "de-1".into(),
245                    priority: 2,
246                },
247                false,
248            ),
249        ]);
250        assert_eq!(recovered.unwrap().outbound_tag, "fi-2");
251        assert_eq!(state.active_profile().unwrap().outbound_tag, "fi-2");
252    }
253}