mockforge-chaos 0.3.21

Chaos engineering features for MockForge - fault injection and resilience testing
Documentation
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntegrationConfig {
    pub slack: Option<SlackConfig>,
    pub teams: Option<TeamsConfig>,
    pub jira: Option<JiraConfig>,
    pub pagerduty: Option<PagerDutyConfig>,
    pub grafana: Option<GrafanaConfig>,
}

/// Slack integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlackConfig {
    pub webhook_url: String,
    pub channel: String,
    pub username: Option<String>,
    pub icon_emoji: Option<String>,
    pub mention_users: Vec<String>,
}

/// Microsoft Teams integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamsConfig {
    pub webhook_url: String,
    pub mention_users: Vec<String>,
}

/// Jira integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraConfig {
    pub url: String,
    pub username: String,
    pub api_token: String,
    pub project_key: String,
    pub issue_type: String,
    pub priority: Option<String>,
    pub assignee: Option<String>,
}

/// PagerDuty integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PagerDutyConfig {
    pub routing_key: String,
    pub severity: Option<String>,
    pub dedup_key_prefix: Option<String>,
}

/// Grafana integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GrafanaConfig {
    pub url: String,
    pub api_key: String,
    pub dashboard_uid: Option<String>,
    pub folder_uid: Option<String>,
}

/// Notification severity
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum NotificationSeverity {
    Info,
    Warning,
    Error,
    Critical,
}

/// Notification message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Notification {
    pub title: String,
    pub message: String,
    pub severity: NotificationSeverity,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Slack notifier
pub struct SlackNotifier {
    config: SlackConfig,
    client: reqwest::Client,
}

impl SlackNotifier {
    pub fn new(config: SlackConfig) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    pub async fn send(&self, notification: &Notification) -> Result<()> {
        let color = match notification.severity {
            NotificationSeverity::Info => "#36a64f",
            NotificationSeverity::Warning => "#ff9900",
            NotificationSeverity::Error => "#ff0000",
            NotificationSeverity::Critical => "#8b0000",
        };

        let mentions = if !self.config.mention_users.is_empty() {
            format!(
                "\n{}",
                self.config
                    .mention_users
                    .iter()
                    .map(|u| format!("<@{}>", u))
                    .collect::<Vec<_>>()
                    .join(" ")
            )
        } else {
            String::new()
        };

        let payload = serde_json::json!({
            "channel": self.config.channel,
            "username": self.config.username.as_deref().unwrap_or("MockForge"),
            "icon_emoji": self.config.icon_emoji.as_deref().unwrap_or(":robot_face:"),
            "attachments": [{
                "color": color,
                "title": notification.title,
                "text": format!("{}{}", notification.message, mentions),
                "timestamp": notification.timestamp.timestamp(),
                "fields": notification.metadata.iter().map(|(k, v)| {
                    serde_json::json!({
                        "title": k,
                        "value": v.to_string(),
                        "short": true
                    })
                }).collect::<Vec<_>>()
            }]
        });

        self.client
            .post(&self.config.webhook_url)
            .json(&payload)
            .send()
            .await
            .context("Failed to send Slack notification")?;

        Ok(())
    }
}

/// Microsoft Teams notifier
pub struct TeamsNotifier {
    config: TeamsConfig,
    client: reqwest::Client,
}

impl TeamsNotifier {
    pub fn new(config: TeamsConfig) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    pub async fn send(&self, notification: &Notification) -> Result<()> {
        let theme_color = match notification.severity {
            NotificationSeverity::Info => "0078D4",
            NotificationSeverity::Warning => "FFA500",
            NotificationSeverity::Error => "FF0000",
            NotificationSeverity::Critical => "8B0000",
        };

        let mentions = if !self.config.mention_users.is_empty() {
            format!(
                "\n\n{}",
                self.config
                    .mention_users
                    .iter()
                    .map(|u| format!("<at>{}</at>", u))
                    .collect::<Vec<_>>()
                    .join(" ")
            )
        } else {
            String::new()
        };

        let facts: Vec<_> = notification
            .metadata
            .iter()
            .map(|(k, v)| {
                serde_json::json!({
                    "name": k,
                    "value": v.to_string()
                })
            })
            .collect();

        let payload = serde_json::json!({
            "@type": "MessageCard",
            "@context": "https://schema.org/extensions",
            "themeColor": theme_color,
            "summary": notification.title,
            "sections": [{
                "activityTitle": notification.title,
                "activitySubtitle": format!("Severity: {:?}", notification.severity),
                "text": format!("{}{}", notification.message, mentions),
                "facts": facts
            }]
        });

        self.client
            .post(&self.config.webhook_url)
            .json(&payload)
            .send()
            .await
            .context("Failed to send Teams notification")?;

        Ok(())
    }
}

/// Jira ticket creator
pub struct JiraIntegration {
    config: JiraConfig,
    client: reqwest::Client,
}

impl JiraIntegration {
    pub fn new(config: JiraConfig) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    pub async fn create_ticket(&self, notification: &Notification) -> Result<String> {
        let description = format!(
            "{}\n\n*Metadata:*\n{}",
            notification.message,
            notification
                .metadata
                .iter()
                .map(|(k, v)| format!("* {}: {}", k, v))
                .collect::<Vec<_>>()
                .join("\n")
        );

        let priority = self.config.priority.as_deref().or({
            Some(match notification.severity {
                NotificationSeverity::Critical => "Highest",
                NotificationSeverity::Error => "High",
                NotificationSeverity::Warning => "Medium",
                NotificationSeverity::Info => "Low",
            })
        });

        let mut fields = serde_json::json!({
            "project": {
                "key": self.config.project_key
            },
            "summary": notification.title,
            "description": description,
            "issuetype": {
                "name": self.config.issue_type
            }
        });

        if let Some(priority) = priority {
            fields["priority"] = serde_json::json!({ "name": priority });
        }

        if let Some(assignee) = &self.config.assignee {
            fields["assignee"] = serde_json::json!({ "name": assignee });
        }

        let payload = serde_json::json!({ "fields": fields });

        let url = format!("{}/rest/api/2/issue", self.config.url);

        let response = self
            .client
            .post(&url)
            .basic_auth(&self.config.username, Some(&self.config.api_token))
            .json(&payload)
            .send()
            .await
            .context("Failed to create Jira ticket")?;

        let result: serde_json::Value = response.json().await?;
        let ticket_key = result["key"]
            .as_str()
            .context("Failed to get ticket key from response")?
            .to_string();

        Ok(ticket_key)
    }

    pub async fn update_ticket(&self, ticket_key: &str, comment: &str) -> Result<()> {
        let payload = serde_json::json!({
            "body": comment
        });

        let url = format!("{}/rest/api/2/issue/{}/comment", self.config.url, ticket_key);

        self.client
            .post(&url)
            .basic_auth(&self.config.username, Some(&self.config.api_token))
            .json(&payload)
            .send()
            .await
            .context("Failed to add comment to Jira ticket")?;

        Ok(())
    }
}

/// PagerDuty integration
pub struct PagerDutyIntegration {
    config: PagerDutyConfig,
    client: reqwest::Client,
}

impl PagerDutyIntegration {
    pub fn new(config: PagerDutyConfig) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    pub async fn trigger_incident(&self, notification: &Notification) -> Result<String> {
        let severity = self.config.severity.as_deref().or({
            Some(match notification.severity {
                NotificationSeverity::Critical => "critical",
                NotificationSeverity::Error => "error",
                NotificationSeverity::Warning => "warning",
                NotificationSeverity::Info => "info",
            })
        });

        let dedup_key = format!(
            "{}-{}",
            self.config.dedup_key_prefix.as_deref().unwrap_or("mockforge"),
            notification.timestamp.timestamp()
        );

        let payload = serde_json::json!({
            "routing_key": self.config.routing_key,
            "event_action": "trigger",
            "dedup_key": dedup_key,
            "payload": {
                "summary": notification.title,
                "severity": severity,
                "source": "MockForge",
                "timestamp": notification.timestamp.to_rfc3339(),
                "custom_details": notification.metadata
            }
        });

        let response = self
            .client
            .post("https://events.pagerduty.com/v2/enqueue")
            .json(&payload)
            .send()
            .await
            .context("Failed to trigger PagerDuty incident")?;

        let _result: serde_json::Value = response.json().await?;
        Ok(dedup_key)
    }

    pub async fn resolve_incident(&self, dedup_key: &str) -> Result<()> {
        let payload = serde_json::json!({
            "routing_key": self.config.routing_key,
            "event_action": "resolve",
            "dedup_key": dedup_key
        });

        self.client
            .post("https://events.pagerduty.com/v2/enqueue")
            .json(&payload)
            .send()
            .await
            .context("Failed to resolve PagerDuty incident")?;

        Ok(())
    }
}

/// Grafana integration
pub struct GrafanaIntegration {
    config: GrafanaConfig,
    client: reqwest::Client,
}

impl GrafanaIntegration {
    pub fn new(config: GrafanaConfig) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    pub async fn create_annotation(&self, notification: &Notification) -> Result<()> {
        let tags = vec![
            format!("severity:{:?}", notification.severity).to_lowercase(),
            "mockforge".to_string(),
        ];

        let payload = serde_json::json!({
            "text": notification.message,
            "tags": tags,
            "time": notification.timestamp.timestamp_millis(),
            "dashboardUID": self.config.dashboard_uid
        });

        let url = format!("{}/api/annotations", self.config.url);

        self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .json(&payload)
            .send()
            .await
            .context("Failed to create Grafana annotation")?;

        Ok(())
    }

    pub async fn create_dashboard(&self, dashboard_json: serde_json::Value) -> Result<String> {
        let payload = serde_json::json!({
            "dashboard": dashboard_json,
            "folderUid": self.config.folder_uid,
            "overwrite": false
        });

        let url = format!("{}/api/dashboards/db", self.config.url);

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .json(&payload)
            .send()
            .await
            .context("Failed to create Grafana dashboard")?;

        let result: serde_json::Value = response.json().await?;
        let uid = result["uid"].as_str().context("Failed to get dashboard UID")?.to_string();

        Ok(uid)
    }
}

/// Integration manager
pub struct IntegrationManager {
    slack: Option<SlackNotifier>,
    teams: Option<TeamsNotifier>,
    jira: Option<JiraIntegration>,
    pagerduty: Option<PagerDutyIntegration>,
    grafana: Option<GrafanaIntegration>,
}

impl IntegrationManager {
    pub fn new(config: IntegrationConfig) -> Self {
        Self {
            slack: config.slack.map(SlackNotifier::new),
            teams: config.teams.map(TeamsNotifier::new),
            jira: config.jira.map(JiraIntegration::new),
            pagerduty: config.pagerduty.map(PagerDutyIntegration::new),
            grafana: config.grafana.map(GrafanaIntegration::new),
        }
    }

    /// Send notification to all configured channels
    pub async fn notify(&self, notification: &Notification) -> Result<NotificationResults> {
        let mut results = NotificationResults::default();

        // Send to Slack
        if let Some(slack) = &self.slack {
            match slack.send(notification).await {
                Ok(_) => results.slack_sent = true,
                Err(e) => results.errors.push(format!("Slack: {}", e)),
            }
        }

        // Send to Teams
        if let Some(teams) = &self.teams {
            match teams.send(notification).await {
                Ok(_) => results.teams_sent = true,
                Err(e) => results.errors.push(format!("Teams: {}", e)),
            }
        }

        // Create Jira ticket for errors and critical
        if let Some(jira) = &self.jira {
            if matches!(
                notification.severity,
                NotificationSeverity::Error | NotificationSeverity::Critical
            ) {
                match jira.create_ticket(notification).await {
                    Ok(key) => {
                        results.jira_ticket = Some(key);
                    }
                    Err(e) => results.errors.push(format!("Jira: {}", e)),
                }
            }
        }

        // Trigger PagerDuty incident for critical
        if let Some(pd) = &self.pagerduty {
            if notification.severity == NotificationSeverity::Critical {
                match pd.trigger_incident(notification).await {
                    Ok(key) => {
                        results.pagerduty_incident = Some(key);
                    }
                    Err(e) => results.errors.push(format!("PagerDuty: {}", e)),
                }
            }
        }

        // Create Grafana annotation
        if let Some(grafana) = &self.grafana {
            match grafana.create_annotation(notification).await {
                Ok(_) => results.grafana_annotated = true,
                Err(e) => results.errors.push(format!("Grafana: {}", e)),
            }
        }

        Ok(results)
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct NotificationResults {
    pub slack_sent: bool,
    pub teams_sent: bool,
    pub jira_ticket: Option<String>,
    pub pagerduty_incident: Option<String>,
    pub grafana_annotated: bool,
    pub errors: Vec<String>,
}

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

    #[test]
    fn test_notification_creation() {
        let notification = Notification {
            title: "Test Alert".to_string(),
            message: "This is a test".to_string(),
            severity: NotificationSeverity::Warning,
            timestamp: chrono::Utc::now(),
            metadata: HashMap::new(),
        };

        assert_eq!(notification.severity, NotificationSeverity::Warning);
    }
}