copybook-core 0.4.3

Core COBOL copybook parser, schema, and validation primitives.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Performance Audit Subsystem
//!
//! Tracks processing performance metrics, baseline management, and regression
//! detection for copybook-rs enterprise mainframe data processing operations.

use crate::{Error, ErrorCode, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

/// Performance audit system for tracking and validating processing metrics
pub struct PerformanceAuditor {
    baseline_manager: BaselineManager,
    regression_detector: RegressionDetector,
}

impl PerformanceAuditor {
    /// Creates a new PerformanceAuditor.
    ///
    /// # Arguments
    ///
    /// * `baseline_path` - The path to the performance baseline file.
    /// * `regression_threshold` - The percentage threshold for detecting a performance regression.
    pub fn new(baseline_path: impl AsRef<Path>, regression_threshold: f64) -> Self {
        Self {
            baseline_manager: BaselineManager::new(baseline_path),
            regression_detector: RegressionDetector::new().with_threshold(regression_threshold),
        }
    }

    /// Audits the current performance metrics against the baseline.
    ///
    /// # Arguments
    ///
    /// * `current_metrics` - The performance metrics of the current run.
    ///
    /// # Errors
    /// Returns an error if the baseline file cannot be loaded or parsed.
    #[inline]
    #[must_use = "Handle the Result or propagate the error"]
    pub fn audit(&self, current_metrics: &ThroughputMetrics) -> Result<Vec<String>> {
        let baseline = self.baseline_manager.load_baseline()?;
        let regressions = self
            .regression_detector
            .check_regression(current_metrics, &baseline.throughput);
        Ok(regressions)
    }
}

/// Performance baseline management
#[derive(Debug, Clone)]
pub struct BaselineManager {
    baseline_path: PathBuf,
}

impl BaselineManager {
    /// Creates a new BaselineManager.
    pub fn new(baseline_path: impl AsRef<Path>) -> Self {
        Self {
            baseline_path: baseline_path.as_ref().to_path_buf(),
        }
    }

    /// Loads the performance baseline from the specified file.
    ///
    /// # Errors
    /// Returns an error if the baseline file cannot be read or parsed.
    #[inline]
    #[must_use = "Handle the Result or propagate the error"]
    pub fn load_baseline(&self) -> Result<PerformanceBaseline> {
        let data = fs::read_to_string(&self.baseline_path).map_err(|e| {
            Error::new(
                ErrorCode::CBKA001_BASELINE_ERROR,
                format!("Failed to read baseline file: {}", e),
            )
        })?;
        let baseline = serde_json::from_str(&data).map_err(|e| {
            Error::new(
                ErrorCode::CBKA001_BASELINE_ERROR,
                format!("Failed to parse baseline file: {}", e),
            )
        })?;
        Ok(baseline)
    }

    /// Saves a performance baseline to the specified file.
    ///
    /// # Errors
    /// Returns an error if the baseline file cannot be serialized or written.
    #[inline]
    #[must_use = "Handle the Result or propagate the error"]
    pub fn save_baseline(&self, baseline: &PerformanceBaseline) -> Result<()> {
        let data = serde_json::to_string_pretty(baseline).map_err(|e| {
            Error::new(
                ErrorCode::CBKA001_BASELINE_ERROR,
                format!("Failed to serialize baseline: {}", e),
            )
        })?;
        fs::write(&self.baseline_path, data).map_err(|e| {
            Error::new(
                ErrorCode::CBKA001_BASELINE_ERROR,
                format!("Failed to write baseline file: {}", e),
            )
        })
    }
}

/// Performance baseline data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceBaseline {
    /// Unique identifier for this baseline snapshot.
    pub baseline_id: String,
    /// Throughput metrics captured in this baseline.
    pub throughput: ThroughputMetrics,
    /// Resource utilization metrics captured in this baseline.
    pub resources: ResourceMetrics,
    /// ISO 8601 timestamp when this baseline was created.
    pub created_at: String,
}

/// Throughput performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThroughputMetrics {
    /// Throughput in bytes per second for DISPLAY fields.
    pub display_throughput: u64,
    /// Throughput in bytes per second for COMP-3 fields.
    pub comp3_throughput: u64,
    /// Record processing rate in records per second.
    pub record_rate: u64,
    /// Peak memory usage in megabytes.
    pub peak_memory_mb: u64,
}

/// System resource utilization metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceMetrics {
    /// CPU utilization as a percentage (0.0–100.0).
    pub cpu_usage_percent: f64,
    /// Memory usage in megabytes.
    pub memory_usage_mb: u64,
    /// Total number of I/O operations performed.
    pub io_operations: u64,
    /// Total network bytes transferred.
    pub network_bytes: u64,
}

/// Performance regression detection
#[derive(Debug, Clone)]
pub struct RegressionDetector {
    threshold_percent: f64,
}

impl RegressionDetector {
    /// Creates a new RegressionDetector with a default threshold.
    pub fn new() -> Self {
        Self {
            threshold_percent: 5.0, // 5% degradation threshold
        }
    }

    /// Sets a custom threshold for the detector.
    #[must_use]
    pub fn with_threshold(mut self, threshold_percent: f64) -> Self {
        self.threshold_percent = threshold_percent;
        self
    }

    /// Compares current metrics against a baseline to detect regressions.
    #[allow(clippy::cast_precision_loss)]
    pub fn check_regression(
        &self,
        current: &ThroughputMetrics,
        baseline: &ThroughputMetrics,
    ) -> Vec<String> {
        let mut regressions = Vec::new();
        let threshold_multiplier = 1.0 - (self.threshold_percent / 100.0);

        if (current.record_rate as f64) < (baseline.record_rate as f64) * threshold_multiplier {
            regressions.push(format!(
                "Record rate regression: current {} recs/s < baseline {} recs/s",
                current.record_rate, baseline.record_rate
            ));
        }

        if (current.display_throughput as f64)
            < (baseline.display_throughput as f64) * threshold_multiplier
        {
            regressions.push(format!(
                "Display throughput regression: current {} bytes/s < baseline {} bytes/s",
                current.display_throughput, baseline.display_throughput
            ));
        }

        if (current.comp3_throughput as f64)
            < (baseline.comp3_throughput as f64) * threshold_multiplier
        {
            regressions.push(format!(
                "COMP-3 throughput regression: current {} bytes/s < baseline {} bytes/s",
                current.comp3_throughput, baseline.comp3_throughput
            ));
        }

        // For memory, a higher value is a regression
        let memory_threshold_multiplier = 1.0 + (self.threshold_percent / 100.0);
        if (current.peak_memory_mb as f64)
            > (baseline.peak_memory_mb as f64) * memory_threshold_multiplier
        {
            regressions.push(format!(
                "Peak memory regression: current {} MB > baseline {} MB",
                current.peak_memory_mb, baseline.peak_memory_mb
            ));
        }

        regressions
    }
}

impl Default for RegressionDetector {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_performance_auditor_creation() {
        let auditor = PerformanceAuditor::new("baseline.json", 10.0);
        assert_eq!(auditor.regression_detector.threshold_percent, 10.0);
    }

    #[test]
    fn test_regression_detector_default() {
        let detector = RegressionDetector::new();
        assert_eq!(detector.threshold_percent, 5.0);
    }

    #[test]
    fn test_regression_detector_custom_threshold() {
        let detector = RegressionDetector::new().with_threshold(15.0);
        assert_eq!(detector.threshold_percent, 15.0);
    }

    #[test]
    fn test_regression_detector_no_regression() {
        let detector = RegressionDetector::new().with_threshold(10.0);

        let current = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let baseline = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let regressions = detector.check_regression(&current, &baseline);
        assert!(regressions.is_empty());
    }

    #[test]
    fn test_regression_detector_record_rate_regression() {
        let detector = RegressionDetector::new().with_threshold(10.0);

        let current = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 80, // 20% below baseline
            peak_memory_mb: 100,
        };

        let baseline = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let regressions = detector.check_regression(&current, &baseline);
        assert_eq!(regressions.len(), 1);
        assert!(regressions[0].contains("Record rate regression"));
    }

    #[test]
    fn test_regression_detector_display_throughput_regression() {
        let detector = RegressionDetector::new().with_threshold(10.0);

        let current = ThroughputMetrics {
            display_throughput: 800, // 20% below baseline
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let baseline = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let regressions = detector.check_regression(&current, &baseline);
        assert_eq!(regressions.len(), 1);
        assert!(regressions[0].contains("Display throughput regression"));
    }

    #[test]
    fn test_regression_detector_comp3_throughput_regression() {
        let detector = RegressionDetector::new().with_threshold(10.0);

        let current = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 400, // 20% below baseline
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let baseline = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let regressions = detector.check_regression(&current, &baseline);
        assert_eq!(regressions.len(), 1);
        assert!(regressions[0].contains("COMP-3 throughput regression"));
    }

    #[test]
    fn test_regression_detector_memory_regression() {
        let detector = RegressionDetector::new().with_threshold(10.0);

        let current = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 120, // 20% above baseline
        };

        let baseline = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let regressions = detector.check_regression(&current, &baseline);
        assert_eq!(regressions.len(), 1);
        assert!(regressions[0].contains("Peak memory regression"));
    }

    #[test]
    fn test_regression_detector_multiple_regressions() {
        let detector = RegressionDetector::new().with_threshold(10.0);

        let current = ThroughputMetrics {
            display_throughput: 800, // 20% below
            comp3_throughput: 400,   // 20% below
            record_rate: 80,         // 20% below
            peak_memory_mb: 120,     // 20% above
        };

        let baseline = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        let regressions = detector.check_regression(&current, &baseline);
        assert_eq!(regressions.len(), 4);
    }

    #[test]
    fn test_regression_detector_default_impl() {
        let detector = RegressionDetector::default();
        assert_eq!(detector.threshold_percent, 5.0);
    }

    #[test]
    fn test_baseline_manager_creation() {
        let manager = BaselineManager::new("test_baseline.json");
        assert_eq!(manager.baseline_path, PathBuf::from("test_baseline.json"));
    }

    #[test]
    fn test_performance_baseline_serialization() {
        let baseline = PerformanceBaseline {
            baseline_id: "test-baseline".to_string(),
            throughput: ThroughputMetrics {
                display_throughput: 1000,
                comp3_throughput: 500,
                record_rate: 100,
                peak_memory_mb: 100,
            },
            resources: ResourceMetrics {
                cpu_usage_percent: 50.0,
                memory_usage_mb: 100,
                io_operations: 1000,
                network_bytes: 5000,
            },
            created_at: "2024-01-01T00:00:00Z".to_string(),
        };

        let json = serde_json::to_string(&baseline).expect("Failed to serialize");
        assert!(json.contains("test-baseline"));
        assert!(json.contains("display_throughput"));
    }

    #[test]
    fn test_throughput_metrics_creation() {
        let metrics = ThroughputMetrics {
            display_throughput: 1000,
            comp3_throughput: 500,
            record_rate: 100,
            peak_memory_mb: 100,
        };

        assert_eq!(metrics.display_throughput, 1000);
        assert_eq!(metrics.comp3_throughput, 500);
        assert_eq!(metrics.record_rate, 100);
        assert_eq!(metrics.peak_memory_mb, 100);
    }

    #[test]
    fn test_resource_metrics_creation() {
        let metrics = ResourceMetrics {
            cpu_usage_percent: 50.0,
            memory_usage_mb: 100,
            io_operations: 1000,
            network_bytes: 5000,
        };

        assert_eq!(metrics.cpu_usage_percent, 50.0);
        assert_eq!(metrics.memory_usage_mb, 100);
        assert_eq!(metrics.io_operations, 1000);
        assert_eq!(metrics.network_bytes, 5000);
    }
}