mockforge-reporting 0.3.130

Report generation and visualization for MockForge
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
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
//! PDF report generation for orchestration execution results

use crate::{ReportingError, Result};
use chrono::{DateTime, Utc};
use printpdf::*;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::BufWriter;

/// PDF generation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PdfConfig {
    pub title: String,
    pub author: String,
    pub include_charts: bool,
    pub include_metrics: bool,
    pub include_recommendations: bool,
}

impl Default for PdfConfig {
    fn default() -> Self {
        Self {
            title: "Chaos Orchestration Report".to_string(),
            author: "MockForge".to_string(),
            include_charts: true,
            include_metrics: true,
            include_recommendations: true,
        }
    }
}

/// Execution report data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionReport {
    pub orchestration_name: String,
    pub start_time: DateTime<Utc>,
    pub end_time: DateTime<Utc>,
    pub duration_seconds: u64,
    pub status: String,
    pub total_steps: usize,
    pub completed_steps: usize,
    pub failed_steps: usize,
    pub metrics: ReportMetrics,
    pub failures: Vec<FailureDetail>,
    pub recommendations: Vec<String>,
}

/// Report metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportMetrics {
    pub total_requests: u64,
    pub successful_requests: u64,
    pub failed_requests: u64,
    pub avg_latency_ms: f64,
    pub p95_latency_ms: f64,
    pub p99_latency_ms: f64,
    pub error_rate: f64,
}

/// Failure detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureDetail {
    pub step_name: String,
    pub error_message: String,
    pub timestamp: DateTime<Utc>,
}

/// PDF report generator
pub struct PdfReportGenerator {
    config: PdfConfig,
}

impl PdfReportGenerator {
    /// Create a new PDF generator
    pub fn new(config: PdfConfig) -> Self {
        Self { config }
    }

    /// Generate PDF report from execution data
    pub fn generate(&self, report: &ExecutionReport, output_path: &str) -> Result<()> {
        let (doc, page1, layer1) =
            PdfDocument::new(&self.config.title, Mm(210.0), Mm(297.0), "Layer 1");

        let font = doc
            .add_builtin_font(BuiltinFont::Helvetica)
            .map_err(|e| ReportingError::Pdf(e.to_string()))?;
        let font_bold = doc
            .add_builtin_font(BuiltinFont::HelveticaBold)
            .map_err(|e| ReportingError::Pdf(e.to_string()))?;

        let current_layer = doc.get_page(page1).get_layer(layer1);

        // Title
        current_layer.use_text(&self.config.title, 24.0, Mm(20.0), Mm(270.0), &font_bold);

        // Metadata
        let mut y = 255.0;
        current_layer.use_text(
            format!("Orchestration: {}", report.orchestration_name),
            12.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        y -= 7.0;
        current_layer.use_text(
            format!("Start: {}", report.start_time.format("%Y-%m-%d %H:%M:%S UTC")),
            10.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        y -= 5.0;
        current_layer.use_text(
            format!("End: {}", report.end_time.format("%Y-%m-%d %H:%M:%S UTC")),
            10.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        y -= 5.0;
        current_layer.use_text(
            format!("Duration: {}s", report.duration_seconds),
            10.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        y -= 5.0;
        current_layer.use_text(
            format!("Status: {}", report.status),
            10.0,
            Mm(20.0),
            Mm(y),
            &font_bold,
        );

        // Summary section
        y -= 15.0;
        current_layer.use_text("Summary", 14.0, Mm(20.0), Mm(y), &font_bold);

        y -= 7.0;
        current_layer.use_text(
            format!("Total Steps: {}", report.total_steps),
            10.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        y -= 5.0;
        current_layer.use_text(
            format!("Completed: {}", report.completed_steps),
            10.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        y -= 5.0;
        current_layer.use_text(
            format!("Failed: {}", report.failed_steps),
            10.0,
            Mm(20.0),
            Mm(y),
            &font,
        );

        // Metrics section
        if self.config.include_metrics {
            y -= 15.0;
            current_layer.use_text("Metrics", 14.0, Mm(20.0), Mm(y), &font_bold);

            y -= 7.0;
            current_layer.use_text(
                format!("Total Requests: {}", report.metrics.total_requests),
                10.0,
                Mm(20.0),
                Mm(y),
                &font,
            );

            y -= 5.0;
            current_layer.use_text(
                format!("Error Rate: {:.2}%", report.metrics.error_rate * 100.0),
                10.0,
                Mm(20.0),
                Mm(y),
                &font,
            );

            y -= 5.0;
            current_layer.use_text(
                format!("Avg Latency: {:.2}ms", report.metrics.avg_latency_ms),
                10.0,
                Mm(20.0),
                Mm(y),
                &font,
            );

            y -= 5.0;
            current_layer.use_text(
                format!("P95 Latency: {:.2}ms", report.metrics.p95_latency_ms),
                10.0,
                Mm(20.0),
                Mm(y),
                &font,
            );
        }

        // Charts section (text-based metric visualization)
        if self.config.include_charts {
            y -= 15.0;
            current_layer.use_text("Performance Overview", 14.0, Mm(20.0), Mm(y), &font_bold);

            // Success rate bar
            y -= 8.0;
            let success_rate = if report.metrics.total_requests > 0 {
                report.metrics.successful_requests as f64 / report.metrics.total_requests as f64
            } else {
                0.0
            };
            let bar_len = (success_rate * 30.0) as usize;
            let bar =
                format!("Success Rate: [{:>30}] {:.1}%", "#".repeat(bar_len), success_rate * 100.0);
            current_layer.use_text(bar, 9.0, Mm(20.0), Mm(y), &font);

            // Step completion bar
            y -= 6.0;
            let step_rate = if report.total_steps > 0 {
                report.completed_steps as f64 / report.total_steps as f64
            } else {
                0.0
            };
            let bar_len = (step_rate * 30.0) as usize;
            let bar =
                format!("Steps Done:   [{:>30}] {:.1}%", "#".repeat(bar_len), step_rate * 100.0);
            current_layer.use_text(bar, 9.0, Mm(20.0), Mm(y), &font);

            // Latency breakdown
            y -= 6.0;
            current_layer.use_text(
                format!(
                    "Latency (ms):  avg={:.1}  p95={:.1}  p99={:.1}",
                    report.metrics.avg_latency_ms,
                    report.metrics.p95_latency_ms,
                    report.metrics.p99_latency_ms,
                ),
                9.0,
                Mm(20.0),
                Mm(y),
                &font,
            );
        }

        // Failures section
        if !report.failures.is_empty() {
            y -= 15.0;
            current_layer.use_text("Failures", 14.0, Mm(20.0), Mm(y), &font_bold);

            for failure in &report.failures {
                y -= 7.0;
                if y < 20.0 {
                    break; // Page boundary - would need to add new page
                }
                current_layer.use_text(
                    format!("• {}: {}", failure.step_name, failure.error_message),
                    9.0,
                    Mm(25.0),
                    Mm(y),
                    &font,
                );
            }
        }

        // Recommendations section
        if self.config.include_recommendations && !report.recommendations.is_empty() {
            y -= 15.0;
            current_layer.use_text("Recommendations", 14.0, Mm(20.0), Mm(y), &font_bold);

            for recommendation in &report.recommendations {
                y -= 7.0;
                if y < 20.0 {
                    break;
                }
                current_layer.use_text(
                    format!("• {}", recommendation),
                    9.0,
                    Mm(25.0),
                    Mm(y),
                    &font,
                );
            }
        }

        // Footer
        current_layer.use_text(
            format!("Generated by MockForge on {}", Utc::now().format("%Y-%m-%d %H:%M UTC")),
            8.0,
            Mm(20.0),
            Mm(10.0),
            &font,
        );

        // Save PDF
        doc.save(&mut BufWriter::new(File::create(output_path)?))
            .map_err(|e| ReportingError::Pdf(e.to_string()))?;

        Ok(())
    }
}

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

    fn create_test_report() -> ExecutionReport {
        ExecutionReport {
            orchestration_name: "test-orch".to_string(),
            start_time: Utc::now(),
            end_time: Utc::now(),
            duration_seconds: 120,
            status: "Completed".to_string(),
            total_steps: 5,
            completed_steps: 5,
            failed_steps: 0,
            metrics: ReportMetrics {
                total_requests: 1000,
                successful_requests: 980,
                failed_requests: 20,
                avg_latency_ms: 125.5,
                p95_latency_ms: 250.0,
                p99_latency_ms: 350.0,
                error_rate: 0.02,
            },
            failures: vec![],
            recommendations: vec!["Increase timeout thresholds".to_string()],
        }
    }

    #[test]
    fn test_pdf_generation() {
        let config = PdfConfig::default();
        let generator = PdfReportGenerator::new(config);
        let report = create_test_report();

        let temp_dir = tempdir().unwrap();
        let output_path = temp_dir.path().join("report.pdf");

        let result = generator.generate(&report, output_path.to_str().unwrap());
        assert!(result.is_ok());
        assert!(output_path.exists());
    }

    #[test]
    fn test_pdf_config_default() {
        let config = PdfConfig::default();
        assert_eq!(config.title, "Chaos Orchestration Report");
        assert_eq!(config.author, "MockForge");
        assert!(config.include_charts);
        assert!(config.include_metrics);
        assert!(config.include_recommendations);
    }

    #[test]
    fn test_pdf_config_custom() {
        let config = PdfConfig {
            title: "Custom Report".to_string(),
            author: "Test Author".to_string(),
            include_charts: false,
            include_metrics: true,
            include_recommendations: false,
        };

        assert_eq!(config.title, "Custom Report");
        assert_eq!(config.author, "Test Author");
        assert!(!config.include_charts);
        assert!(config.include_metrics);
        assert!(!config.include_recommendations);
    }

    #[test]
    fn test_pdf_config_clone() {
        let config = PdfConfig::default();
        let cloned = config.clone();
        assert_eq!(config.title, cloned.title);
        assert_eq!(config.author, cloned.author);
    }

    #[test]
    fn test_pdf_config_serialize() {
        let config = PdfConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("title"));
        assert!(json.contains("author"));
        assert!(json.contains("include_charts"));
    }

    #[test]
    fn test_pdf_config_deserialize() {
        let json = r#"{"title":"Test","author":"Author","include_charts":true,"include_metrics":false,"include_recommendations":true}"#;
        let config: PdfConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.title, "Test");
        assert_eq!(config.author, "Author");
        assert!(config.include_charts);
        assert!(!config.include_metrics);
    }

    #[test]
    fn test_execution_report_clone() {
        let report = create_test_report();
        let cloned = report.clone();
        assert_eq!(report.orchestration_name, cloned.orchestration_name);
        assert_eq!(report.duration_seconds, cloned.duration_seconds);
    }

    #[test]
    fn test_execution_report_serialize() {
        let report = create_test_report();
        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("orchestration_name"));
        assert!(json.contains("metrics"));
        assert!(json.contains("status"));
    }

    #[test]
    fn test_report_metrics_clone() {
        let metrics = ReportMetrics {
            total_requests: 1000,
            successful_requests: 980,
            failed_requests: 20,
            avg_latency_ms: 100.0,
            p95_latency_ms: 200.0,
            p99_latency_ms: 300.0,
            error_rate: 0.02,
        };

        let cloned = metrics.clone();
        assert_eq!(metrics.total_requests, cloned.total_requests);
        assert_eq!(metrics.error_rate, cloned.error_rate);
    }

    #[test]
    fn test_report_metrics_serialize() {
        let metrics = ReportMetrics {
            total_requests: 1000,
            successful_requests: 980,
            failed_requests: 20,
            avg_latency_ms: 100.0,
            p95_latency_ms: 200.0,
            p99_latency_ms: 300.0,
            error_rate: 0.02,
        };

        let json = serde_json::to_string(&metrics).unwrap();
        assert!(json.contains("total_requests"));
        assert!(json.contains("error_rate"));
    }

    #[test]
    fn test_failure_detail_clone() {
        let failure = FailureDetail {
            step_name: "auth-step".to_string(),
            error_message: "Connection timeout".to_string(),
            timestamp: Utc::now(),
        };

        let cloned = failure.clone();
        assert_eq!(failure.step_name, cloned.step_name);
        assert_eq!(failure.error_message, cloned.error_message);
    }

    #[test]
    fn test_failure_detail_serialize() {
        let failure = FailureDetail {
            step_name: "auth-step".to_string(),
            error_message: "Connection timeout".to_string(),
            timestamp: Utc::now(),
        };

        let json = serde_json::to_string(&failure).unwrap();
        assert!(json.contains("step_name"));
        assert!(json.contains("error_message"));
        assert!(json.contains("timestamp"));
    }

    #[test]
    fn test_pdf_with_failures() {
        let config = PdfConfig::default();
        let generator = PdfReportGenerator::new(config);

        let mut report = create_test_report();
        report.failures = vec![
            FailureDetail {
                step_name: "auth-step".to_string(),
                error_message: "Connection timeout".to_string(),
                timestamp: Utc::now(),
            },
            FailureDetail {
                step_name: "data-step".to_string(),
                error_message: "Invalid response".to_string(),
                timestamp: Utc::now(),
            },
        ];
        report.failed_steps = 2;

        let temp_dir = tempdir().unwrap();
        let output_path = temp_dir.path().join("report_with_failures.pdf");

        let result = generator.generate(&report, output_path.to_str().unwrap());
        assert!(result.is_ok());
        assert!(output_path.exists());
    }

    #[test]
    fn test_pdf_without_metrics() {
        let config = PdfConfig {
            include_metrics: false,
            ..PdfConfig::default()
        };
        let generator = PdfReportGenerator::new(config);
        let report = create_test_report();

        let temp_dir = tempdir().unwrap();
        let output_path = temp_dir.path().join("report_no_metrics.pdf");

        let result = generator.generate(&report, output_path.to_str().unwrap());
        assert!(result.is_ok());
    }

    #[test]
    fn test_pdf_without_recommendations() {
        let config = PdfConfig {
            include_recommendations: false,
            ..PdfConfig::default()
        };
        let generator = PdfReportGenerator::new(config);

        let mut report = create_test_report();
        report.recommendations = vec![];

        let temp_dir = tempdir().unwrap();
        let output_path = temp_dir.path().join("report_no_recs.pdf");

        let result = generator.generate(&report, output_path.to_str().unwrap());
        assert!(result.is_ok());
    }

    #[test]
    fn test_pdf_generator_invalid_path() {
        let config = PdfConfig::default();
        let generator = PdfReportGenerator::new(config);
        let report = create_test_report();

        let result = generator.generate(&report, "/nonexistent/path/report.pdf");
        assert!(result.is_err());
    }

    #[test]
    fn test_pdf_config_debug() {
        let config = PdfConfig::default();
        let debug = format!("{:?}", config);
        assert!(debug.contains("PdfConfig"));
    }

    #[test]
    fn test_execution_report_debug() {
        let report = create_test_report();
        let debug = format!("{:?}", report);
        assert!(debug.contains("ExecutionReport"));
    }

    #[test]
    fn test_report_metrics_debug() {
        let metrics = ReportMetrics {
            total_requests: 1000,
            successful_requests: 980,
            failed_requests: 20,
            avg_latency_ms: 100.0,
            p95_latency_ms: 200.0,
            p99_latency_ms: 300.0,
            error_rate: 0.02,
        };
        let debug = format!("{:?}", metrics);
        assert!(debug.contains("ReportMetrics"));
    }
}