adk-gateway 1.0.0

Multi-channel AI gateway for adk-rust agents — Telegram, Slack, WhatsApp, Discord, Matrix + control panel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Health Monitor — periodic health checks for gateway components.
//!
//! Implements a state machine that tracks per-component health status,
//! emits alerts after consecutive failures reach a threshold, and emits
//! recovery notifications when a failing component returns to healthy.
//!
//! Integrates with the existing `/health` endpoint to expose per-component
//! breakdown, and supports alerting via webhook POST or Telegram message.

use chrono::{DateTime, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tracing::{error, info, warn};

use crate::config::HealthMonitorConfig;

// ── Health Status ──────────────────────────────────────────────────

/// The health status of a monitored component.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum HealthStatus {
    Healthy,
    Degraded { reason: String },
    Unhealthy { reason: String },
}

impl HealthStatus {
    /// Returns true if the status represents a healthy state.
    pub fn is_healthy(&self) -> bool {
        matches!(self, HealthStatus::Healthy)
    }
}

// ── Component Health ───────────────────────────────────────────────

/// Per-component health state tracked by the monitor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentHealth {
    pub name: String,
    pub status: HealthStatus,
    pub consecutive_failures: u32,
    pub last_check: DateTime<Utc>,
    /// Whether an alert has been emitted for the current failure streak.
    /// Used to prevent duplicate alerts.
    #[serde(skip)]
    pub alerted: bool,
}

// ── Health Events ──────────────────────────────────────────────────

/// Events emitted by the health monitor state machine.
#[derive(Debug, Clone, PartialEq)]
pub enum HealthEvent {
    /// Alert: component has reached the failure threshold.
    Alert { component: String, failures: u32 },
    /// Recovery: component transitioned from alerted (failed) state to healthy.
    Recovery { component: String },
}

// ── Health Monitor ─────────────────────────────────────────────────

/// The health monitor tracks per-component health and emits events
/// based on state transitions.
pub struct HealthMonitor {
    components: DashMap<String, ComponentHealth>,
    config: HealthMonitorConfig,
}

impl HealthMonitor {
    /// Create a new health monitor with the given configuration.
    pub fn new(config: HealthMonitorConfig) -> Self {
        Self {
            components: DashMap::new(),
            config,
        }
    }

    /// Record a health check result for a component.
    ///
    /// Returns `Some(HealthEvent)` if the state transition warrants an alert
    /// or recovery notification. Returns `None` if no event should be emitted.
    ///
    /// State machine rules:
    /// - Alert emitted when consecutive_failures reaches failure_threshold (exactly once)
    /// - Recovery emitted when a component transitions from alerted state to healthy
    /// - No duplicate alerts for the same failure streak
    /// - No duplicate recoveries for the same recovery
    pub fn record_check(&self, component: &str, healthy: bool) -> Option<HealthEvent> {
        let now = Utc::now();
        let threshold = self.config.failure_threshold;

        let mut entry = self.components.entry(component.to_string()).or_insert_with(|| {
            ComponentHealth {
                name: component.to_string(),
                status: HealthStatus::Healthy,
                consecutive_failures: 0,
                last_check: now,
                alerted: false,
            }
        });

        let health = entry.value_mut();
        health.last_check = now;

        if healthy {
            // Component is healthy
            let was_alerted = health.alerted;
            health.status = HealthStatus::Healthy;
            health.consecutive_failures = 0;
            health.alerted = false;

            if was_alerted {
                // Transition from alerted (failed) state to healthy → recovery
                Some(HealthEvent::Recovery {
                    component: component.to_string(),
                })
            } else {
                None
            }
        } else {
            // Component failed
            health.consecutive_failures += 1;
            let failures = health.consecutive_failures;

            if failures >= threshold {
                health.status = HealthStatus::Unhealthy {
                    reason: format!("{} consecutive failures", failures),
                };
            } else {
                health.status = HealthStatus::Degraded {
                    reason: format!("{}/{} failures", failures, threshold),
                };
            }

            // Emit alert exactly once when threshold is reached
            if failures >= threshold && !health.alerted {
                health.alerted = true;
                Some(HealthEvent::Alert {
                    component: component.to_string(),
                    failures,
                })
            } else {
                None
            }
        }
    }

    /// Record a health check with a specific reason for failure.
    pub fn record_check_with_reason(
        &self,
        component: &str,
        healthy: bool,
        _reason: Option<&str>,
    ) -> Option<HealthEvent> {
        self.record_check(component, healthy)
    }

    /// Get current health status for all monitored components.
    pub fn status(&self) -> Vec<ComponentHealth> {
        self.components
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Get health status for a specific component.
    pub fn component_status(&self, component: &str) -> Option<ComponentHealth> {
        self.components.get(component).map(|entry| entry.value().clone())
    }

    /// Get the configuration.
    pub fn config(&self) -> &HealthMonitorConfig {
        &self.config
    }

    /// Get the number of monitored components.
    pub fn component_count(&self) -> usize {
        self.components.len()
    }
}

// ── Alerting ───────────────────────────────────────────────────────

/// Alert payload sent via webhook or Telegram.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertPayload {
    pub component: String,
    pub status: String,
    pub failure_count: u32,
    pub timestamp: DateTime<Utc>,
    pub event_type: String,
}

/// Send an alert via webhook (POST JSON).
pub async fn send_webhook_alert(url: &str, event: &HealthEvent) -> Result<(), anyhow::Error> {
    let payload = match event {
        HealthEvent::Alert {
            component,
            failures,
        } => AlertPayload {
            component: component.clone(),
            status: "unhealthy".to_string(),
            failure_count: *failures,
            timestamp: Utc::now(),
            event_type: "alert".to_string(),
        },
        HealthEvent::Recovery { component } => AlertPayload {
            component: component.clone(),
            status: "healthy".to_string(),
            failure_count: 0,
            timestamp: Utc::now(),
            event_type: "recovery".to_string(),
        },
    };

    let client = reqwest::Client::new();
    let response = client.post(url).json(&payload).send().await?;

    if !response.status().is_success() {
        warn!(
            url = url,
            status = %response.status(),
            "Webhook alert delivery failed"
        );
        anyhow::bail!(
            "Webhook returned non-success status: {}",
            response.status()
        );
    }

    info!(
        component = %payload.component,
        event_type = %payload.event_type,
        "Webhook alert delivered successfully"
    );
    Ok(())
}

/// Send an alert via Telegram to the configured admin user.
pub async fn send_telegram_alert(
    bot_token: &str,
    admin_chat_id: &str,
    event: &HealthEvent,
) -> Result<(), anyhow::Error> {
    let message = match event {
        HealthEvent::Alert {
            component,
            failures,
        } => {
            format!(
                "🚨 *Health Alert*\n\nComponent: `{}`\nStatus: Unhealthy\nConsecutive failures: {}\nTime: {}",
                component, failures, Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
            )
        }
        HealthEvent::Recovery { component } => {
            format!(
                "✅ *Recovery*\n\nComponent: `{}`\nStatus: Healthy\nTime: {}",
                component,
                Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
            )
        }
    };

    let url = format!(
        "https://api.telegram.org/bot{}/sendMessage",
        bot_token
    );

    let client = reqwest::Client::new();
    let response = client
        .post(&url)
        .json(&serde_json::json!({
            "chat_id": admin_chat_id,
            "text": message,
            "parse_mode": "Markdown",
        }))
        .send()
        .await?;

    if !response.status().is_success() {
        error!(
            admin_chat_id = admin_chat_id,
            status = %response.status(),
            "Telegram alert delivery failed"
        );
        anyhow::bail!(
            "Telegram API returned non-success status: {}",
            response.status()
        );
    }

    info!(
        admin_chat_id = admin_chat_id,
        "Telegram alert delivered successfully"
    );
    Ok(())
}

// ── Periodic Check Runner ──────────────────────────────────────────

/// Component check function type.
pub type CheckFn = Arc<dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send>> + Send + Sync>;

/// Start the periodic health check loop.
///
/// This spawns a tokio task that runs health checks at the configured interval.
/// It checks channel connectivity, model reachability, and session store availability.
pub async fn run_periodic_checks(
    monitor: Arc<HealthMonitor>,
    checks: Vec<(String, CheckFn)>,
    cancel: tokio_util::sync::CancellationToken,
) {
    let interval_secs = monitor.config().check_interval_secs;
    let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(interval_secs));

    loop {
        tokio::select! {
            _ = cancel.cancelled() => {
                info!("Health monitor shutting down");
                break;
            }
            _ = interval.tick() => {
                for (component_name, check_fn) in &checks {
                    let healthy = check_fn().await;
                    if let Some(event) = monitor.record_check(component_name, healthy) {
                        // Dispatch alert/recovery
                        dispatch_event(&monitor, &event).await;
                    }
                }
            }
        }
    }
}

/// Dispatch a health event to configured alerting channels.
async fn dispatch_event(monitor: &HealthMonitor, event: &HealthEvent) {
    let config = monitor.config();

    // Log the event
    match event {
        HealthEvent::Alert { component, failures } => {
            error!(
                component = %component,
                failures = failures,
                "Health alert: component unhealthy"
            );
        }
        HealthEvent::Recovery { component } => {
            info!(
                component = %component,
                "Health recovery: component restored"
            );
        }
    }

    // Webhook alerting
    if let Some(ref webhook_url) = config.alert_webhook_url {
        if let Err(e) = send_webhook_alert(webhook_url, event).await {
            error!(error = %e, "Failed to send webhook alert");
        }
    }

    // Telegram alerting
    if let Some(ref admin_chat_id) = config.alert_telegram_admin {
        // For Telegram alerting, we need a bot token from the environment
        // or config. For now, we check the TELEGRAM_BOT_TOKEN env var.
        if let Ok(bot_token) = std::env::var("TELEGRAM_BOT_TOKEN") {
            if let Err(e) = send_telegram_alert(&bot_token, admin_chat_id, event).await {
                error!(error = %e, "Failed to send Telegram alert");
            }
        } else {
            warn!("Telegram alerting configured but TELEGRAM_BOT_TOKEN not set");
        }
    }
}

// ── Health Endpoint Response ───────────────────────────────────────

/// Build the per-component health breakdown for the `/health` endpoint.
pub fn build_health_response(monitor: &HealthMonitor) -> serde_json::Value {
    let components: Vec<serde_json::Value> = monitor
        .status()
        .into_iter()
        .map(|c| {
            serde_json::json!({
                "name": c.name,
                "status": match &c.status {
                    HealthStatus::Healthy => "healthy".to_string(),
                    HealthStatus::Degraded { reason } => format!("degraded: {}", reason),
                    HealthStatus::Unhealthy { reason } => format!("unhealthy: {}", reason),
                },
                "consecutive_failures": c.consecutive_failures,
                "last_check": c.last_check.to_rfc3339(),
            })
        })
        .collect();

    serde_json::json!({
        "components": components,
    })
}

// ── Unit Tests ─────────────────────────────────────────────────────

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

    fn default_config() -> HealthMonitorConfig {
        HealthMonitorConfig {
            check_interval_secs: 60,
            failure_threshold: 3,
            alert_webhook_url: None,
            alert_telegram_admin: None,
        }
    }

    #[test]
    fn test_healthy_check_no_event() {
        let monitor = HealthMonitor::new(default_config());
        let event = monitor.record_check("channel", true);
        assert_eq!(event, None);
    }

    #[test]
    fn test_single_failure_no_alert() {
        let monitor = HealthMonitor::new(default_config());
        let event = monitor.record_check("channel", false);
        assert_eq!(event, None);
    }

    #[test]
    fn test_two_failures_no_alert() {
        let monitor = HealthMonitor::new(default_config());
        monitor.record_check("channel", false);
        let event = monitor.record_check("channel", false);
        assert_eq!(event, None);
    }

    #[test]
    fn test_three_failures_emits_alert() {
        let monitor = HealthMonitor::new(default_config());
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        let event = monitor.record_check("channel", false);
        assert_eq!(
            event,
            Some(HealthEvent::Alert {
                component: "channel".to_string(),
                failures: 3,
            })
        );
    }

    #[test]
    fn test_no_duplicate_alert_after_threshold() {
        let monitor = HealthMonitor::new(default_config());
        // Reach threshold
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        monitor.record_check("channel", false); // alert emitted here

        // Further failures should NOT emit another alert
        let event = monitor.record_check("channel", false);
        assert_eq!(event, None);

        let event = monitor.record_check("channel", false);
        assert_eq!(event, None);
    }

    #[test]
    fn test_recovery_after_alert() {
        let monitor = HealthMonitor::new(default_config());
        // Reach threshold
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        monitor.record_check("channel", false); // alert

        // Recovery
        let event = monitor.record_check("channel", true);
        assert_eq!(
            event,
            Some(HealthEvent::Recovery {
                component: "channel".to_string(),
            })
        );
    }

    #[test]
    fn test_no_recovery_without_prior_alert() {
        let monitor = HealthMonitor::new(default_config());
        // Two failures (below threshold, no alert)
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);

        // Recovery without having been alerted → no recovery event
        let event = monitor.record_check("channel", true);
        assert_eq!(event, None);
    }

    #[test]
    fn test_no_duplicate_recovery() {
        let monitor = HealthMonitor::new(default_config());
        // Alert
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);

        // First recovery
        let event = monitor.record_check("channel", true);
        assert_eq!(
            event,
            Some(HealthEvent::Recovery {
                component: "channel".to_string(),
            })
        );

        // Second healthy check → no duplicate recovery
        let event = monitor.record_check("channel", true);
        assert_eq!(event, None);
    }

    #[test]
    fn test_re_alert_after_recovery() {
        let monitor = HealthMonitor::new(default_config());
        // First alert cycle
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        monitor.record_check("channel", false); // alert

        // Recovery
        monitor.record_check("channel", true); // recovery

        // Second alert cycle
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        let event = monitor.record_check("channel", false);
        assert_eq!(
            event,
            Some(HealthEvent::Alert {
                component: "channel".to_string(),
                failures: 3,
            })
        );
    }

    #[test]
    fn test_multiple_components_independent() {
        let monitor = HealthMonitor::new(default_config());

        // Component A fails
        monitor.record_check("channel_a", false);
        monitor.record_check("channel_a", false);
        let event = monitor.record_check("channel_a", false);
        assert_eq!(
            event,
            Some(HealthEvent::Alert {
                component: "channel_a".to_string(),
                failures: 3,
            })
        );

        // Component B is healthy — no event
        let event = monitor.record_check("channel_b", true);
        assert_eq!(event, None);

        // Component B fails independently
        monitor.record_check("channel_b", false);
        monitor.record_check("channel_b", false);
        let event = monitor.record_check("channel_b", false);
        assert_eq!(
            event,
            Some(HealthEvent::Alert {
                component: "channel_b".to_string(),
                failures: 3,
            })
        );
    }

    #[test]
    fn test_status_returns_all_components() {
        let monitor = HealthMonitor::new(default_config());
        monitor.record_check("channel", true);
        monitor.record_check("model", false);
        monitor.record_check("session_store", true);

        let status = monitor.status();
        assert_eq!(status.len(), 3);
    }

    #[test]
    fn test_component_status() {
        let monitor = HealthMonitor::new(default_config());
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);

        let status = monitor.component_status("channel").unwrap();
        assert_eq!(status.consecutive_failures, 2);
        assert!(matches!(status.status, HealthStatus::Degraded { .. }));
    }

    #[test]
    fn test_custom_threshold() {
        let config = HealthMonitorConfig {
            check_interval_secs: 60,
            failure_threshold: 5,
            alert_webhook_url: None,
            alert_telegram_admin: None,
        };
        let monitor = HealthMonitor::new(config);

        // 4 failures — no alert (threshold is 5)
        for _ in 0..4 {
            let event = monitor.record_check("channel", false);
            assert_eq!(event, None);
        }

        // 5th failure — alert
        let event = monitor.record_check("channel", false);
        assert_eq!(
            event,
            Some(HealthEvent::Alert {
                component: "channel".to_string(),
                failures: 5,
            })
        );
    }

    #[test]
    fn test_failure_reset_on_success() {
        let monitor = HealthMonitor::new(default_config());
        // Two failures
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);

        // Success resets counter
        monitor.record_check("channel", true);

        // Need 3 more failures for alert
        monitor.record_check("channel", false);
        monitor.record_check("channel", false);
        let event = monitor.record_check("channel", false);
        assert_eq!(
            event,
            Some(HealthEvent::Alert {
                component: "channel".to_string(),
                failures: 3,
            })
        );
    }

    #[test]
    fn test_build_health_response() {
        let monitor = HealthMonitor::new(default_config());
        monitor.record_check("channel", true);
        monitor.record_check("model", false);

        let response = build_health_response(&monitor);
        let components = response["components"].as_array().unwrap();
        assert_eq!(components.len(), 2);
    }
}