Skip to main content

aidaemon_work/health/
mod.rs

1//! First-class health probe system with structured metrics, trend analysis, and alerting.
2
3pub mod alerts;
4pub mod probes;
5pub mod store;
6mod tool;
7pub mod trends;
8
9use chrono::{DateTime, Utc};
10use std::sync::Arc;
11use std::time::Duration;
12use tracing::{error, info, warn};
13
14use crate::schedule::{compute_next_run, parse_schedule};
15
16pub use alerts::{AlertDelivery, AlertManager};
17pub use probes::{HealthProbe, ProbeConfig, ProbeExecutor, ProbeResult, ProbeType};
18pub use store::HealthProbeStore;
19pub use tool::HealthProbeTool;
20pub use trends::TrendAnalyzer;
21
22use serde::Deserialize;
23
24/// The `[health]` settings.
25#[derive(Debug, Deserialize, Clone, Default)]
26pub struct HealthConfig {
27    #[serde(default = "default_health_enabled")]
28    pub enabled: bool,
29    #[serde(default = "default_health_tick_interval_secs")]
30    pub tick_interval_secs: u64,
31    #[serde(default = "default_health_result_retention_days")]
32    pub result_retention_days: u32,
33    #[serde(default)]
34    pub probes: Vec<HealthProbeConfig>,
35}
36
37fn default_health_enabled() -> bool {
38    false
39}
40
41fn default_health_tick_interval_secs() -> u64 {
42    30
43}
44
45fn default_health_result_retention_days() -> u32 {
46    7
47}
48
49#[derive(Debug, Deserialize, Clone)]
50pub struct HealthProbeConfig {
51    pub name: String,
52    #[serde(rename = "type")]
53    pub probe_type: String,
54    pub target: String,
55    pub schedule: String,
56    #[serde(default)]
57    pub description: Option<String>,
58    #[serde(default)]
59    pub config: HealthProbeConfigOptions,
60    #[serde(default)]
61    pub consecutive_failures_alert: Option<u32>,
62    #[serde(default)]
63    pub latency_threshold_ms: Option<u32>,
64    #[serde(default)]
65    pub alert_session_ids: Vec<String>,
66}
67
68#[derive(Debug, Deserialize, Clone, Default)]
69pub struct HealthProbeConfigOptions {
70    #[serde(default)]
71    pub timeout_secs: Option<u64>,
72    #[serde(default)]
73    pub expected_status: Option<u16>,
74    #[serde(default)]
75    pub expected_body: Option<String>,
76    #[serde(default)]
77    pub method: Option<String>,
78    #[serde(default)]
79    pub headers: Option<std::collections::HashMap<String, String>>,
80    #[serde(default)]
81    pub max_age_secs: Option<u64>,
82    #[serde(default)]
83    pub expected_exit_code: Option<i32>,
84}
85
86/// Manager for health probes with background tick loop.
87pub struct HealthProbeManager {
88    store: Arc<HealthProbeStore>,
89    alerts: Arc<AlertManager>,
90    tick_interval: Duration,
91}
92
93impl HealthProbeManager {
94    /// Create a new health probe manager.
95    pub fn new(
96        store: Arc<HealthProbeStore>,
97        hub: Arc<dyn AlertDelivery>,
98        tick_interval_secs: u64,
99    ) -> Self {
100        let alerts = Arc::new(AlertManager::new(store.clone(), hub));
101
102        Self {
103            store,
104            alerts,
105            tick_interval: Duration::from_secs(tick_interval_secs),
106        }
107    }
108
109    /// Get a reference to the store for external use.
110    pub fn store(&self) -> &Arc<HealthProbeStore> {
111        &self.store
112    }
113
114    /// Seed probes from configuration.
115    ///
116    /// Uses upsert by name for config-sourced probes and removes stale entries.
117    pub async fn seed_from_config(
118        &self,
119        probes: &[HealthProbeConfig],
120        default_alert_sessions: &[String],
121    ) {
122        let now = Utc::now();
123
124        for probe_config in probes {
125            // Parse schedule to cron
126            let cron_expr = match parse_schedule(&probe_config.schedule) {
127                Ok(expr) => expr,
128                Err(e) => {
129                    error!(
130                        name = %probe_config.name,
131                        schedule = %probe_config.schedule,
132                        "Failed to parse health probe schedule: {}",
133                        e
134                    );
135                    continue;
136                }
137            };
138
139            // Compute next run time
140            let next_run = match compute_next_run(&cron_expr) {
141                Ok(dt) => dt,
142                Err(e) => {
143                    error!(
144                        name = %probe_config.name,
145                        "Failed to compute next run for health probe: {}",
146                        e
147                    );
148                    continue;
149                }
150            };
151
152            // Build probe configuration
153            let config = ProbeConfig {
154                timeout_secs: probe_config.config.timeout_secs.unwrap_or(10),
155                expected_status: probe_config.config.expected_status,
156                expected_body: probe_config.config.expected_body.clone(),
157                method: probe_config
158                    .config
159                    .method
160                    .clone()
161                    .unwrap_or_else(|| "GET".to_string()),
162                headers: probe_config.config.headers.clone().unwrap_or_default(),
163                max_age_secs: probe_config.config.max_age_secs,
164                expected_exit_code: probe_config.config.expected_exit_code,
165            };
166
167            // Determine alert sessions - use probe-specific or fall back to defaults
168            let alert_sessions = if probe_config.alert_session_ids.is_empty() {
169                default_alert_sessions.to_vec()
170            } else {
171                probe_config.alert_session_ids.clone()
172            };
173
174            let probe = HealthProbe {
175                id: uuid::Uuid::new_v4().to_string(),
176                name: probe_config.name.clone(),
177                description: probe_config.description.clone(),
178                probe_type: ProbeType::from_str(&probe_config.probe_type),
179                target: probe_config.target.clone(),
180                schedule: cron_expr,
181                source: "config".to_string(),
182                config,
183                consecutive_failures_alert: probe_config.consecutive_failures_alert.unwrap_or(3),
184                latency_threshold_ms: probe_config.latency_threshold_ms,
185                alert_session_ids: alert_sessions,
186                is_paused: false,
187                last_run_at: None,
188                next_run_at: next_run,
189                created_at: now,
190                updated_at: now,
191            };
192
193            match self.store.upsert_probe(&probe).await {
194                Ok(_) => info!(
195                    name = %probe_config.name,
196                    probe_type = %probe_config.probe_type,
197                    schedule = %probe_config.schedule,
198                    "Seeded health probe from config"
199                ),
200                Err(e) => error!(
201                    name = %probe_config.name,
202                    "Failed to seed health probe: {}",
203                    e
204                ),
205            }
206        }
207
208        // Remove config-sourced probes that are no longer in config
209        let config_names: Vec<&str> = probes.iter().map(|p| p.name.as_str()).collect();
210        match self.store.remove_stale_config_probes(&config_names).await {
211            Ok(removed) if removed > 0 => {
212                info!(count = removed, "Removed stale config health probes");
213            }
214            Err(e) => {
215                warn!("Failed to remove stale config probes: {}", e);
216            }
217            _ => {}
218        }
219    }
220
221    /// Spawn the background tick loop.
222    pub fn spawn(self: Arc<Self>) {
223        tokio::spawn(async move {
224            info!(
225                interval_secs = self.tick_interval.as_secs(),
226                "Health probe manager started"
227            );
228
229            loop {
230                tokio::time::sleep(self.tick_interval).await;
231
232                if let Err(e) = self.tick().await {
233                    error!("Health probe tick error: {}", e);
234                }
235            }
236        });
237    }
238
239    /// Check for due probes and execute them.
240    async fn tick(&self) -> anyhow::Result<()> {
241        let now = Utc::now();
242        let due_probes = self.store.get_due_probes(now).await?;
243
244        if due_probes.is_empty() {
245            return Ok(());
246        }
247
248        info!(count = due_probes.len(), "Running due health probes");
249
250        for probe in due_probes {
251            // Execute the probe
252            let result = ProbeExecutor::execute(&probe).await;
253
254            info!(
255                probe = %probe.name,
256                status = %result.status.as_str(),
257                latency_ms = ?result.latency_ms,
258                "Probe check completed"
259            );
260
261            // Store the result
262            if let Err(e) = self.store.insert_result(&result).await {
263                warn!(probe = %probe.name, "Failed to store probe result: {}", e);
264            }
265
266            // Process alerts
267            self.alerts.process_result(&probe, &result).await;
268
269            // Update next run time
270            let next_run = match compute_next_run(&probe.schedule) {
271                Ok(dt) => dt,
272                Err(e) => {
273                    warn!(
274                        probe = %probe.name,
275                        "Failed to compute next run, using +1 minute: {}",
276                        e
277                    );
278                    now + chrono::Duration::minutes(1)
279                }
280            };
281
282            if let Err(e) = self.store.update_probe_run(&probe.id, now, next_run).await {
283                warn!(probe = %probe.name, "Failed to update probe run time: {}", e);
284            }
285        }
286
287        Ok(())
288    }
289
290    /// Cleanup old probe results beyond retention period.
291    pub async fn cleanup_old_results(&self, retention_days: u32) -> anyhow::Result<u64> {
292        let cutoff = Utc::now() - chrono::Duration::days(retention_days as i64);
293        let deleted = self.store.delete_old_results(cutoff).await?;
294
295        if deleted > 0 {
296            info!(deleted, retention_days, "Cleaned up old probe results");
297        }
298
299        Ok(deleted)
300    }
301}
302
303/// Summary of a probe's current status for API responses.
304#[derive(Debug, Clone, serde::Serialize)]
305pub struct ProbeStatusSummary {
306    pub id: String,
307    pub name: String,
308    pub probe_type: String,
309    pub target: String,
310    pub is_paused: bool,
311    pub last_status: Option<String>,
312    pub last_latency_ms: Option<u32>,
313    pub last_checked: Option<DateTime<Utc>>,
314    pub next_run: DateTime<Utc>,
315    pub consecutive_failures: u32,
316    pub has_active_alert: bool,
317}
318
319/// Spawn a cleanup task that runs daily.
320pub fn spawn_cleanup_task(manager: Arc<HealthProbeManager>, retention_days: u32) {
321    tokio::spawn(async move {
322        loop {
323            // Run at 3:40 AM (after other cleanup tasks)
324            let now = chrono::Utc::now();
325            let next_340am = {
326                let today_340am = now.date_naive().and_hms_opt(3, 40, 0).unwrap();
327                let today_340am_utc = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
328                    today_340am,
329                    chrono::Utc,
330                );
331                if now < today_340am_utc {
332                    today_340am_utc
333                } else {
334                    today_340am_utc + chrono::Duration::days(1)
335                }
336            };
337
338            let sleep_duration = (next_340am - now)
339                .to_std()
340                .unwrap_or(Duration::from_secs(3600));
341            tokio::time::sleep(sleep_duration).await;
342
343            match manager.cleanup_old_results(retention_days).await {
344                Ok(deleted) => {
345                    if deleted > 0 {
346                        info!(deleted, "Health probe result cleanup complete");
347                    }
348                }
349                Err(e) => {
350                    error!("Health probe result cleanup failed: {}", e);
351                }
352            }
353        }
354    });
355}