# Architecture Overview
`proxy-pilot` is a single-binary Linux daemon and CLI tool written in Rust. It monitors real end-to-end access through proxy tunnels, performs automatic failover with anti-flapping, and sends alerts over VPN-independent channels.
## Design Principles
1. **Core-Agnostic Engine:** The monitoring and failover engine (`src/engine/`) depends only on traits (`ProxyCore`, `HealthProbe`, `Notifier`). It never imports concrete implementations like `XrayCore` or `BaleNotifier`.
2. **Zero-Friction Server Deployment:** Distributed as static Linux `musl` binaries via GitHub Releases, managed by `systemd`. Target servers require no Rust toolchain or runtime dependencies.
3. **Resilience on Restricted Networks (Iran & Worldwide):**
- Battle-tested on Iran servers (domestic `direct_check_url` such as `aparat.com`, VPN-independent Bale Bot API alerts, and whitelist routing), while remaining **region-agnostic**: servers in any censored or geo-restricted country can configure their own `direct_check_url`, `targets`, `routing` rules, and notification channels.
- Binary/core downloads support fallback mirrors when GitHub release assets are slow or degraded.
## Repository Layout
```text
proxy-pilot/
├── Cargo.toml # Package metadata, dependencies, release profile
├── CHANGELOG.md # Release history (Keep a Changelog)
├── LICENSE # MIT License
├── AGENTS.md # Agent router & repository rules
├── config.example.yaml # Sample configuration (never commit live config.yaml)
├── .pre-commit-config.yaml # Pre-commit hooks (cargo fmt, clippy, YAML, secrets)
├── .github/workflows/ # CI (ci.yml) and static musl Release (release.yml)
├── deploy/
│ └── proxy-pilot.service # systemd unit file
├── docs/ # Technical documentation (guides/ and standards/)
└── src/
├── main.rs # Binary entry point
├── lib.rs # Library exports for tests
├── error.rs # Unified PilotError (thiserror)
├── cli/ # CLI commands (clap) & setup wizard
├── config/ # config.yaml schema & loader
├── engine/ # Watchdog, anti-flapping, failover, auto-recovery
├── core/ # ProxyCore trait + adapters (xray/, future singbox/)
├── probe/ # HealthProbe trait + proxy-routed HTTP checks
└── notify/ # Notifier trait + channels (bale.rs, future sms/email/heartbeat)
```
## Module Boundaries
| `src/cli/` | Command-line parsing (`clap`), interactive `setup` wizard, wiring concrete implementations into `engine`. | All internal modules |
| `src/config/` | Loading, validating, and saving `config.yaml`. | `error` |
| `src/engine/` | Watchdog loop, anti-flapping state machine, failover selection, auto-recovery, alert cooldowns. | `config`, `error`, traits from `core`, `probe`, `notify` |
| `src/core/` | `ProxyCore` trait + concrete adapters (`xray`, future `singbox`) + core binary installer. | `config`, `error` |
| `src/probe/` | `HealthProbe` trait + HTTP/SOCKS5 probes distinguishing `Healthy`, `GeoBlocked` (`403`/`429`), and `Unreachable`. | `config`, `error` |
| `src/notify/` | `Notifier` trait + concrete channels (`bale`, future `heartbeat`, `sms`, `email`). | `config`, `error` |
## Failover & Health State Machine
Each configured proxy profile tracks:
- `Healthy` — Active or standby candidate.
- `Degraded` — Experienced 1 to `failure_threshold - 1` consecutive failures (anti-flapping buffer).
- `Unhealthy` — Reached `failure_threshold` consecutive failures; triggers failover to the highest-priority `Healthy` profile and emits an alert.
- `Recovering` — Periodically re-probed in the background; returns to `Healthy` after `recovery_threshold` consecutive successes.
If **all** profiles become `Unhealthy`, the engine emits a `Critical` alert (respecting `cooldown_secs`) and continues periodic probing until any profile recovers.
### Non-Disruptive Periodic Background Benchmarking
Every `probe.benchmark_interval_secs` (default `900`s / 15 minutes; `0` disables), `Watchdog` runs an isolated background benchmark across all configured profiles:
- Spawns a separate temporary proxy core session bound to ephemeral loopback ports, probing all profiles in parallel without touching or reloading the live proxy service.
- If the configured core does not support isolated sessions (e.g., `start_benchmark_session()` returns `Ok(None)`), the background benchmark is safely skipped so active traffic is never interrupted.
- Re-ranks profiles by lowest average latency, updates `priority` in memory and atomically in `config.yaml`, and restores previously `Unhealthy` profiles that are now healthy back to standby.
- Keeps the currently active profile running with zero disruption if it is still healthy; only switches and reloads the live core if the active profile was unhealthy and a healthy candidate is found.
- Tracks continuous downtime in RAM (`unhealthy_since`); when `probe.auto_prune_after_hours` (default `24`, `0` disables) is exceeded, verifies at least one healthy profile exists and that `probe.direct_check_url` (non-proxied host internet check) succeeds before pruning dead profiles and sending an `Info` alert.
## Linux FHS Deployment Layout
| `proxy-pilot` binary | `/usr/local/bin/proxy-pilot` |
| User configuration | `/etc/proxy-pilot/config.yaml` |
| Managed core binaries (`xray`, `sing-box`) & state | `/var/lib/proxy-pilot/` |
| `systemd` unit | `/etc/systemd/system/proxy-pilot.service` |