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
428
429
430
431
432
433
434
435
436
437
438
439
use serde::{Deserialize, Serialize};
use crate::models::k8s::{K8sMetadata, K8sPodTemplate};
use crate::models::validation::{ConfigValidator, Diagnostic, Severity, YamlType};

// ═══════════════════════════════════════════════════════════════════════════
// HorizontalPodAutoscaler (v2)
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPAMetricTarget {
    #[serde(default, rename = "type")]
    pub target_type: Option<String>,
    #[serde(default, rename = "averageUtilization")]
    pub average_utilization: Option<u32>,
    #[serde(default, rename = "averageValue")]
    pub average_value: Option<String>,
    #[serde(default)]
    pub value: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPAMetricResource {
    pub name: String,
    pub target: HPAMetricTarget,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPAMetric {
    #[serde(rename = "type")]
    pub metric_type: String,
    #[serde(default)]
    pub resource: Option<HPAMetricResource>,
    #[serde(default)]
    pub pods: Option<serde_json::Value>,
    #[serde(default)]
    pub object: Option<serde_json::Value>,
    #[serde(default)]
    pub external: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPAScaleTargetRef {
    #[serde(rename = "apiVersion")]
    pub api_version: Option<String>,
    pub kind: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPABehaviorPolicy {
    #[serde(rename = "type")]
    pub policy_type: String,
    pub value: u32,
    #[serde(rename = "periodSeconds")]
    pub period_seconds: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPABehaviorRules {
    #[serde(default, rename = "stabilizationWindowSeconds")]
    pub stabilization_window_seconds: Option<u32>,
    #[serde(default)]
    pub policies: Vec<HPABehaviorPolicy>,
    #[serde(default, rename = "selectPolicy")]
    pub select_policy: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPABehavior {
    #[serde(default, rename = "scaleUp")]
    pub scale_up: Option<HPABehaviorRules>,
    #[serde(default, rename = "scaleDown")]
    pub scale_down: Option<HPABehaviorRules>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HPASpec {
    #[serde(rename = "scaleTargetRef")]
    pub scale_target_ref: HPAScaleTargetRef,
    #[serde(rename = "minReplicas")]
    pub min_replicas: Option<u32>,
    #[serde(rename = "maxReplicas")]
    pub max_replicas: u32,
    #[serde(default)]
    pub metrics: Vec<HPAMetric>,
    #[serde(default)]
    pub behavior: Option<HPABehavior>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct K8sHPA {
    #[serde(rename = "apiVersion")]
    pub api_version: String,
    pub kind: String,
    pub metadata: K8sMetadata,
    pub spec: HPASpec,
}

impl ConfigValidator for K8sHPA {
    fn yaml_type(&self) -> YamlType { YamlType::K8sHPA }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if let Some(min) = self.spec.min_replicas
            && min > self.spec.max_replicas {
                diags.push(Diagnostic {
                    severity: Severity::Error,
                    message: format!("minReplicas ({}) > maxReplicas ({})", min, self.spec.max_replicas),
                    path: Some("spec".into()),
                });
            }
        if self.spec.max_replicas == 0 {
            diags.push(Diagnostic {
                severity: Severity::Error,
                message: "maxReplicas is 0 — HPA will not create any pods".into(),
                path: Some("spec > maxReplicas".into()),
            });
        }
        diags
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if self.spec.metrics.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Warning,
                message: "No metrics defined — HPA will default to CPU at 80%".into(),
                path: Some("spec > metrics".into()),
            });
        }
        if self.spec.min_replicas == Some(0) {
            diags.push(Diagnostic {
                severity: Severity::Warning,
                message: "minReplicas=0 — scale-to-zero requires KEDA or custom setup".into(),
                path: Some("spec > minReplicas".into()),
            });
        }
        if self.spec.max_replicas > 100 {
            diags.push(Diagnostic {
                severity: Severity::Info,
                message: format!("maxReplicas={} is unusually high", self.spec.max_replicas),
                path: Some("spec > maxReplicas".into()),
            });
        }
        diags
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CronJob
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CronJobJobTemplate {
    #[serde(default)]
    pub metadata: Option<K8sMetadata>,
    pub spec: JobSpec,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CronJobSpec {
    pub schedule: String,
    #[serde(default, rename = "timeZone")]
    pub time_zone: Option<String>,
    #[serde(default, rename = "concurrencyPolicy")]
    pub concurrency_policy: Option<String>,
    #[serde(default, rename = "suspend")]
    pub suspend: Option<bool>,
    #[serde(default, rename = "successfulJobsHistoryLimit")]
    pub successful_jobs_history_limit: Option<u32>,
    #[serde(default, rename = "failedJobsHistoryLimit")]
    pub failed_jobs_history_limit: Option<u32>,
    #[serde(default, rename = "startingDeadlineSeconds")]
    pub starting_deadline_seconds: Option<u64>,
    #[serde(rename = "jobTemplate")]
    pub job_template: CronJobJobTemplate,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct K8sCronJob {
    #[serde(rename = "apiVersion")]
    pub api_version: String,
    pub kind: String,
    pub metadata: K8sMetadata,
    pub spec: CronJobSpec,
}

/// Basic cron expression validation (5 fields: min hour dom month dow)
fn is_valid_cron(expr: &str) -> bool {
    let parts: Vec<&str> = expr.split_whitespace().collect();
    parts.len() == 5
}

impl ConfigValidator for K8sCronJob {
    fn yaml_type(&self) -> YamlType { YamlType::K8sCronJob }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if !is_valid_cron(&self.spec.schedule) {
            diags.push(Diagnostic {
                severity: Severity::Error,
                message: format!("Invalid cron schedule '{}' — expected 5 fields (min hour dom month dow)", self.spec.schedule),
                path: Some("spec > schedule".into()),
            });
        }
        diags
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if let Some(policy) = &self.spec.concurrency_policy
            && !["Allow", "Forbid", "Replace"].contains(&policy.as_str()) {
                diags.push(Diagnostic {
                    severity: Severity::Warning,
                    message: format!("Unknown concurrencyPolicy '{}' — expected Allow/Forbid/Replace", policy),
                    path: Some("spec > concurrencyPolicy".into()),
                });
            }
        if self.spec.suspend == Some(true) {
            diags.push(Diagnostic {
                severity: Severity::Info,
                message: "CronJob is suspended — no jobs will be created".into(),
                path: Some("spec > suspend".into()),
            });
        }
        // Warn if schedule runs very frequently
        if self.spec.schedule.starts_with("* ") || self.spec.schedule.starts_with("*/1 ") {
            diags.push(Diagnostic {
                severity: Severity::Warning,
                message: "CronJob runs every minute — ensure this is intentional".into(),
                path: Some("spec > schedule".into()),
            });
        }
        diags
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Job
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JobSpec {
    pub template: K8sPodTemplate,
    #[serde(default, rename = "backoffLimit")]
    pub backoff_limit: Option<u32>,
    #[serde(default)]
    pub completions: Option<u32>,
    #[serde(default)]
    pub parallelism: Option<u32>,
    #[serde(default, rename = "activeDeadlineSeconds")]
    pub active_deadline_seconds: Option<u64>,
    #[serde(default, rename = "ttlSecondsAfterFinished")]
    pub ttl_seconds_after_finished: Option<u64>,
    #[serde(default)]
    pub selector: Option<serde_json::Value>,
    #[serde(default, rename = "completionMode")]
    pub completion_mode: Option<String>,
    #[serde(default, rename = "manualSelector")]
    pub manual_selector: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct K8sJob {
    #[serde(rename = "apiVersion")]
    pub api_version: String,
    pub kind: String,
    pub metadata: K8sMetadata,
    pub spec: JobSpec,
}

impl ConfigValidator for K8sJob {
    fn yaml_type(&self) -> YamlType { YamlType::K8sJob }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        vec![]
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if let Some(limit) = self.spec.backoff_limit
            && limit > 10 {
                diags.push(Diagnostic {
                    severity: Severity::Warning,
                    message: format!("backoffLimit={} is high — job will retry many times before giving up", limit),
                    path: Some("spec > backoffLimit".into()),
                });
            }
        if self.spec.active_deadline_seconds.is_none() {
            diags.push(Diagnostic {
                severity: Severity::Info,
                message: "No activeDeadlineSeconds — job may run indefinitely".into(),
                path: Some("spec > activeDeadlineSeconds".into()),
            });
        }
        // Check restartPolicy
        let restart = self.spec.template.spec.restart_policy.as_deref().unwrap_or("Always");
        if restart == "Always" {
            diags.push(Diagnostic {
                severity: Severity::Warning,
                message: "Job template has restartPolicy=Always — should be 'Never' or 'OnFailure'".into(),
                path: Some("spec > template > spec > restartPolicy".into()),
            });
        }
        diags
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// StatefulSet
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StatefulSetSpec {
    #[serde(default)]
    pub replicas: Option<u32>,
    #[serde(rename = "serviceName")]
    pub service_name: String,
    pub selector: serde_json::Value,
    pub template: K8sPodTemplate,
    #[serde(default, rename = "volumeClaimTemplates")]
    pub volume_claim_templates: Vec<serde_json::Value>,
    #[serde(default, rename = "updateStrategy")]
    pub update_strategy: Option<serde_json::Value>,
    #[serde(default, rename = "podManagementPolicy")]
    pub pod_management_policy: Option<String>,
    #[serde(default, rename = "revisionHistoryLimit")]
    pub revision_history_limit: Option<u32>,
    #[serde(default, rename = "minReadySeconds")]
    pub min_ready_seconds: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct K8sStatefulSet {
    #[serde(rename = "apiVersion")]
    pub api_version: String,
    pub kind: String,
    pub metadata: K8sMetadata,
    pub spec: StatefulSetSpec,
}

impl ConfigValidator for K8sStatefulSet {
    fn yaml_type(&self) -> YamlType { YamlType::K8sStatefulSet }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if self.spec.service_name.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Error,
                message: "serviceName is required for StatefulSet".into(),
                path: Some("spec > serviceName".into()),
            });
        }
        diags
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        if self.spec.volume_claim_templates.is_empty() {
            diags.push(Diagnostic {
                severity: Severity::Info,
                message: "No volumeClaimTemplates — StatefulSet pods will have no persistent storage".into(),
                path: Some("spec > volumeClaimTemplates".into()),
            });
        }
        if self.spec.replicas == Some(0) {
            diags.push(Diagnostic {
                severity: Severity::Warning,
                message: "replicas=0 — no pods will be created".into(),
                path: Some("spec > replicas".into()),
            });
        }
        diags
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DaemonSet
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DaemonSetSpec {
    pub selector: serde_json::Value,
    pub template: K8sPodTemplate,
    #[serde(default, rename = "updateStrategy")]
    pub update_strategy: Option<serde_json::Value>,
    #[serde(default, rename = "revisionHistoryLimit")]
    pub revision_history_limit: Option<u32>,
    #[serde(default, rename = "minReadySeconds")]
    pub min_ready_seconds: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct K8sDaemonSet {
    #[serde(rename = "apiVersion")]
    pub api_version: String,
    pub kind: String,
    pub metadata: K8sMetadata,
    pub spec: DaemonSetSpec,
}

impl ConfigValidator for K8sDaemonSet {
    fn yaml_type(&self) -> YamlType { YamlType::K8sDaemonSet }

    fn validate_structure(&self) -> Vec<Diagnostic> {
        vec![]
    }

    fn validate_semantics(&self) -> Vec<Diagnostic> {
        let mut diags = Vec::new();
        let tolerations = self.spec.template.spec.tolerations.as_ref();
        if tolerations.is_none() || tolerations.map(|t| t.is_null()).unwrap_or(true) {
            diags.push(Diagnostic {
                severity: Severity::Info,
                message: "No tolerations — DaemonSet won't schedule on tainted nodes (including control-plane)".into(),
                path: Some("spec > template > spec > tolerations".into()),
            });
        }
        diags
    }
}