proxy-pilot 0.6.1

Core-agnostic proxy health monitor, automatic failover daemon, and multi-channel alerting tool for Linux servers.
Documentation
use std::time::Duration;

use async_trait::async_trait;
use reqwest::Client;
use serde::Serialize;

use crate::error::{PilotError, Result};
use crate::notify::{AlertEvent, AlertSeverity, Notifier};

const DEFAULT_BALE_API_BASE: &str = "https://tapi.bale.ai";

pub struct BaleNotifier {
    base_url: String,
    bot_token: String,
    chat_id: String,
    client: Client,
}

#[derive(Serialize)]
struct SendMessagePayload<'a> {
    chat_id: &'a str,
    text: String,
}

impl BaleNotifier {
    pub fn new(bot_token: String, chat_id: String) -> Result<Self> {
        Self::with_base_url(DEFAULT_BALE_API_BASE.to_string(), bot_token, chat_id)
    }

    pub fn with_base_url(base_url: String, bot_token: String, chat_id: String) -> Result<Self> {
        if bot_token.trim().is_empty() || chat_id.trim().is_empty() {
            return Err(PilotError::Notify(
                "bale bot_token and chat_id must not be empty".into(),
            ));
        }
        let client = Client::builder()
            .no_proxy()
            .connect_timeout(Duration::from_secs(5))
            .timeout(Duration::from_secs(10))
            .build()
            .map_err(|err| PilotError::Notify(format!("failed to build bale client: {err}")))?;
        Ok(Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            bot_token,
            chat_id,
            client,
        })
    }

    pub fn format_message(event: &AlertEvent) -> String {
        let icon = match event.severity {
            AlertSeverity::Info => "ℹ️",
            AlertSeverity::Warning => "⚠️",
            AlertSeverity::Critical => "🚨",
        };
        format!("{icon} {}\n\n{}", event.title, event.message)
    }
}

#[async_trait]
impl Notifier for BaleNotifier {
    fn channel_name(&self) -> &'static str {
        "bale"
    }

    async fn send(&self, event: &AlertEvent) -> Result<()> {
        let url = format!("{}/bot{}/sendMessage", self.base_url, self.bot_token);
        let payload = SendMessagePayload {
            chat_id: &self.chat_id,
            text: Self::format_message(event),
        };
        let resp = self
            .client
            .post(&url)
            .json(&payload)
            .send()
            .await
            .map_err(|err| {
                PilotError::Notify(format!("bale request failed: {}", err.without_url()))
            })?;

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            return Err(PilotError::Notify(format!(
                "bale api returned HTTP {status}"
            )));
        }
        Ok(())
    }
}

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

    #[test]
    fn rejects_empty_credentials() {
        assert!(BaleNotifier::new("".into(), "123".into()).is_err());
        assert!(BaleNotifier::new("tok".into(), " ".into()).is_err());
    }

    #[test]
    fn formats_alert_with_severity_prefix() {
        let event = AlertEvent {
            severity: AlertSeverity::Critical,
            title: "قطع کامل کانفیگ‌ها".into(),
            message: "هیچ کانفیگ سالمی در دسترس نیست.".into(),
        };
        let text = BaleNotifier::format_message(&event);
        assert!(text.starts_with("🚨 قطع کامل کانفیگ‌ها"));
        assert!(text.contains("هیچ کانفیگ سالمی"));
    }
}