voirs-cli 0.1.0-rc.1

Command-line interface for VoiRS speech synthesis
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
//! Workflow Validation
//!
//! Validates workflow definitions for correctness and safety.

use super::definition::Workflow;
use crate::error::CliError;

type Result<T> = std::result::Result<T, CliError>;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Validation error types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationError {
    /// Duplicate step name
    DuplicateStepName(String),
    /// Missing dependency
    MissingDependency { step: String, dependency: String },
    /// Circular dependency
    CircularDependency(Vec<String>),
    /// Invalid condition
    InvalidCondition { step: String, reason: String },
    /// Invalid parameter
    InvalidParameter {
        step: String,
        parameter: String,
        reason: String,
    },
    /// Empty workflow
    EmptyWorkflow,
    /// Invalid for-each variable
    InvalidForEachVariable { step: String, variable: String },
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DuplicateStepName(name) => write!(f, "Duplicate step name: {}", name),
            Self::MissingDependency { step, dependency } => {
                write!(
                    f,
                    "Step '{}' depends on non-existent step '{}'",
                    step, dependency
                )
            }
            Self::CircularDependency(cycle) => {
                write!(f, "Circular dependency detected: {}", cycle.join(" -> "))
            }
            Self::InvalidCondition { step, reason } => {
                write!(f, "Invalid condition in step '{}': {}", step, reason)
            }
            Self::InvalidParameter {
                step,
                parameter,
                reason,
            } => write!(
                f,
                "Invalid parameter '{}' in step '{}': {}",
                parameter, step, reason
            ),
            Self::EmptyWorkflow => write!(f, "Workflow has no steps"),
            Self::InvalidForEachVariable { step, variable } => {
                write!(
                    f,
                    "Invalid for-each variable '{}' in step '{}'",
                    variable, step
                )
            }
        }
    }
}

/// Validation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Whether validation passed
    pub valid: bool,
    /// List of errors
    pub errors: Vec<ValidationError>,
    /// List of warnings
    pub warnings: Vec<String>,
}

impl ValidationResult {
    /// Create successful validation result
    pub fn success() -> Self {
        Self {
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Create failed validation result
    pub fn failure(errors: Vec<ValidationError>) -> Self {
        Self {
            valid: false,
            errors,
            warnings: Vec::new(),
        }
    }

    /// Add a warning
    pub fn with_warning(mut self, warning: String) -> Self {
        self.warnings.push(warning);
        self
    }

    /// Check if has errors
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Check if has warnings
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }
}

/// Workflow validator
pub struct WorkflowValidator {
    /// Maximum allowed steps
    max_steps: usize,
    /// Maximum dependency depth
    max_dependency_depth: usize,
}

impl WorkflowValidator {
    /// Create new validator with defaults
    pub fn new() -> Self {
        Self {
            max_steps: 1000,
            max_dependency_depth: 100,
        }
    }

    /// Create validator with custom limits
    pub fn with_limits(max_steps: usize, max_dependency_depth: usize) -> Self {
        Self {
            max_steps,
            max_dependency_depth,
        }
    }

    /// Validate a workflow
    pub fn validate(&self, workflow: &Workflow) -> Result<ValidationResult> {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        // Check if workflow is empty
        if workflow.steps.is_empty() {
            errors.push(ValidationError::EmptyWorkflow);
            return Ok(ValidationResult::failure(errors));
        }

        // Check step count
        if workflow.steps.len() > self.max_steps {
            warnings.push(format!(
                "Workflow has {} steps, which exceeds recommended limit of {}",
                workflow.steps.len(),
                self.max_steps
            ));
        }

        // Check for duplicate step names
        let mut step_names = HashSet::new();
        for step in &workflow.steps {
            if !step_names.insert(&step.name) {
                errors.push(ValidationError::DuplicateStepName(step.name.clone()));
            }
        }

        // Build step map for dependency checking
        let step_map: HashMap<&String, &super::definition::Step> =
            workflow.steps.iter().map(|s| (&s.name, s)).collect();

        // Check dependencies exist
        for step in &workflow.steps {
            for dep in &step.depends_on {
                if !step_map.contains_key(&dep.step_name) {
                    errors.push(ValidationError::MissingDependency {
                        step: step.name.clone(),
                        dependency: dep.step_name.clone(),
                    });
                }
            }
        }

        // Check for circular dependencies
        if let Some(cycle) = self.detect_cycles(workflow) {
            errors.push(ValidationError::CircularDependency(cycle));
        }

        // Check dependency depth
        for step in &workflow.steps {
            let depth = self.calculate_dependency_depth(&step.name, workflow, &mut HashSet::new());
            if depth > self.max_dependency_depth {
                warnings.push(format!(
                    "Step '{}' has dependency depth of {}, which exceeds recommended limit of {}",
                    step.name, depth, self.max_dependency_depth
                ));
            }
        }

        // Validate conditions
        for step in &workflow.steps {
            if let Some(ref condition) = step.condition {
                // Basic validation of condition syntax
                if condition.left.is_empty() || condition.right.is_empty() {
                    errors.push(ValidationError::InvalidCondition {
                        step: step.name.clone(),
                        reason: "Condition operands cannot be empty".to_string(),
                    });
                }
            }
        }

        // Validate for-each loops
        for step in &workflow.steps {
            if let Some(ref for_each_var) = step.for_each {
                // Check if variable is properly formatted
                if !for_each_var.starts_with("${") || !for_each_var.ends_with('}') {
                    errors.push(ValidationError::InvalidForEachVariable {
                        step: step.name.clone(),
                        variable: for_each_var.clone(),
                    });
                }
            }
        }

        if errors.is_empty() {
            let mut result = ValidationResult::success();
            result.warnings = warnings;
            Ok(result)
        } else {
            let mut result = ValidationResult::failure(errors);
            result.warnings = warnings;
            Ok(result)
        }
    }

    /// Detect circular dependencies
    fn detect_cycles(&self, workflow: &Workflow) -> Option<Vec<String>> {
        let mut visited = HashSet::new();
        let mut recursion_stack = Vec::new();

        for step in &workflow.steps {
            if self.has_cycle_dfs(&step.name, workflow, &mut visited, &mut recursion_stack) {
                return Some(recursion_stack);
            }
        }

        None
    }

    /// DFS-based cycle detection
    fn has_cycle_dfs(
        &self,
        node: &str,
        workflow: &Workflow,
        visited: &mut HashSet<String>,
        recursion_stack: &mut Vec<String>,
    ) -> bool {
        if recursion_stack.iter().any(|s| s == node) {
            recursion_stack.push(node.to_string());
            return true;
        }

        if visited.contains(node) {
            return false;
        }

        visited.insert(node.to_string());
        recursion_stack.push(node.to_string());

        // Find step and check dependencies
        if let Some(step) = workflow.steps.iter().find(|s| s.name == node) {
            for dep in &step.depends_on {
                if self.has_cycle_dfs(&dep.step_name, workflow, visited, recursion_stack) {
                    return true;
                }
            }
        }

        recursion_stack.pop();
        false
    }

    /// Calculate dependency depth
    fn calculate_dependency_depth(
        &self,
        step_name: &str,
        workflow: &Workflow,
        visited: &mut HashSet<String>,
    ) -> usize {
        if visited.contains(step_name) {
            return 0;
        }

        visited.insert(step_name.to_string());

        let step = workflow.steps.iter().find(|s| s.name == step_name);

        if let Some(step) = step {
            if step.depends_on.is_empty() {
                return 1;
            }

            let max_dep_depth = step
                .depends_on
                .iter()
                .map(|dep| self.calculate_dependency_depth(&dep.step_name, workflow, visited))
                .max()
                .unwrap_or(0);

            max_dep_depth + 1
        } else {
            0
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workflow::definition::{Step, StepDependency, StepType};
    use std::collections::HashMap;

    #[test]
    fn test_validator_creation() {
        let validator = WorkflowValidator::new();
        assert_eq!(validator.max_steps, 1000);
    }

    #[test]
    fn test_validate_empty_workflow() {
        let validator = WorkflowValidator::new();
        let workflow = Workflow::new("test", "1.0", "Test");

        let result = validator.validate(&workflow).unwrap();
        assert!(!result.valid);
        assert!(result.has_errors());
    }

    #[test]
    fn test_validate_valid_workflow() {
        let validator = WorkflowValidator::new();
        let mut workflow = Workflow::new("test", "1.0", "Test");

        let step = Step {
            name: "step1".to_string(),
            step_type: StepType::Command,
            description: None,
            parameters: HashMap::new(),
            condition: None,
            depends_on: Vec::new(),
            retry: None,
            for_each: None,
            parallel: false,
        };

        workflow.add_step(step);

        let result = validator.validate(&workflow).unwrap();
        assert!(result.valid);
        assert!(!result.has_errors());
    }

    #[test]
    fn test_validate_duplicate_step_names() {
        let validator = WorkflowValidator::new();
        let mut workflow = Workflow::new("test", "1.0", "Test");

        let step1 = Step {
            name: "duplicate".to_string(),
            step_type: StepType::Command,
            description: None,
            parameters: HashMap::new(),
            condition: None,
            depends_on: Vec::new(),
            retry: None,
            for_each: None,
            parallel: false,
        };

        workflow.add_step(step1.clone());
        workflow.add_step(step1);

        let result = validator.validate(&workflow).unwrap();
        assert!(!result.valid);
        assert!(result.has_errors());
    }

    #[test]
    fn test_validate_missing_dependency() {
        let validator = WorkflowValidator::new();
        let mut workflow = Workflow::new("test", "1.0", "Test");

        let step = Step {
            name: "step1".to_string(),
            step_type: StepType::Command,
            description: None,
            parameters: HashMap::new(),
            condition: None,
            depends_on: vec![StepDependency {
                step_name: "nonexistent".to_string(),
                must_succeed: true,
            }],
            retry: None,
            for_each: None,
            parallel: false,
        };

        workflow.add_step(step);

        let result = validator.validate(&workflow).unwrap();
        assert!(!result.valid);
        assert!(result.has_errors());
    }

    #[test]
    fn test_validation_result_success() {
        let result = ValidationResult::success();
        assert!(result.valid);
        assert!(!result.has_errors());
    }

    #[test]
    fn test_validation_result_with_warning() {
        let result = ValidationResult::success().with_warning("Test warning".to_string());
        assert!(result.valid);
        assert!(result.has_warnings());
        assert_eq!(result.warnings.len(), 1);
    }
}