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
//! # Migration Management
//!
//! Comprehensive migration assistance system for API upgrades
//! and version transitions in production environments.

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

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

/// Migration plan for upgrading between versions
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct MigrationPlan {
    /// Source version
    pub from_version: Version,
    /// Target version
    pub toversion: Version,
    /// Ordered migration steps
    pub steps: Vec<MigrationStep>,
    /// Estimated total effort in hours
    pub estimated_effort: u32,
    /// Risk level of the migration
    pub risk_level: RiskLevel,
    /// Required rollback plan
    pub rollback_plan: Option<RollbackPlan>,
    /// Prerequisites before migration
    pub prerequisites: Vec<String>,
    /// Post-migration validation steps
    pub validation_steps: Vec<String>,
}

/// Individual migration step
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct MigrationStep {
    /// Step identifier
    pub id: String,
    /// Step name
    pub name: String,
    /// Step description
    pub description: String,
    /// Step type
    pub step_type: StepType,
    /// Estimated effort in hours
    pub estimated_effort: u32,
    /// Step priority
    pub priority: StepPriority,
    /// Dependencies on other steps
    pub dependencies: Vec<String>,
    /// Automation script (if available)
    pub automation_script: Option<String>,
    /// Manual instructions
    pub manual_instructions: Option<String>,
    /// Validation criteria
    pub validation_criteria: Vec<String>,
    /// Rollback instructions
    pub rollback_instructions: Option<String>,
}

/// Types of migration steps
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepType {
    /// Code changes required
    CodeChange,
    /// Configuration update
    ConfigurationUpdate,
    /// Database migration
    DatabaseMigration,
    /// Dependency update
    DependencyUpdate,
    /// Feature removal
    FeatureRemoval,
    /// API endpoint change
    ApiChange,
    /// Data format change
    DataFormatChange,
    /// Testing and validation
    Testing,
    /// Documentation update
    Documentation,
}

/// Step priority levels
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum StepPriority {
    /// Optional step
    Optional,
    /// Low priority
    Low,
    /// Medium priority
    Medium,
    /// High priority
    High,
    /// Critical - must be completed
    Critical,
}

/// Risk levels for migrations
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    /// Low risk migration
    Low,
    /// Medium risk migration
    Medium,
    /// High risk migration
    High,
    /// Critical risk migration
    Critical,
}

/// Rollback plan for migration failures
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct RollbackPlan {
    /// Rollback steps in order
    pub steps: Vec<RollbackStep>,
    /// Estimated rollback time
    pub estimated_time: u32,
    /// Data backup requirements
    pub backup_requirements: Vec<String>,
    /// Recovery validation steps
    pub recovery_validation: Vec<String>,
}

/// Individual rollback step
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct RollbackStep {
    /// Step identifier
    pub id: String,
    /// Step description
    pub description: String,
    /// Rollback commands or instructions
    pub instructions: String,
    /// Validation after rollback
    pub validation: Option<String>,
}

/// Migration execution status
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct MigrationExecution {
    /// Migration plan being executed
    pub plan: MigrationPlan,
    /// Current step being executed
    pub current_step: Option<String>,
    /// Completed steps
    pub completed_steps: Vec<String>,
    /// Failed steps
    pub failed_steps: Vec<String>,
    /// Execution status
    pub status: ExecutionStatus,
    /// Start time
    pub start_time: chrono::DateTime<chrono::Utc>,
    /// End time (if completed)
    pub end_time: Option<chrono::DateTime<chrono::Utc>>,
    /// Execution log
    pub executionlog: Vec<LogEntry>,
}

/// Execution status
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutionStatus {
    /// Migration not started
    NotStarted,
    /// Migration in progress
    InProgress,
    /// Migration completed successfully
    Completed,
    /// Migration failed
    Failed,
    /// Migration paused
    Paused,
    /// Migration rolled back
    RolledBack,
}

/// Log entry for migration execution
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct LogEntry {
    /// Timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Log level
    pub level: LogLevel,
    /// Step ID (if applicable)
    pub step_id: Option<String>,
    /// Log message
    pub message: String,
    /// Additional data
    pub data: Option<String>,
}

/// Log levels
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    /// Debug information
    Debug,
    /// Informational message
    Info,
    /// Warning message
    Warning,
    /// Error message
    Error,
}

/// Migration manager implementation
pub struct MigrationManager {
    /// Migration templates by version transitions
    migration_templates: HashMap<(Version, Version), MigrationTemplate>,
    /// Active migrations
    active_migrations: HashMap<String, MigrationExecution>,
    /// Migration history
    migration_history: Vec<MigrationExecution>,
}

impl MigrationManager {
    /// Create a new migration manager
    pub fn new() -> Self {
        Self {
            migration_templates: HashMap::new(),
            active_migrations: HashMap::new(),
            migration_history: Vec::new(),
        }
    }

    /// Register a version for migration planning
    pub fn register_version(&mut self, _apiversion: &super::ApiVersion) -> Result<(), CoreError> {
        // This would register _version-specific migration information
        Ok(())
    }

    /// Create a migration plan between versions
    pub fn create_migration_plan(
        &self,
        from_version: &Version,
        toversion: &Version,
    ) -> Result<MigrationPlan, CoreError> {
        // Check if direct migration template exists
        if let Some(template) = self
            .migration_templates
            .get(&(from_version.clone(), toversion.clone()))
        {
            return Ok(template.create_plan(from_version.clone(), toversion.clone()));
        }

        // Try to find a path through intermediate versions
        if let Some(path) = self.find_migration_path(from_version, toversion)? {
            self.create_multi_step_plan(&path)
        } else {
            self.create_default_migration_plan(from_version, toversion)
        }
    }

    /// Check if a migration path exists
    pub fn has_migration_path(&self, from_version: &Version, toversion: &Version) -> bool {
        // Check direct path
        if self
            .migration_templates
            .contains_key(&(from_version.clone(), toversion.clone()))
        {
            return true;
        }

        // Check if we can find an indirect path
        self.find_migration_path(from_version, toversion)
            .unwrap_or(None)
            .is_some()
    }

    /// Find migration path through intermediate versions
    fn find_migration_path(
        &self,
        from_version: &Version,
        toversion: &Version,
    ) -> Result<Option<Vec<Version>>, CoreError> {
        // BFS to find shortest path
        let mut queue = VecDeque::new();
        let mut visited = std::collections::HashSet::new();
        let mut parent: HashMap<Version, Version> = HashMap::new();

        queue.push_back(from_version.clone());
        visited.insert(from_version.clone());

        while let Some(current) = queue.pop_front() {
            if current == *toversion {
                // Reconstruct path
                let mut path = Vec::new();
                let mut node = current;

                while let Some(p) = parent.get(&node) {
                    path.push(node);
                    node = p.clone();
                }
                path.push(from_version.clone());
                path.reverse();

                return Ok(Some(path));
            }

            // Find all versions reachable from current
            for (from, to) in self.migration_templates.keys() {
                if *from == current && !visited.contains(to) {
                    visited.insert(to.clone());
                    parent.insert(to.clone(), current.clone());
                    queue.push_back(to.clone());
                }
            }
        }

        Ok(None)
    }

    /// Create multi-step migration plan
    fn create_multi_step_plan(&self, path: &[Version]) -> Result<MigrationPlan, CoreError> {
        let mut all_steps = Vec::new();
        let mut total_effort = 0;
        let mut max_risk = RiskLevel::Low;

        for window in path.windows(2) {
            if let Some(template) = self
                .migration_templates
                .get(&(window[0].clone(), window[1].clone()))
            {
                let plan = template.create_plan(window[0].clone(), window[1].clone());
                all_steps.extend(plan.steps);
                total_effort += plan.estimated_effort;
                max_risk = max_risk.max(plan.risk_level);
            }
        }

        Ok(MigrationPlan {
            from_version: path.first().expect("Operation failed").clone(),
            toversion: path.last().expect("Operation failed").clone(),
            steps: all_steps,
            estimated_effort: total_effort,
            risk_level: max_risk,
            rollback_plan: None, // Would be constructed from individual rollback plans
            prerequisites: Vec::new(),
            validation_steps: Vec::new(),
        })
    }

    /// Create default migration plan when no template exists
    fn create_default_migration_plan(
        &self,
        from_version: &Version,
        toversion: &Version,
    ) -> Result<MigrationPlan, CoreError> {
        let mut steps = Vec::new();
        let risk_level = if toversion.major() > from_version.major() {
            RiskLevel::High
        } else if toversion.minor() > from_version.minor() {
            RiskLevel::Medium
        } else {
            RiskLevel::Low
        };

        // Add default steps based on version difference
        if toversion.major() > from_version.major() {
            steps.push(MigrationStep {
                id: "major_version_review".to_string(),
                name: "Major Version Review".to_string(),
                description: "Review all breaking changes in major version upgrade".to_string(),
                step_type: StepType::CodeChange,
                estimated_effort: 40,
                priority: StepPriority::Critical,
                dependencies: Vec::new(),
                automation_script: None,
                manual_instructions: Some(
                    "Review changelog and identify all breaking changes".to_string(),
                ),
                validation_criteria: vec![
                    "All breaking changes identified".to_string(),
                    "Migration strategy defined".to_string(),
                ],
                rollback_instructions: Some("Revert to previous _version".to_string()),
            });
        }

        if toversion.minor() > from_version.minor() {
            steps.push(MigrationStep {
                id: "minor_version_update".to_string(),
                name: "Minor Version Update".to_string(),
                description: "Update to new minor version with backward compatibility".to_string(),
                step_type: StepType::DependencyUpdate,
                estimated_effort: 8,
                priority: StepPriority::Medium,
                dependencies: Vec::new(),
                automation_script: Some("update_dependencies.sh".to_string()),
                manual_instructions: None,
                validation_criteria: vec!["All tests pass".to_string()],
                rollback_instructions: Some("Revert dependency versions".to_string()),
            });
        }

        // Always add testing step
        steps.push(MigrationStep {
            id: "comprehensive_testing".to_string(),
            name: "Comprehensive Testing".to_string(),
            description: "Run full test suite and integration tests".to_string(),
            step_type: StepType::Testing,
            estimated_effort: 16,
            priority: StepPriority::Critical,
            dependencies: steps.iter().map(|s| s.id.clone()).collect(),
            automation_script: Some("run_tests.sh".to_string()),
            manual_instructions: Some("Verify all functionality works as expected".to_string()),
            validation_criteria: vec![
                "All unit tests pass".to_string(),
                "All integration tests pass".to_string(),
                "Performance benchmarks met".to_string(),
            ],
            rollback_instructions: None,
        });

        let estimated_effort = steps.iter().map(|s| s.estimated_effort).sum();

        Ok(MigrationPlan {
            from_version: from_version.clone(),
            toversion: toversion.clone(),
            steps,
            estimated_effort,
            risk_level,
            rollback_plan: Some(self.create_default_rollback_plan()),
            prerequisites: vec![
                "Create backup of current system".to_string(),
                "Ensure rollback plan is tested".to_string(),
            ],
            validation_steps: vec![
                "Verify system functionality".to_string(),
                "Check performance metrics".to_string(),
                "Validate data integrity".to_string(),
            ],
        })
    }

    /// Create default rollback plan
    fn create_default_rollback_plan(&self) -> RollbackPlan {
        RollbackPlan {
            steps: vec![RollbackStep {
                id: "restore_backup".to_string(),
                description: "Restore from backup".to_string(),
                instructions: "Restore system from pre-migration backup".to_string(),
                validation: Some("Verify system is functioning".to_string()),
            }],
            estimated_time: 30, // 30 minutes
            backup_requirements: vec![
                "Full system backup".to_string(),
                "Database backup".to_string(),
                "Configuration backup".to_string(),
            ],
            recovery_validation: vec![
                "System startup successful".to_string(),
                "All services running".to_string(),
                "Data integrity verified".to_string(),
            ],
        }
    }

    /// Start migration execution
    pub fn start_migration(
        &mut self,
        plan: MigrationPlan,
        executionid: String,
    ) -> Result<(), CoreError> {
        let execution = MigrationExecution {
            plan,
            current_step: None,
            completed_steps: Vec::new(),
            failed_steps: Vec::new(),
            status: ExecutionStatus::NotStarted,
            start_time: chrono::Utc::now(),
            end_time: None,
            executionlog: Vec::new(),
        };

        self.active_migrations.insert(executionid, execution);
        Ok(())
    }

    /// Get migration execution status
    pub fn id_2(&self, executionid: &str) -> Option<&MigrationExecution> {
        self.active_migrations.get(executionid)
    }

    /// Clean up old migration plans
    pub fn cleanup_old_plans(&mut self) -> Result<usize, CoreError> {
        let cutoff = chrono::Utc::now() - chrono::Duration::days(30);
        let initial_count = self.migration_history.len();

        self.migration_history
            .retain(|execution| execution.start_time > cutoff);

        Ok(initial_count - self.migration_history.len())
    }
}

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

/// Migration template for version transitions
struct MigrationTemplate {
    /// Template steps
    steps: Vec<MigrationStepTemplate>,
    /// Base effort estimate
    base_effort: u32,
    /// Risk level
    risk_level: RiskLevel,
}

impl MigrationTemplate {
    fn create_plan(&self, from_version: Version, toversion: Version) -> MigrationPlan {
        let steps = self
            .steps
            .iter()
            .map(|template| template.create_step())
            .collect();

        MigrationPlan {
            from_version,
            toversion,
            steps,
            estimated_effort: self.base_effort,
            risk_level: self.risk_level,
            rollback_plan: None,
            prerequisites: Vec::new(),
            validation_steps: Vec::new(),
        }
    }
}

/// Template for migration steps
struct MigrationStepTemplate {
    id: String,
    name: String,
    description: String,
    step_type: StepType,
    estimated_effort: u32,
    priority: StepPriority,
}

impl MigrationStepTemplate {
    fn create_step(&self) -> MigrationStep {
        MigrationStep {
            id: self.id.clone(),
            name: self.name.clone(),
            description: self.description.clone(),
            step_type: self.step_type,
            estimated_effort: self.estimated_effort,
            priority: self.priority,
            dependencies: Vec::new(),
            automation_script: None,
            manual_instructions: None,
            validation_criteria: Vec::new(),
            rollback_instructions: None,
        }
    }
}

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

    #[test]
    fn test_migration_manager_creation() {
        let manager = MigrationManager::new();
        assert!(manager.migration_templates.is_empty());
        assert!(manager.active_migrations.is_empty());
    }

    #[test]
    fn test_default_migration_plan() {
        let manager = MigrationManager::new();
        let from_version = Version::new(1, 0, 0);
        let toversion = Version::new(2, 0, 0);

        let plan = manager
            .create_migration_plan(&from_version, &toversion)
            .expect("Operation failed");
        assert_eq!(plan.from_version, from_version);
        assert_eq!(plan.toversion, toversion);
        assert!(!plan.steps.is_empty());
        assert_eq!(plan.risk_level, RiskLevel::High); // Major version change
    }

    #[test]
    fn test_minor_version_migration() {
        let manager = MigrationManager::new();
        let from_version = Version::new(1, 0, 0);
        let toversion = Version::new(1, 1, 0);

        let plan = manager
            .create_migration_plan(&from_version, &toversion)
            .expect("Operation failed");
        assert_eq!(plan.risk_level, RiskLevel::Medium); // Minor version change
    }

    #[test]
    fn test_patch_version_migration() {
        let manager = MigrationManager::new();
        let from_version = Version::new(1, 0, 0);
        let toversion = Version::new(1, 0, 1);

        let plan = manager
            .create_migration_plan(&from_version, &toversion)
            .expect("Operation failed");
        assert_eq!(plan.risk_level, RiskLevel::Low); // Patch version change
    }

    #[test]
    fn test_migration_execution() {
        let mut manager = MigrationManager::new();
        let plan = MigrationPlan {
            from_version: Version::new(1, 0, 0),
            toversion: Version::new(1, 1, 0),
            steps: Vec::new(),
            estimated_effort: 8,
            risk_level: RiskLevel::Medium,
            rollback_plan: None,
            prerequisites: Vec::new(),
            validation_steps: Vec::new(),
        };

        let executionid = "test_migration_123".to_string();
        manager
            .start_migration(plan, executionid.clone())
            .expect("Operation failed");

        // let status = manager.get_migration_status(&executionid);
        // assert!(status.is_some());
        // assert_eq!(status.expect("Operation failed").status, ExecutionStatus::NotStarted);
    }

    #[test]
    fn test_step_priority_ordering() {
        assert!(StepPriority::Critical > StepPriority::High);
        assert!(StepPriority::High > StepPriority::Medium);
        assert!(StepPriority::Medium > StepPriority::Low);
        assert!(StepPriority::Low > StepPriority::Optional);
    }

    #[test]
    fn test_risk_level_ordering() {
        assert!(RiskLevel::Critical > RiskLevel::High);
        assert!(RiskLevel::High > RiskLevel::Medium);
        assert!(RiskLevel::Medium > RiskLevel::Low);
    }
}