proxy-pilot 0.7.1

Core-agnostic proxy health monitor, automatic failover daemon, and multi-channel alerting tool for Linux servers.
Documentation
use crate::config::ProfileConfig;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileHealth {
    Healthy,
    Degraded { consecutive_failures: u32 },
    Unhealthy,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FailoverAction {
    Stay,
    Degraded { failures: u32 },
    SwitchTo { from: String, to: ProfileConfig },
    AllUnhealthy { failed: String },
}

pub struct FailoverState {
    profiles: Vec<ProfileConfig>,
    health: Vec<ProfileHealth>,
    active_index: usize,
    failure_threshold: u32,
}

impl FailoverState {
    pub fn new(mut profiles: Vec<ProfileConfig>, failure_threshold: u32) -> Self {
        profiles.sort_by_key(|p| p.priority);
        let len = profiles.len();
        Self {
            profiles,
            health: vec![ProfileHealth::Healthy; len],
            active_index: 0,
            failure_threshold: failure_threshold.max(1),
        }
    }

    pub fn active_profile(&self) -> Option<&ProfileConfig> {
        self.profiles.get(self.active_index)
    }

    /// Reorder profiles and refresh health states from a non-disruptive background benchmark.
    ///
    /// Keeps the currently active profile if it is still healthy (zero disruption). If the
    /// active profile is unhealthy and a healthy candidate exists, switches `active_index` to
    /// the fastest healthy profile and returns it so the caller can activate it.
    pub fn apply_benchmark_order(
        &mut self,
        ranked: Vec<(ProfileConfig, bool)>,
    ) -> Option<ProfileConfig> {
        if ranked.is_empty() {
            return None;
        }
        let current_tag = self
            .profiles
            .get(self.active_index)
            .map(|p| p.outbound_tag.clone());

        self.profiles = ranked.iter().map(|(p, _)| p.clone()).collect();
        self.health = ranked
            .iter()
            .map(|(_, healthy)| {
                if *healthy {
                    ProfileHealth::Healthy
                } else {
                    ProfileHealth::Unhealthy
                }
            })
            .collect();

        if let Some(tag) = current_tag
            && let Some(idx) = self.profiles.iter().position(|p| p.outbound_tag == tag)
            && matches!(self.health[idx], ProfileHealth::Healthy)
        {
            self.active_index = idx;
            return None;
        }

        if let Some(idx) = self
            .health
            .iter()
            .position(|state| matches!(state, ProfileHealth::Healthy))
        {
            self.active_index = idx;
            return Some(self.profiles[idx].clone());
        }

        self.active_index = 0;
        None
    }

    pub fn record_probe(&mut self, healthy: bool) -> FailoverAction {
        if self.profiles.is_empty() {
            return FailoverAction::Stay;
        }
        if healthy {
            self.health[self.active_index] = ProfileHealth::Healthy;
            return FailoverAction::Stay;
        }

        let failures = match self.health[self.active_index] {
            ProfileHealth::Degraded {
                consecutive_failures,
            } => consecutive_failures + 1,
            _ => 1,
        };

        if failures < self.failure_threshold {
            self.health[self.active_index] = ProfileHealth::Degraded {
                consecutive_failures: failures,
            };
            return FailoverAction::Degraded { failures };
        }

        self.health[self.active_index] = ProfileHealth::Unhealthy;
        let failed_name = self.profiles[self.active_index].name.clone();

        if let Some(next_idx) = self.next_healthy_index() {
            self.active_index = next_idx;
            return FailoverAction::SwitchTo {
                from: failed_name,
                to: self.profiles[next_idx].clone(),
            };
        }

        FailoverAction::AllUnhealthy {
            failed: failed_name,
        }
    }

    fn next_healthy_index(&self) -> Option<usize> {
        self.health
            .iter()
            .enumerate()
            .find(|(idx, state)| {
                *idx != self.active_index && matches!(state, ProfileHealth::Healthy)
            })
            .map(|(idx, _)| idx)
    }
}

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

    fn sample_profiles() -> Vec<ProfileConfig> {
        vec![
            ProfileConfig {
                name: "finland".into(),
                outbound_tag: "fi-2".into(),
                priority: 2,
            },
            ProfileConfig {
                name: "germany".into(),
                outbound_tag: "de-1".into(),
                priority: 1,
            },
        ]
    }

    #[test]
    fn enforces_anti_flapping_before_failover() {
        let mut state = FailoverState::new(sample_profiles(), 3);
        assert_eq!(state.active_profile().unwrap().name, "germany");

        assert_eq!(
            state.record_probe(false),
            FailoverAction::Degraded { failures: 1 }
        );
        assert_eq!(
            state.record_probe(false),
            FailoverAction::Degraded { failures: 2 }
        );

        let action = state.record_probe(false);
        assert_eq!(
            action,
            FailoverAction::SwitchTo {
                from: "germany".into(),
                to: ProfileConfig {
                    name: "finland".into(),
                    outbound_tag: "fi-2".into(),
                    priority: 2,
                },
            }
        );
        assert_eq!(state.active_profile().unwrap().name, "finland");
    }

    #[test]
    fn reports_all_unhealthy_when_no_candidates_remain() {
        let mut state = FailoverState::new(sample_profiles(), 1);
        assert!(matches!(
            state.record_probe(false),
            FailoverAction::SwitchTo { .. }
        ));
        assert_eq!(
            state.record_probe(false),
            FailoverAction::AllUnhealthy {
                failed: "finland".into()
            }
        );
    }

    #[test]
    fn apply_benchmark_order_preserves_healthy_active_and_recovers_when_active_unhealthy() {
        let mut state = FailoverState::new(sample_profiles(), 1);
        assert_eq!(state.active_profile().unwrap().outbound_tag, "de-1");

        // Reorder so fi-2 is faster, while active de-1 is still healthy -> no forced switch.
        let switched = state.apply_benchmark_order(vec![
            (
                ProfileConfig {
                    name: "finland".into(),
                    outbound_tag: "fi-2".into(),
                    priority: 1,
                },
                true,
            ),
            (
                ProfileConfig {
                    name: "germany".into(),
                    outbound_tag: "de-1".into(),
                    priority: 2,
                },
                true,
            ),
        ]);
        assert!(switched.is_none());
        assert_eq!(state.active_profile().unwrap().outbound_tag, "de-1");

        // Now active de-1 is unhealthy in benchmark -> auto-recovers to fastest healthy fi-2.
        let recovered = state.apply_benchmark_order(vec![
            (
                ProfileConfig {
                    name: "finland".into(),
                    outbound_tag: "fi-2".into(),
                    priority: 1,
                },
                true,
            ),
            (
                ProfileConfig {
                    name: "germany".into(),
                    outbound_tag: "de-1".into(),
                    priority: 2,
                },
                false,
            ),
        ]);
        assert_eq!(recovered.unwrap().outbound_tag, "fi-2");
        assert_eq!(state.active_profile().unwrap().outbound_tag, "fi-2");
    }
}