lava-operator 0.5.11

lava-operator — typed Kubernetes controller for the LavaArchitecture CRD. Operators submit a LavaArchitecture manifest naming a .tlisp source + bindings + gate; the controller renders via magma-lava + applies via the embedded magma path (or shells out to tofu/terraform). Status conditions track Synthesized / Planned / Applied / Failed phases. Pangea-operator analog for the lava + tatara-lisp stack.
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
//! lava-operator — typed Kubernetes controller for the LavaArchitecture
//! CRD. Pangea-operator analog for the lava + tatara-lisp stack.
//!
//! ## Shape
//!
//! Operator authors a LavaArchitecture manifest:
//!
//! ```yaml
//! apiVersion: lava.pleme.io/v1alpha1
//! kind: LavaArchitecture
//! metadata: { name: prod-vpc, namespace: infra }
//! spec:
//!   source:
//!     # Either inline tlisp source ...
//!     inline: |
//!       (deflava-architecture demo-vpc
//!         :inputs ((:cidr "10.42.0.0/16"))
//!         :resources ((aws-vpc "main" :cidr-block "{cidr}")))
//!     # ... or a registry-hosted reference:
//!     # name: aws-vpc-network  (looks up bundled architecture)
//!   bindings:
//!     name: prod
//!     cidr: 10.42.0.0/16
//!   gate: aws-vpc-network              # optional typed Interface gate
//!   engine: embedded                   # embedded | tofu | terraform
//! status:
//!   phase: Applied
//!   conditions:
//!     - type: Synthesized | Planned | Applied | Failed
//!       status: True
//! ```
//!
//! The controller's Reconcile loop:
//!   1. Resolve source (inline or bundled name)
//!   2. magma-lava::synthesize → typed Architecture + terraform.json
//!   3. (Optional) typed-interface gate
//!   4. engine: embedded (in-process) OR shell out to tofu/terraform
//!   5. Status update with typed Conditions
//!
//! ## Status
//!
//! This crate ships the **typed CRD schema** + **reconcile state machine**
//! (typed Phase + Condition + RenderRecord values). The kube-rs
//! controller binary is the next-milestone (M1) wrapper — keeps this
//! crate dependency-light + testable without a live cluster.

#![allow(clippy::module_name_repetitions)]

pub mod anomaly_bridge;
pub mod attest;
pub mod drift;
pub mod finalizer;
pub mod viggy_loop;

#[cfg(feature = "controller")]
pub mod controller;

#[cfg(all(feature = "controller", feature = "magma-bridge"))]
pub mod magma_bridge;

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Top-level CRD spec + status.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LavaArchitecture {
    pub api_version: String,
    pub kind: String,
    pub metadata: ObjectMeta,
    pub spec: LavaArchitectureSpec,
    #[serde(default)]
    pub status: LavaArchitectureStatus,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObjectMeta {
    pub name: String,
    #[serde(default)]
    pub namespace: Option<String>,
    #[serde(default)]
    pub labels: IndexMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LavaArchitectureSpec {
    pub source: Source,
    #[serde(default)]
    pub bindings: IndexMap<String, String>,
    #[serde(default)]
    pub gate: Option<String>,
    #[serde(default = "default_engine")]
    pub engine: String,
}

fn default_engine() -> String {
    "embedded".to_string()
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Source {
    /// .tlisp source text embedded directly.
    Inline { inline: String },
    /// Bundled architecture name (looked up via lava-architectures).
    Name { name: String },
    /// Remote git ref + path.
    Git {
        url: String,
        rev: String,
        path: String,
    },
}

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct LavaArchitectureStatus {
    #[serde(default)]
    pub phase: Option<Phase>,
    #[serde(default)]
    pub conditions: Vec<Condition>,
    #[serde(default)]
    pub last_synthesized_hash: Option<String>,
    #[serde(default)]
    pub last_applied_at: Option<String>,
}

/// Typed phase the controller drives the resource through.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum Phase {
    /// Initial state; nothing rendered yet.
    Pending,
    /// magma-lava produced typed Architecture + terraform.json.
    Synthesized,
    /// engine plan succeeded; no apply yet.
    Planned,
    /// engine apply succeeded; live resources match desired state.
    Applied,
    /// Drift detector found non-NoOp changes against live state;
    /// the next tick will reconverge per the remediation policy.
    Drifted,
    /// Reconciling to close detected drift.
    Reconverging,
    /// Finalizer is running — destroy in progress before CR removal.
    Finalizing,
    /// Last reconcile failed (see conditions for details).
    Failed,
}

impl Phase {
    /// Stable string token. Used in OutcomeChain payload + CRD status.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "Pending",
            Self::Synthesized => "Synthesized",
            Self::Planned => "Planned",
            Self::Applied => "Applied",
            Self::Drifted => "Drifted",
            Self::Reconverging => "Reconverging",
            Self::Finalizing => "Finalizing",
            Self::Failed => "Failed",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Condition {
    #[serde(rename = "type")]
    pub kind: String,
    pub status: String, // True | False | Unknown
    #[serde(default)]
    pub reason: Option<String>,
    #[serde(default)]
    pub message: Option<String>,
    #[serde(default)]
    pub last_transition_time: Option<String>,
}

impl Condition {
    #[must_use]
    pub fn ok(kind: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            kind: kind.into(),
            status: "True".into(),
            reason: Some(reason.into()),
            message: None,
            last_transition_time: None,
        }
    }
    #[must_use]
    pub fn fail(kind: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            kind: kind.into(),
            status: "False".into(),
            reason: Some("Error".into()),
            message: Some(message.into()),
            last_transition_time: None,
        }
    }
}

/// Result of one reconcile pass. The controller serializes this back
/// into the resource's `.status` block.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReconcileOutcome {
    pub phase: Phase,
    pub conditions: Vec<Condition>,
    pub terraform_json: Option<serde_json::Value>,
}

/// Pure state-machine: given the current resource + a synthesize
/// callback, advance the phase. The kube-rs wrapper supplies the
/// callback (which routes through magma-lava); this function stays
/// kube-free + unit-testable.
pub fn reconcile<F>(
    spec: &LavaArchitectureSpec,
    synthesize_fn: F,
) -> Result<ReconcileOutcome, ReconcileError>
where
    F: FnOnce(&Source, &IndexMap<String, String>, Option<&str>)
        -> Result<serde_json::Value, String>,
{
    let synthesized = synthesize_fn(&spec.source, &spec.bindings, spec.gate.as_deref());
    match synthesized {
        Ok(tf_json) => Ok(ReconcileOutcome {
            phase: Phase::Synthesized,
            conditions: vec![Condition::ok("Synthesized", "RenderOk")],
            terraform_json: Some(tf_json),
        }),
        Err(e) => Ok(ReconcileOutcome {
            phase: Phase::Failed,
            conditions: vec![Condition::fail("Synthesized", e)],
            terraform_json: None,
        }),
    }
}

#[derive(Debug, Error)]
pub enum ReconcileError {
    #[error("synthesize: {0}")]
    Synthesize(String),
    #[error("apply: {0}")]
    Apply(String),
}

/// Render the LavaArchitecture CRD YAML for `kubectl apply`.
/// Backwards-compat single-CRD form — new consumers should use
/// [`crd_yaml_all`] which emits every CRD the operator owns.
pub fn crd_yaml() -> String {
    crd_yaml_for("LavaArchitecture", "lavaarchitectures", "lavaarchitecture")
}

/// Emit every CRD the operator owns, joined with `---` separators
/// so the output is a single `kubectl apply -f -` stream. Each CRD
/// carries a full `openAPIV3Schema` derived from the kube-rs
/// `#[derive(CustomResource, JsonSchema)]` shapes — apiextensions/v1
/// requires this; the hand-rolled `crd_yaml_for` helper below is
/// kept only for the backwards-compat single-CRD form.
#[cfg(feature = "controller")]
pub fn crd_yaml_all() -> String {
    use kube::CustomResourceExt;
    let parts: Vec<String> = [
        serde_yaml::to_string(&crate::controller::LavaArchitecture::crd()).unwrap_or_default(),
        serde_yaml::to_string(&crate::controller::RemediationPolicy::crd()).unwrap_or_default(),
        serde_yaml::to_string(&crate::controller::LavaArchitectureDependency::crd())
            .unwrap_or_default(),
    ]
    .into_iter()
    .collect();
    parts.join("---\n")
}

#[cfg(not(feature = "controller"))]
pub fn crd_yaml_all() -> String {
    // Without the controller feature, fall back to the schema-less
    // hand-rolled form — kept so library consumers can still preview
    // CRD names without pulling kube-rs.
    let parts = [
        crd_yaml_for("LavaArchitecture", "lavaarchitectures", "lavaarchitecture"),
        crd_yaml_for("RemediationPolicy", "remediationpolicies", "remediationpolicy"),
        crd_yaml_for(
            "LavaArchitectureDependency",
            "lavaarchitecturedependencies",
            "lavaarchitecturedependency",
        ),
    ];
    parts.join("---\n")
}

fn crd_yaml_for(kind: &str, plural: &str, singular: &str) -> String {
    let list_kind = format!("{kind}List");
    let names = serde_yaml::Mapping::from_iter([
        ("kind".into(), kind.into()),
        ("listKind".into(), list_kind.into()),
        ("plural".into(), plural.into()),
        ("singular".into(), singular.into()),
    ]);
    let version = serde_yaml::Mapping::from_iter([
        ("name".into(), "v1alpha1".into()),
        ("served".into(), serde_yaml::Value::Bool(true)),
        ("storage".into(), serde_yaml::Value::Bool(true)),
    ]);
    let crd_spec = serde_yaml::Mapping::from_iter([
        ("group".into(), "lava.pleme.io".into()),
        ("scope".into(), "Namespaced".into()),
        ("names".into(), serde_yaml::Value::Mapping(names)),
        (
            "versions".into(),
            serde_yaml::Value::Sequence(vec![serde_yaml::Value::Mapping(version)]),
        ),
    ]);
    let metadata_name = format!("{plural}.lava.pleme.io");
    let crd = serde_yaml::Mapping::from_iter([
        ("apiVersion".into(), "apiextensions.k8s.io/v1".into()),
        ("kind".into(), "CustomResourceDefinition".into()),
        (
            "metadata".into(),
            serde_yaml::Value::Mapping(serde_yaml::Mapping::from_iter([(
                "name".into(),
                metadata_name.into(),
            )])),
        ),
        ("spec".into(), serde_yaml::Value::Mapping(crd_spec)),
    ]);
    serde_yaml::to_string(&serde_yaml::Value::Mapping(crd)).unwrap_or_default()
}

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

    fn sample_spec() -> LavaArchitectureSpec {
        LavaArchitectureSpec {
            source: Source::Inline {
                inline: "(deflava-architecture demo :inputs () :resources ())".into(),
            },
            bindings: IndexMap::new(),
            gate: None,
            engine: "embedded".into(),
        }
    }

    #[test]
    fn reconcile_drives_to_synthesized_when_synthesize_callback_succeeds() {
        let outcome = reconcile(&sample_spec(), |_src, _b, _g| {
            Ok(serde_json::json!({"resource": {}}))
        })
        .unwrap();
        assert_eq!(outcome.phase, Phase::Synthesized);
        assert_eq!(outcome.conditions[0].status, "True");
        assert!(outcome.terraform_json.is_some());
    }

    #[test]
    fn reconcile_drives_to_failed_when_synthesize_callback_errors() {
        let outcome = reconcile(&sample_spec(), |_src, _b, _g| {
            Err("render failed: bad input".to_string())
        })
        .unwrap();
        assert_eq!(outcome.phase, Phase::Failed);
        assert_eq!(outcome.conditions[0].status, "False");
        assert!(outcome.terraform_json.is_none());
    }

    #[test]
    fn condition_ok_and_fail_constructors_set_status_correctly() {
        let ok = Condition::ok("Synthesized", "RenderOk");
        assert_eq!(ok.status, "True");
        assert_eq!(ok.reason.as_deref(), Some("RenderOk"));
        let fail = Condition::fail("Applied", "tofu apply exited non-zero");
        assert_eq!(fail.status, "False");
        assert_eq!(fail.message.as_deref(), Some("tofu apply exited non-zero"));
    }

    #[test]
    fn lava_architecture_round_trips_through_serde_yaml() {
        let la = LavaArchitecture {
            api_version: "lava.pleme.io/v1alpha1".into(),
            kind: "LavaArchitecture".into(),
            metadata: ObjectMeta {
                name: "prod-vpc".into(),
                namespace: Some("infra".into()),
                labels: IndexMap::new(),
            },
            spec: sample_spec(),
            status: LavaArchitectureStatus::default(),
        };
        let yaml = serde_yaml::to_string(&la).unwrap();
        let parsed: LavaArchitecture = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(la, parsed);
    }

    #[test]
    fn source_variants_round_trip_through_serde() {
        for src in [
            Source::Inline { inline: "(x)".into() },
            Source::Name { name: "aws-vpc".into() },
            Source::Git {
                url: "https://github.com/x/y".into(),
                rev: "main".into(),
                path: "infra/vpc.tlisp".into(),
            },
        ] {
            let json = serde_json::to_string(&src).unwrap();
            let parsed: Source = serde_json::from_str(&json).unwrap();
            assert_eq!(src, parsed);
        }
    }

    #[test]
    fn crd_yaml_emits_valid_two_doc_apiextensions_yaml() {
        let yaml = crd_yaml();
        assert!(yaml.contains("apiVersion: apiextensions.k8s.io/v1"));
        assert!(yaml.contains("kind: CustomResourceDefinition"));
        assert!(yaml.contains("name: lavaarchitectures.lava.pleme.io"));
        assert!(yaml.contains("group: lava.pleme.io"));
        assert!(yaml.contains("v1alpha1"));
    }

    #[test]
    fn crd_yaml_all_emits_every_owned_crd() {
        let yaml = crd_yaml_all();
        assert!(yaml.contains("lavaarchitectures.lava.pleme.io"));
        assert!(yaml.contains("remediationpolicies.lava.pleme.io"));
        assert!(yaml.contains("lavaarchitecturedependencies.lava.pleme.io"));
        // Three docs separated by `---`.
        assert_eq!(yaml.matches("kind: CustomResourceDefinition").count(), 3);
    }

    #[test]
    fn phase_variants_serialize_as_pascal_case_strings() {
        let p = Phase::Synthesized;
        let json = serde_json::to_string(&p).unwrap();
        assert_eq!(json, "\"Synthesized\"");
    }
}