1use crate::Alerter;
4use async_trait::async_trait;
5use reqwest::{Client, StatusCode};
6use llm_sentinel_core::{events::AnomalyEvent, Error, Result};
7use serde::{Deserialize, Serialize};
8use std::time::Duration;
9use tracing::{debug, error, info, warn};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct WebhookConfig {
14 pub url: String,
16 pub method: HttpMethod,
18 pub timeout_secs: u64,
20 pub headers: Vec<(String, String)>,
22 pub max_retries: u32,
24 pub retry_delay_ms: u64,
26 pub backoff_multiplier: f64,
28 pub secret: Option<String>,
30}
31
32impl Default for WebhookConfig {
33 fn default() -> Self {
34 Self {
35 url: String::new(),
36 method: HttpMethod::Post,
37 timeout_secs: 10,
38 headers: vec![("Content-Type".to_string(), "application/json".to_string())],
39 max_retries: 3,
40 retry_delay_ms: 1000,
41 backoff_multiplier: 2.0,
42 secret: None,
43 }
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
49pub enum HttpMethod {
50 #[serde(rename = "POST")]
51 Post,
52 #[serde(rename = "PUT")]
53 Put,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct WebhookPayload {
59 pub event_type: String,
61 pub timestamp: chrono::DateTime<chrono::Utc>,
63 pub data: AnomalyEvent,
65 #[serde(skip_serializing_if = "Option::is_none")]
67 pub signature: Option<String>,
68}
69
70pub struct WebhookAlerter {
72 client: Client,
73 config: WebhookConfig,
74}
75
76impl WebhookAlerter {
77 pub fn new(config: WebhookConfig) -> Result<Self> {
79 if config.url.is_empty() {
80 return Err(Error::config("Webhook URL cannot be empty"));
81 }
82
83 info!("Creating webhook alerter for {}", config.url);
84
85 let client = Client::builder()
86 .timeout(Duration::from_secs(config.timeout_secs))
87 .build()
88 .map_err(|e| Error::config(format!("Failed to create HTTP client: {}", e)))?;
89
90 Ok(Self { client, config })
91 }
92
93 fn generate_signature(&self, payload: &str) -> Option<String> {
95 self.config.secret.as_ref().map(|secret| {
96 use hmac::{Hmac, Mac};
97 use sha2::Sha256;
98
99 type HmacSha256 = Hmac<Sha256>;
100
101 let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
102 mac.update(payload.as_bytes());
103 let result = mac.finalize();
104 hex::encode(result.into_bytes())
105 })
106 }
107
108 async fn send_with_retry(&self, alert: &AnomalyEvent) -> Result<()> {
110 let mut payload = WebhookPayload {
111 event_type: "anomaly.detected".to_string(),
112 timestamp: chrono::Utc::now(),
113 data: alert.clone(),
114 signature: None,
115 };
116
117 let payload_json = serde_json::to_string(&payload).map_err(|e| {
118 Error::internal(format!("Failed to serialize webhook payload: {}", e))
119 })?;
120
121 if let Some(signature) = self.generate_signature(&payload_json) {
123 payload.signature = Some(signature);
124 }
125
126 let final_payload = serde_json::to_string(&payload).map_err(|e| {
127 Error::internal(format!("Failed to serialize webhook payload: {}", e))
128 })?;
129
130 let mut attempt = 0;
131 let mut delay = self.config.retry_delay_ms;
132
133 loop {
134 attempt += 1;
135
136 let mut request = match self.config.method {
137 HttpMethod::Post => self.client.post(&self.config.url),
138 HttpMethod::Put => self.client.put(&self.config.url),
139 };
140
141 for (key, value) in &self.config.headers {
143 request = request.header(key, value);
144 }
145
146 if let Some(ref sig) = payload.signature {
148 request = request.header("X-Sentinel-Signature", sig);
149 }
150
151 request = request.body(final_payload.clone());
152
153 match request.send().await {
154 Ok(response) => {
155 let status = response.status();
156
157 if status.is_success() {
158 debug!(
159 alert_id = %alert.alert_id,
160 url = %self.config.url,
161 status = %status,
162 attempt = attempt,
163 "Webhook sent successfully"
164 );
165
166 metrics::counter!("sentinel_webhook_success_total").increment(1);
167
168 if attempt > 1 {
169 metrics::counter!("sentinel_webhook_retries_total").increment(1);
170 }
171
172 return Ok(());
173 } else if Self::is_retryable_status(status) && attempt < self.config.max_retries
174 {
175 warn!(
176 alert_id = %alert.alert_id,
177 status = %status,
178 attempt = attempt,
179 delay_ms = delay,
180 "Webhook failed with retryable status, retrying..."
181 );
182
183 tokio::time::sleep(Duration::from_millis(delay)).await;
184
185 delay = (delay as f64 * self.config.backoff_multiplier) as u64;
186 } else {
187 let body = response.text().await.unwrap_or_default();
188
189 error!(
190 alert_id = %alert.alert_id,
191 status = %status,
192 body = %body,
193 attempts = attempt,
194 "Webhook failed with non-retryable status or max retries reached"
195 );
196
197 metrics::counter!("sentinel_webhook_failures_total").increment(1);
198
199 return Err(Error::alerting(format!(
200 "Webhook failed with status {}: {}",
201 status, body
202 )));
203 }
204 }
205 Err(e) => {
206 if attempt >= self.config.max_retries {
207 error!(
208 alert_id = %alert.alert_id,
209 attempts = attempt,
210 error = %e,
211 "Webhook failed after max retries"
212 );
213
214 metrics::counter!("sentinel_webhook_failures_total").increment(1);
215
216 return Err(Error::alerting(format!(
217 "Webhook failed after {} attempts: {}",
218 attempt, e
219 )));
220 }
221
222 warn!(
223 alert_id = %alert.alert_id,
224 attempt = attempt,
225 delay_ms = delay,
226 error = %e,
227 "Webhook request failed, retrying..."
228 );
229
230 tokio::time::sleep(Duration::from_millis(delay)).await;
231
232 delay = (delay as f64 * self.config.backoff_multiplier) as u64;
233 }
234 }
235 }
236 }
237
238 fn is_retryable_status(status: StatusCode) -> bool {
240 matches!(
241 status,
242 StatusCode::REQUEST_TIMEOUT
243 | StatusCode::TOO_MANY_REQUESTS
244 | StatusCode::INTERNAL_SERVER_ERROR
245 | StatusCode::BAD_GATEWAY
246 | StatusCode::SERVICE_UNAVAILABLE
247 | StatusCode::GATEWAY_TIMEOUT
248 )
249 }
250}
251
252#[async_trait]
253impl Alerter for WebhookAlerter {
254 async fn send(&self, alert: &AnomalyEvent) -> Result<()> {
255 self.send_with_retry(alert).await
256 }
257
258 async fn send_batch(&self, alerts: &[AnomalyEvent]) -> Result<()> {
259 if alerts.is_empty() {
260 return Ok(());
261 }
262
263 let mut errors = Vec::new();
264
265 for alert in alerts {
266 if let Err(e) = self.send(alert).await {
267 error!(
268 alert_id = %alert.alert_id,
269 error = %e,
270 "Failed to send webhook in batch"
271 );
272 errors.push(e);
273 }
274 }
275
276 if !errors.is_empty() {
277 return Err(Error::alerting(format!(
278 "Failed to send {} out of {} webhooks",
279 errors.len(),
280 alerts.len()
281 )));
282 }
283
284 info!("Successfully sent batch of {} webhooks", alerts.len());
285 Ok(())
286 }
287
288 async fn health_check(&self) -> Result<()> {
289 match self.client.head(&self.config.url).send().await {
291 Ok(response) => {
292 if response.status().is_success() || response.status() == StatusCode::METHOD_NOT_ALLOWED {
293 Ok(())
294 } else {
295 Err(Error::connection(format!(
296 "Webhook health check failed with status: {}",
297 response.status()
298 )))
299 }
300 }
301 Err(e) => Err(Error::connection(format!(
302 "Webhook health check failed: {}",
303 e
304 ))),
305 }
306 }
307
308 fn name(&self) -> &str {
309 "Webhook"
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316 use llm_sentinel_core::{
317 events::{AnomalyDetails, PromptInfo, ResponseInfo, TelemetryEvent},
318 types::{AnomalyType, DetectionMethod, ModelId, ServiceId, Severity},
319 };
320
321 fn create_test_config(url: &str) -> WebhookConfig {
322 WebhookConfig {
323 url: url.to_string(),
324 method: HttpMethod::Post,
325 timeout_secs: 5,
326 headers: vec![("Content-Type".to_string(), "application/json".to_string())],
327 max_retries: 2,
328 retry_delay_ms: 100,
329 backoff_multiplier: 2.0,
330 secret: Some("test-secret".to_string()),
331 }
332 }
333
334 fn create_test_anomaly() -> AnomalyEvent {
335 let telemetry = TelemetryEvent::new(
336 ServiceId::new("test-service"),
337 ModelId::new("gpt-4"),
338 PromptInfo {
339 text: "test".to_string(),
340 tokens: 10,
341 embedding: None,
342 },
343 ResponseInfo {
344 text: "response".to_string(),
345 tokens: 20,
346 finish_reason: "stop".to_string(),
347 embedding: None,
348 },
349 100.0,
350 0.01,
351 );
352
353 AnomalyEvent::new(
354 Severity::High,
355 AnomalyType::LatencySpike,
356 DetectionMethod::ZScore,
357 0.95,
358 AnomalyDetails {
359 metric: "latency_ms".to_string(),
360 value: 500.0,
361 baseline: 100.0,
362 threshold: 300.0,
363 deviation_percent: 400.0,
364 },
365 &telemetry,
366 )
367 }
368
369 #[test]
370 fn test_config_creation() {
371 let config = create_test_config("https://example.com/webhook");
372 assert_eq!(config.url, "https://example.com/webhook");
373 assert_eq!(config.method, HttpMethod::Post);
374 }
375
376 #[test]
377 fn test_empty_url_error() {
378 let config = WebhookConfig {
379 url: String::new(),
380 ..Default::default()
381 };
382
383 let result = WebhookAlerter::new(config);
384 assert!(result.is_err());
385 }
386
387 #[test]
388 fn test_retryable_status_codes() {
389 assert!(WebhookAlerter::is_retryable_status(
390 StatusCode::INTERNAL_SERVER_ERROR
391 ));
392 assert!(WebhookAlerter::is_retryable_status(
393 StatusCode::SERVICE_UNAVAILABLE
394 ));
395 assert!(WebhookAlerter::is_retryable_status(
396 StatusCode::TOO_MANY_REQUESTS
397 ));
398 assert!(!WebhookAlerter::is_retryable_status(StatusCode::NOT_FOUND));
399 assert!(!WebhookAlerter::is_retryable_status(StatusCode::BAD_REQUEST));
400 }
401
402 #[tokio::test]
403 async fn test_webhook_payload_serialization() {
404 let alert = create_test_anomaly();
405 let payload = WebhookPayload {
406 event_type: "anomaly.detected".to_string(),
407 timestamp: chrono::Utc::now(),
408 data: alert,
409 signature: Some("test-signature".to_string()),
410 };
411
412 let json = serde_json::to_string(&payload).unwrap();
413 assert!(json.contains("anomaly.detected"));
414 assert!(json.contains("test-signature"));
415 }
416
417 #[tokio::test]
419 async fn test_successful_webhook() {
420 use wiremock::{matchers::*, Mock, MockServer, ResponseTemplate};
421
422 let mock_server = MockServer::start().await;
423
424 Mock::given(method("POST"))
425 .and(path("/webhook"))
426 .and(header("Content-Type", "application/json"))
427 .respond_with(ResponseTemplate::new(200))
428 .expect(1)
429 .mount(&mock_server)
430 .await;
431
432 let config = create_test_config(&format!("{}/webhook", mock_server.uri()));
433 let alerter = WebhookAlerter::new(config).unwrap();
434 let alert = create_test_anomaly();
435
436 let result = alerter.send(&alert).await;
437 assert!(result.is_ok());
438 }
439
440 #[tokio::test]
441 async fn test_webhook_retry_on_500() {
442 use wiremock::{matchers::*, Mock, MockServer, ResponseTemplate};
443
444 let mock_server = MockServer::start().await;
445
446 Mock::given(method("POST"))
448 .and(path("/webhook"))
449 .respond_with(ResponseTemplate::new(500))
450 .up_to_n_times(1)
451 .mount(&mock_server)
452 .await;
453
454 Mock::given(method("POST"))
455 .and(path("/webhook"))
456 .respond_with(ResponseTemplate::new(200))
457 .expect(1)
458 .mount(&mock_server)
459 .await;
460
461 let config = create_test_config(&format!("{}/webhook", mock_server.uri()));
462 let alerter = WebhookAlerter::new(config).unwrap();
463 let alert = create_test_anomaly();
464
465 let result = alerter.send(&alert).await;
466 assert!(result.is_ok());
467 }
468
469 #[tokio::test]
470 async fn test_webhook_max_retries_exceeded() {
471 use wiremock::{matchers::*, Mock, MockServer, ResponseTemplate};
472
473 let mock_server = MockServer::start().await;
474
475 Mock::given(method("POST"))
477 .and(path("/webhook"))
478 .respond_with(ResponseTemplate::new(500))
479 .mount(&mock_server)
480 .await;
481
482 let config = create_test_config(&format!("{}/webhook", mock_server.uri()));
483 let alerter = WebhookAlerter::new(config).unwrap();
484 let alert = create_test_anomaly();
485
486 let result = alerter.send(&alert).await;
487 assert!(result.is_err());
488 }
489}