scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
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
665
666
//! # Backward Compatibility Checking
//!
//! Comprehensive backward compatibility checking and enforcement system
//! for API evolution management in production environments.

use super::{ApiVersion, Version};
use crate::error::CoreError;
use std::collections::HashMap;

#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};

/// Compatibility levels between API versions
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CompatibilityLevel {
    /// Fully backward compatible
    BackwardCompatible,
    /// Compatible with minor changes
    MostlyCompatible,
    /// Some breaking changes but migration possible
    PartiallyCompatible,
    /// Major breaking changes requiring significant migration
    BreakingChanges,
    /// Incompatible - no migration path
    Incompatible,
}

impl CompatibilityLevel {
    /// Get the string representation
    pub const fn as_str(&self) -> &'static str {
        match self {
            CompatibilityLevel::BackwardCompatible => "backward_compatible",
            CompatibilityLevel::MostlyCompatible => "mostly_compatible",
            CompatibilityLevel::PartiallyCompatible => "partially_compatible",
            CompatibilityLevel::BreakingChanges => "breakingchanges",
            CompatibilityLevel::Incompatible => "incompatible",
        }
    }

    /// Check if migration is recommended
    pub fn requires_migration(&self) -> bool {
        matches!(
            self,
            CompatibilityLevel::PartiallyCompatible
                | CompatibilityLevel::BreakingChanges
                | CompatibilityLevel::Incompatible
        )
    }

    /// Check if automatic migration is possible
    pub fn supports_auto_migration(&self) -> bool {
        matches!(
            self,
            CompatibilityLevel::BackwardCompatible
                | CompatibilityLevel::MostlyCompatible
                | CompatibilityLevel::PartiallyCompatible
        )
    }
}

/// Detailed compatibility report
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct CompatibilityReport {
    /// Source version
    pub from_version: Version,
    /// Target version
    pub toversion: Version,
    /// Overall compatibility level
    pub compatibility_level: CompatibilityLevel,
    /// Detailed compatibility issues
    pub issues: Vec<CompatibilityIssue>,
    /// Breaking changes detected
    pub breakingchanges: Vec<BreakingChange>,
    /// Deprecated features that will be removed
    pub deprecated_features: Vec<String>,
    /// New features added
    pub new_features: Vec<String>,
    /// Migration recommendations
    pub migration_recommendations: Vec<String>,
    /// Estimated migration effort (in developer hours)
    pub estimated_migration_effort: Option<u32>,
}

/// Specific compatibility issue
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct CompatibilityIssue {
    /// Issue severity
    pub severity: IssueSeverity,
    /// Component affected
    pub component: String,
    /// Issue description
    pub description: String,
    /// Suggested resolution
    pub resolution: Option<String>,
    /// Impact assessment
    pub impact: ImpactLevel,
}

/// Issue severity levels
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum IssueSeverity {
    /// Informational - no action required
    Info,
    /// Warning - action recommended
    Warning,
    /// Error - action required
    Error,
    /// Critical - blocking issue
    Critical,
}

/// Impact level of compatibility issues
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ImpactLevel {
    /// No user impact
    None,
    /// Minor impact - easily resolved
    Low,
    /// Moderate impact - requires changes
    Medium,
    /// High impact - significant changes required
    High,
    /// Critical impact - may block migration
    Critical,
}

/// Breaking change information
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct BreakingChange {
    /// Change type
    pub change_type: ChangeType,
    /// Component affected
    pub component: String,
    /// Description of the change
    pub description: String,
    /// Migration path
    pub migration_path: Option<String>,
    /// Version where change was introduced
    pub introduced_in: Version,
}

/// Types of breaking changes
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeType {
    /// API signature changed
    ApiSignatureChange,
    /// Behavior change
    BehaviorChange,
    /// Removed feature
    FeatureRemoval,
    /// Configuration change
    ConfigurationChange,
    /// Dependency change
    DependencyChange,
    /// Data format change
    DataFormatChange,
}

/// Compatibility checker implementation
pub struct CompatibilityChecker {
    /// Registered versions and their metadata
    versions: HashMap<Version, ApiVersion>,
    /// Compatibility rules
    rules: Vec<CompatibilityRule>,
}

impl CompatibilityChecker {
    /// Create a new compatibility checker
    pub fn new() -> Self {
        Self {
            versions: HashMap::new(),
            rules: Self::default_rules(),
        }
    }

    /// Register a version for compatibility checking
    pub fn register_version(&mut self, apiversion: &ApiVersion) -> Result<(), CoreError> {
        self.versions
            .insert(apiversion.version.clone(), apiversion.clone());
        Ok(())
    }

    /// Check compatibility between two versions
    pub fn check_compatibility(
        &self,
        from_version: &Version,
        toversion: &Version,
    ) -> Result<CompatibilityLevel, CoreError> {
        let report = self.get_compatibility_report(from_version, toversion)?;
        Ok(report.compatibility_level)
    }

    /// Get detailed compatibility report
    pub fn get_compatibility_report(
        &self,
        from_version: &Version,
        toversion: &Version,
    ) -> Result<CompatibilityReport, CoreError> {
        let from_api = self.versions.get(from_version).ok_or_else(|| {
            CoreError::ComputationError(crate::error::ErrorContext::new(format!(
                "Version {from_version} not registered"
            )))
        })?;
        let to_api = self.versions.get(toversion).ok_or_else(|| {
            CoreError::ComputationError(crate::error::ErrorContext::new(format!(
                "Version {toversion} not registered"
            )))
        })?;

        let mut report = CompatibilityReport {
            from_version: from_version.clone(),
            toversion: toversion.clone(),
            compatibility_level: CompatibilityLevel::BackwardCompatible,
            issues: Vec::new(),
            breakingchanges: Vec::new(),
            deprecated_features: to_api.deprecated_features.clone(),
            new_features: to_api.new_features.clone(),
            migration_recommendations: Vec::new(),
            estimated_migration_effort: None,
        };

        // Apply compatibility rules
        for rule in &self.rules {
            rule.apply(from_api, to_api, &mut report)?;
        }

        // Determine overall compatibility level
        report.compatibility_level = self.determine_compatibility_level(&report);

        // Generate migration recommendations
        self.generate_migration_recommendations(&mut report);

        // Estimate migration effort
        report.estimated_migration_effort = self.estimate_migration_effort(&report);

        Ok(report)
    }

    /// Add a custom compatibility rule
    pub fn add_rule(&mut self, rule: CompatibilityRule) {
        self.rules.push(rule);
    }

    /// Create default compatibility rules
    fn default_rules() -> Vec<CompatibilityRule> {
        vec![
            CompatibilityRule::SemVerRule,
            CompatibilityRule::BreakingChangeRule,
            CompatibilityRule::FeatureRemovalRule,
            CompatibilityRule::ApiSignatureRule,
            CompatibilityRule::BehaviorChangeRule,
        ]
    }

    /// Determine overall compatibility level based on issues
    fn determine_compatibility_level(&self, report: &CompatibilityReport) -> CompatibilityLevel {
        let has_critical = report
            .issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Critical);
        let haserrors = report
            .issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Error);
        let has_warnings = report
            .issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Warning);
        let has_breakingchanges = !report.breakingchanges.is_empty();

        if has_critical {
            CompatibilityLevel::Incompatible
        } else if has_breakingchanges || haserrors {
            if report.from_version.major() != report.toversion.major() {
                CompatibilityLevel::BreakingChanges
            } else {
                CompatibilityLevel::PartiallyCompatible
            }
        } else if has_warnings {
            CompatibilityLevel::MostlyCompatible
        } else {
            CompatibilityLevel::BackwardCompatible
        }
    }

    /// Generate migration recommendations
    fn generate_migration_recommendations(&self, report: &mut CompatibilityReport) {
        for issue in &report.issues {
            if let Some(ref resolution) = issue.resolution {
                report
                    .migration_recommendations
                    .push(format!("{}: {}", issue.component, resolution));
            }
        }

        for breaking_change in &report.breakingchanges {
            if let Some(ref migration_path) = breaking_change.migration_path {
                report
                    .migration_recommendations
                    .push(format!("{}, {}", breaking_change.component, migration_path));
            }
        }

        // Add version-specific recommendations
        if report.from_version.major() != report.toversion.major() {
            report
                .migration_recommendations
                .push("Major version upgrade - review all API usage".to_string());
        }

        if !report.deprecated_features.is_empty() {
            report
                .migration_recommendations
                .push("Update code to avoid deprecated features".to_string());
        }
    }

    /// Estimate migration effort in developer hours
    fn estimate_migration_effort(&self, report: &CompatibilityReport) -> Option<u32> {
        let mut effort_hours = 0u32;

        // Base effort for version differences
        let major_diff = report
            .toversion
            .major()
            .saturating_sub(report.from_version.major());
        let minor_diff = if major_diff == 0 {
            report
                .toversion
                .minor()
                .saturating_sub(report.from_version.minor())
        } else {
            0
        };

        effort_hours += (major_diff * 40) as u32; // 40 hours per major version
        effort_hours += (minor_diff * 8) as u32; // 8 hours per minor version

        // Add effort for specific issues
        for issue in &report.issues {
            effort_hours += match issue.impact {
                ImpactLevel::None => 0,
                ImpactLevel::Low => 2,
                ImpactLevel::Medium => 8,
                ImpactLevel::High => 24,
                ImpactLevel::Critical => 80,
            };
        }

        // Add effort for breaking changes
        for breaking_change in &report.breakingchanges {
            effort_hours += match breaking_change.change_type {
                ChangeType::ApiSignatureChange => 16,
                ChangeType::BehaviorChange => 24,
                ChangeType::FeatureRemoval => 32,
                ChangeType::ConfigurationChange => 8,
                ChangeType::DependencyChange => 16,
                ChangeType::DataFormatChange => 40,
            };
        }

        if effort_hours > 0 {
            Some(effort_hours)
        } else {
            None
        }
    }
}

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

/// Compatibility rule trait
pub trait CompatibilityRuleTrait {
    /// Apply the rule to generate compatibility issues
    fn apply(
        &self,
        from_api: &ApiVersion,
        to_api: &ApiVersion,
        report: &mut CompatibilityReport,
    ) -> Result<(), CoreError>;
}

/// Built-in compatibility rules
#[derive(Debug, Clone)]
pub enum CompatibilityRule {
    /// Semantic versioning rule
    SemVerRule,
    /// Breaking change detection rule
    BreakingChangeRule,
    /// Feature removal rule
    FeatureRemovalRule,
    /// API signature change rule
    ApiSignatureRule,
    /// Behavior change rule
    BehaviorChangeRule,
}

impl CompatibilityRuleTrait for CompatibilityRule {
    fn apply(
        &self,
        from_api: &ApiVersion,
        to_api: &ApiVersion,
        report: &mut CompatibilityReport,
    ) -> Result<(), CoreError> {
        match self {
            CompatibilityRule::SemVerRule => self.apply_semver_rule(from_api, to_api, report),
            CompatibilityRule::BreakingChangeRule => {
                self.apply_breaking_change_rule(from_api, to_api, report)
            }
            CompatibilityRule::FeatureRemovalRule => {
                self.apply_feature_removal_rule(from_api, to_api, report)
            }
            CompatibilityRule::ApiSignatureRule => {
                self.apply_api_signature_rule(from_api, to_api, report)
            }
            CompatibilityRule::BehaviorChangeRule => {
                self.apply_behavior_change_rule(from_api, to_api, report)
            }
        }
    }
}

impl CompatibilityRule {
    /// Apply semantic versioning rule
    fn apply_semver_rule(
        &self,
        from_api: &ApiVersion,
        to_api: &ApiVersion,
        report: &mut CompatibilityReport,
    ) -> Result<(), CoreError> {
        let from_version = &from_api.version;
        let toversion = &to_api.version;

        if toversion.major() > from_version.major() {
            report.issues.push(CompatibilityIssue {
                severity: IssueSeverity::Warning,
                component: "version".to_string(),
                description: "Major version upgrade detected".to_string(),
                resolution: Some("Review all API usage for breaking changes".to_string()),
                impact: ImpactLevel::High,
            });
        }

        if toversion < from_version {
            report.issues.push(CompatibilityIssue {
                severity: IssueSeverity::Error,
                component: "version".to_string(),
                description: "Downgrade detected".to_string(),
                resolution: Some("Downgrades are not supported".to_string()),
                impact: ImpactLevel::Critical,
            });
        }

        Ok(())
    }

    /// Apply breaking change rule
    fn apply_breaking_change_rule(
        &self,
        _from_api: &ApiVersion,
        to_api: &ApiVersion,
        report: &mut CompatibilityReport,
    ) -> Result<(), CoreError> {
        for breaking_change in &to_api.breakingchanges {
            report.breakingchanges.push(BreakingChange {
                change_type: ChangeType::BehaviorChange, // Default type
                component: "api".to_string(),
                description: breaking_change.clone(),
                migration_path: None,
                introduced_in: to_api.version.clone(),
            });

            report.issues.push(CompatibilityIssue {
                severity: IssueSeverity::Error,
                component: "api".to_string(),
                description: breaking_change.to_string(),
                resolution: Some("Update code to handle the breaking change".to_string()),
                impact: ImpactLevel::High,
            });
        }

        Ok(())
    }

    /// Apply feature removal rule
    fn apply_feature_removal_rule(
        &self,
        from_api: &ApiVersion,
        to_api: &ApiVersion,
        report: &mut CompatibilityReport,
    ) -> Result<(), CoreError> {
        // Check for features that existed in from_api but not in to_api
        for feature in &from_api.features {
            if !to_api.features.contains(feature) {
                report.breakingchanges.push(BreakingChange {
                    change_type: ChangeType::FeatureRemoval,
                    component: feature.clone(),
                    description: format!("Feature '{feature}' has been removed"),
                    migration_path: Some("Remove usage of this feature".to_string()),
                    introduced_in: to_api.version.clone(),
                });

                report.issues.push(CompatibilityIssue {
                    severity: IssueSeverity::Error,
                    component: feature.clone(),
                    description: format!("Feature '{feature}' no longer available"),
                    resolution: Some("Remove or replace feature usage".to_string()),
                    impact: ImpactLevel::High,
                });
            }
        }

        Ok(())
    }

    /// Apply API signature rule
    fn apply_api_signature_rule(
        &self,
        _from_api: &ApiVersion,
        _to_api: &ApiVersion,
        _report: &mut CompatibilityReport,
    ) -> Result<(), CoreError> {
        // This would typically analyze actual API signatures
        // For now, it's a placeholder
        Ok(())
    }

    /// Apply behavior change rule
    fn apply_behavior_change_rule(
        &self,
        _from_api: &ApiVersion,
        _to_api: &ApiVersion,
        _report: &mut CompatibilityReport,
    ) -> Result<(), CoreError> {
        // This would typically analyze behavior changes
        // For now, it's a placeholder
        Ok(())
    }
}

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

    #[test]
    fn test_compatibility_levels() {
        assert!(CompatibilityLevel::BackwardCompatible < CompatibilityLevel::BreakingChanges);
        assert!(CompatibilityLevel::BreakingChanges.requires_migration());
        assert!(CompatibilityLevel::BackwardCompatible.supports_auto_migration());
    }

    #[test]
    fn test_compatibility_checker() {
        let mut checker = CompatibilityChecker::new();

        let v1 = ApiVersionBuilder::new(Version::parse("1.0.0").expect("Operation failed"))
            .feature("feature1")
            .build()
            .expect("Test: operation failed");
        let v2 = ApiVersionBuilder::new(Version::parse("1.1.0").expect("Operation failed"))
            .feature("feature1")
            .feature("feature2")
            .new_feature("Added feature2")
            .build()
            .expect("Test: operation failed");

        checker.register_version(&v1).expect("Operation failed");
        checker.register_version(&v2).expect("Operation failed");

        let compatibility = checker
            .check_compatibility(&v1.version, &v2.version)
            .expect("Test: operation failed");
        assert_eq!(compatibility, CompatibilityLevel::BackwardCompatible);
    }

    #[test]
    fn test_breakingchanges() {
        let mut checker = CompatibilityChecker::new();

        let v1 = ApiVersionBuilder::new(Version::parse("1.0.0").expect("Operation failed"))
            .feature("feature1")
            .build()
            .expect("Test: operation failed");
        let v2 = ApiVersionBuilder::new(Version::parse("2.0.0").expect("Operation failed"))
            .breaking_change("Removed feature1")
            .build()
            .expect("Test: operation failed");

        checker.register_version(&v1).expect("Operation failed");
        checker.register_version(&v2).expect("Operation failed");

        let report = checker
            .get_compatibility_report(&v1.version, &v2.version)
            .expect("Test: operation failed");
        assert!(!report.breakingchanges.is_empty());
        assert!(report.compatibility_level.requires_migration());
    }

    #[test]
    fn test_migration_effort_estimation() {
        let mut checker = CompatibilityChecker::new();

        let v1 = ApiVersionBuilder::new(Version::parse("1.0.0").expect("Operation failed"))
            .build()
            .expect("Test: operation failed");
        let v2 = ApiVersionBuilder::new(Version::parse("2.0.0").expect("Operation failed"))
            .breaking_change("Major API overhaul")
            .build()
            .expect("Test: operation failed");

        checker.register_version(&v1).expect("Operation failed");
        checker.register_version(&v2).expect("Operation failed");

        let report = checker
            .get_compatibility_report(&v1.version, &v2.version)
            .expect("Test: operation failed");
        assert!(report.estimated_migration_effort.is_some());
        assert!(
            report
                .estimated_migration_effort
                .expect("Test: operation failed")
                > 0
        );
    }

    #[test]
    fn test_feature_removal_detection() {
        let mut checker = CompatibilityChecker::new();

        let v1 = ApiVersionBuilder::new(Version::parse("1.0.0").expect("Operation failed"))
            .feature("feature1")
            .feature("feature2")
            .build()
            .expect("Test: operation failed");
        let v2 = ApiVersionBuilder::new(Version::parse("1.1.0").expect("Operation failed"))
            .feature("feature1")
            // feature2 removed
            .build().expect("Operation failed");

        checker.register_version(&v1).expect("Operation failed");
        checker.register_version(&v2).expect("Operation failed");

        let report = checker
            .get_compatibility_report(&v1.version, &v2.version)
            .expect("Test: operation failed");
        assert!(!report.breakingchanges.is_empty());

        let feature_removal = report
            .breakingchanges
            .iter()
            .find(|bc| bc.change_type == ChangeType::FeatureRemoval);
        assert!(feature_removal.is_some());
    }
}