devops-models 0.1.0

Typed serde models for DevOps configuration formats: Kubernetes, Docker Compose, GitLab CI, GitHub Actions, Prometheus, Alertmanager, Helm, Ansible, and OpenAPI.
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
//! Validation types and traits for configuration file validation.
//!
//! This module provides:
//! - [`Severity`] - Error severity levels (Error, Warning, Info, Hint)
//! - [`Diagnostic`] - Individual validation findings with path info
//! - [`ValidationResult`] - Complete validation outcome with errors, warnings, diagnostics
//! - [`YamlType`] - Detected YAML configuration type (K8s, GitLab CI, etc.)
//! - [`ConfigValidator`] - Trait for implementing configuration validators

use serde::{Deserialize, Serialize};

/// Severity level for validation diagnostics.
///
/// Variants are ordered from most to least severe:
/// `Error` < `Warning` < `Info` < `Hint`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Structure is invalid — must be fixed.
    Error,
    /// Valid but risky — likely a mistake.
    Warning,
    /// Best-practice suggestion.
    Info,
    /// Optional improvement hint.
    Hint,
}

/// A single validation diagnostic with severity and optional path.
///
/// # Example
///
/// ```
/// use devops_models::models::validation::{Diagnostic, Severity};
///
/// let diag = Diagnostic {
///     severity: Severity::Warning,
///     message: "replicas=1 may cause availability issues".to_string(),
///     path: Some("spec > replicas".to_string()),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Diagnostic {
    /// How serious this finding is.
    pub severity: Severity,
    /// Human-readable description of the issue.
    pub message: String,
    /// JSON-pointer-like path to the offending field (e.g. `"spec > template > spec > containers > 0"`).
    #[serde(default)]
    pub path: Option<String>,
}

/// Result of validating a YAML configuration file.
///
/// Contains both simple string lists (errors, warnings) for easy display
/// and rich diagnostics for detailed UI rendering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Whether the configuration passed structural validation (no errors).
    pub valid: bool,
    /// Error messages (structural issues that make the config invalid).
    pub errors: Vec<String>,
    /// Warning messages (valid but risky configurations).
    pub warnings: Vec<String>,
    /// Optimization hints (Info/Hint severity — best-practice suggestions).
    #[serde(default)]
    pub hints: Vec<String>,
    /// Rich diagnostics (superset of errors+warnings+hints, includes Info/Hint).
    #[serde(default)]
    pub diagnostics: Vec<Diagnostic>,
    /// The detected YAML type, if recognized.
    #[serde(default)]
    pub yaml_type: Option<YamlType>,
}

impl ValidationResult {
    /// Convenience: build from a list of Diagnostics.
    pub fn from_diagnostics(yaml_type: YamlType, diags: Vec<Diagnostic>) -> Self {
        let errors: Vec<String> = diags
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message.clone())
            .collect();
        let warnings: Vec<String> = diags
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message.clone())
            .collect();
        let hints: Vec<String> = diags
            .iter()
            .filter(|d| matches!(d.severity, Severity::Info | Severity::Hint))
            .map(|d| d.message.clone())
            .collect();
        let valid = errors.is_empty();
        Self {
            valid,
            errors,
            warnings,
            hints,
            diagnostics: diags,
            yaml_type: Some(yaml_type),
        }
    }
}

/// Detected YAML configuration type.
///
/// Used by [`ValidationResult::yaml_type`] to report which format was
/// recognised.  Variant names are self-documenting (e.g. `K8sDeployment`,
/// `GitLabCI`, `DockerCompose`).
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum YamlType {
    // ── Kubernetes ──
    K8sDeployment,
    K8sService,
    K8sConfigMap,
    K8sSecret,
    K8sIngress,
    K8sHPA,
    K8sCronJob,
    K8sJob,
    K8sPVC,
    K8sNetworkPolicy,
    K8sStatefulSet,
    K8sDaemonSet,
    K8sRole,
    K8sClusterRole,
    K8sRoleBinding,
    K8sClusterRoleBinding,
    K8sServiceAccount,
    /// Any resource with apiVersion+kind that we don't have a specific model for.
    K8sGeneric,
    // ── CI/CD ──
    GitLabCI,
    GitHubActions,
    // ── Container orchestration ──
    DockerCompose,
    // ── Monitoring ──
    Prometheus,
    Alertmanager,
    // ── Configuration ──
    HelmValues,
    Ansible,
    // ── API ──
    OpenAPI,
    // ── Fallback ──
    Generic,
}

impl std::fmt::Display for YamlType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::K8sDeployment => write!(f, "K8s Deployment"),
            Self::K8sService => write!(f, "K8s Service"),
            Self::K8sConfigMap => write!(f, "K8s ConfigMap"),
            Self::K8sSecret => write!(f, "K8s Secret"),
            Self::K8sIngress => write!(f, "K8s Ingress"),
            Self::K8sHPA => write!(f, "K8s HPA"),
            Self::K8sCronJob => write!(f, "K8s CronJob"),
            Self::K8sJob => write!(f, "K8s Job"),
            Self::K8sPVC => write!(f, "K8s PVC"),
            Self::K8sNetworkPolicy => write!(f, "K8s NetworkPolicy"),
            Self::K8sStatefulSet => write!(f, "K8s StatefulSet"),
            Self::K8sDaemonSet => write!(f, "K8s DaemonSet"),
            Self::K8sRole => write!(f, "K8s Role"),
            Self::K8sClusterRole => write!(f, "K8s ClusterRole"),
            Self::K8sRoleBinding => write!(f, "K8s RoleBinding"),
            Self::K8sClusterRoleBinding => write!(f, "K8s ClusterRoleBinding"),
            Self::K8sServiceAccount => write!(f, "K8s ServiceAccount"),
            Self::K8sGeneric => write!(f, "K8s (generic)"),
            Self::GitLabCI => write!(f, "GitLab CI"),
            Self::GitHubActions => write!(f, "GitHub Actions"),
            Self::DockerCompose => write!(f, "Docker Compose"),
            Self::Prometheus => write!(f, "Prometheus"),
            Self::Alertmanager => write!(f, "Alertmanager"),
            Self::HelmValues => write!(f, "Helm Values"),
            Self::Ansible => write!(f, "Ansible Playbook"),
            Self::OpenAPI => write!(f, "OpenAPI"),
            Self::Generic => write!(f, "Generic YAML"),
        }
    }
}

/// Trait that all configuration validators implement.
///
/// Adding a new config type involves:
/// 1. Creating a struct that deserializes from YAML via serde
/// 2. Implementing this trait with structure and semantic validation
/// 3. Registering the type in `yaml_validator::detect_yaml_type()`
///
/// # Example
///
/// ```rust,ignore
/// use shared::models::validation::{ConfigValidator, Diagnostic, Severity, YamlType};
///
/// struct MyConfig {
///     name: String,
/// }
///
/// impl ConfigValidator for MyConfig {
///     fn yaml_type(&self) -> YamlType {
///         YamlType::Generic
///     }
///
///     fn validate_structure(&self) -> Vec<Diagnostic> {
///         if self.name.is_empty() {
///             vec![Diagnostic {
///                 severity: Severity::Error,
///                 message: "name cannot be empty".to_string(),
///                 path: Some("name".to_string()),
///             }]
///         } else {
///             vec![]
///         }
///     }
///
///     fn validate_semantics(&self) -> Vec<Diagnostic> {
///         vec![]
///     }
/// }
/// ```
pub trait ConfigValidator {
    /// The YAML type this validator handles.
    fn yaml_type(&self) -> YamlType;

    /// Structural validation — errors mean the config is invalid.
    ///
    /// Returns diagnostics for issues that make the configuration
    /// syntactically or structurally invalid (missing required fields,
    /// wrong types, etc.).
    fn validate_structure(&self) -> Vec<Diagnostic>;

    /// Semantic validation — best-practice warnings, hints, and info.
    ///
    /// Returns diagnostics for issues that are technically valid but
    /// may indicate misconfiguration or deviate from best practices
    /// (e.g., replicas=1, missing resource limits).
    fn validate_semantics(&self) -> Vec<Diagnostic>;

    /// Full validation: structure + semantics combined.
    fn validate(&self) -> ValidationResult {
        let mut diags = self.validate_structure();
        diags.extend(self.validate_semantics());
        ValidationResult::from_diagnostics(self.yaml_type(), diags)
    }
}

/// Output of the YAML auto-repair pipeline.
///
/// Returned by [`devops_validate::repair::repair_yaml`](../../../devops_validate/repair/fn.repair_yaml.html).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepairResult {
    /// `true` if no issues remain after applying fixes.
    pub valid: bool,
    /// The repaired YAML string (may equal input if nothing was fixed).
    pub repaired_yaml: String,
    /// Issues that could not be auto-fixed.
    pub errors: Vec<String>,
    /// Fixes that were applied (human-readable log).
    pub warnings: Vec<String>,
    /// Fields that were ambiguous and need LLM assistance.
    pub llm_fields: Vec<String>,
    /// Single-sentence summary of the repair outcome.
    pub summary: String,
}

/// Record of a single deterministic fix applied during repair.
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixRecord {
    pub field_path: String,
    pub old_value: serde_json::Value,
    pub new_value: serde_json::Value,
    pub reason: String,
}

/// A field that the repair pipeline could not fix automatically.
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmbiguityQuestion {
    pub field_path: String,
    pub question: String,
    pub options: Vec<String>,
    #[serde(default)]
    pub default: Option<String>,
}

/// Stateful session tracking an interactive validation + repair workflow.
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationSession {
    pub session_id: String,
    pub yaml_original: String,
    pub yaml_current: String,
    pub fixes_applied: Vec<FixRecord>,
    pub pending_ambiguities: Vec<AmbiguityQuestion>,
    pub status: SessionStatus,
    pub created_at: String,
}

/// Lifecycle status of a [`ValidationSession`].
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SessionStatus {
    InProgress,
    WaitingUser,
    Completed,
}

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

    #[test]
    fn test_severity_ordering() {
        // Enum variants are ordered by declaration: Error < Warning < Info < Hint
        // So Error is the "smallest" (least severe in terms of code)
        // but semantically Error is the most severe issue
        assert!(Severity::Error < Severity::Warning);
        assert!(Severity::Warning < Severity::Info);
        assert!(Severity::Info < Severity::Hint);
    }

    #[test]
    fn test_severity_serde_roundtrip() {
        let sev = Severity::Warning;
        let json = serde_json::to_string(&sev).unwrap();
        assert_eq!(json, r#""warning""#);
        let parsed: Severity = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, Severity::Warning);
    }

    #[test]
    fn test_yaml_type_display() {
        assert_eq!(format!("{}", YamlType::K8sDeployment), "K8s Deployment");
        assert_eq!(format!("{}", YamlType::DockerCompose), "Docker Compose");
        assert_eq!(format!("{}", YamlType::GitLabCI), "GitLab CI");
        assert_eq!(format!("{}", YamlType::GitHubActions), "GitHub Actions");
        assert_eq!(format!("{}", YamlType::Prometheus), "Prometheus");
        assert_eq!(format!("{}", YamlType::Generic), "Generic YAML");
    }

    #[test]
    fn test_yaml_type_serde_roundtrip() {
        let yt = YamlType::K8sService;
        let json = serde_json::to_string(&yt).unwrap();
        let parsed: YamlType = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, YamlType::K8sService);
    }

    #[test]
    fn test_validation_result_from_diagnostics() {
        let diags = vec![
            Diagnostic {
                severity: Severity::Error,
                message: "Test error".to_string(),
                path: Some("spec".to_string()),
            },
            Diagnostic {
                severity: Severity::Warning,
                message: "Test warning".to_string(),
                path: None,
            },
            Diagnostic {
                severity: Severity::Info,
                message: "Info message".to_string(),
                path: None,
            },
        ];

        let result = ValidationResult::from_diagnostics(YamlType::K8sDeployment, diags);

        assert!(!result.valid);
        assert_eq!(result.errors.len(), 1);
        assert_eq!(result.warnings.len(), 1);
        assert_eq!(result.hints.len(), 1);
        assert_eq!(result.diagnostics.len(), 3);
        assert_eq!(result.yaml_type, Some(YamlType::K8sDeployment));
    }

    #[test]
    fn test_validation_result_valid_when_no_errors() {
        let diags = vec![
            Diagnostic {
                severity: Severity::Warning,
                message: "Warning only".to_string(),
                path: None,
            },
        ];

        let result = ValidationResult::from_diagnostics(YamlType::DockerCompose, diags);

        assert!(result.valid);
        assert!(result.errors.is_empty());
        assert_eq!(result.warnings.len(), 1);
    }

    #[test]
    fn test_diagnostic_path_default() {
        let diag = Diagnostic {
            severity: Severity::Error,
            message: "Error".to_string(),
            path: None,
        };
        assert!(diag.path.is_none());

        let diag_with_path = Diagnostic {
            severity: Severity::Error,
            message: "Error".to_string(),
            path: Some("spec > containers > 0".to_string()),
        };
        assert_eq!(diag_with_path.path, Some("spec > containers > 0".to_string()));
    }

    #[test]
    fn test_session_status_serde() {
        let status = SessionStatus::InProgress;
        let json = serde_json::to_string(&status).unwrap();
        // serde rename_all = "lowercase" converts InProgress -> "inprogress"
        assert_eq!(json, r#""inprogress""#);
        let parsed: SessionStatus = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, SessionStatus::InProgress);
    }
}