Skip to main content

magma_controller/
lib.rs

1//! magma-controller — complete operator-loop composition.
2//!
3//! Wraps `Reconciler` + `DriftPolicy` + `BudgetedReconciler` +
4//! `PlanStream` + `LifecycleState` + `Bundle` + `Metrics` into ONE
5//! reusable controller. The "I want a complete operator" composition
6//! every reconciler kind plugs into.
7//!
8//! Calling `controller.reconcile(&config)` runs the full loop:
9//!
10//! 1. FSM Idle → Planning
11//! 2. read_state (via budgeted reconciler)
12//! 3. compute_plan + emit PlanComputed event + metrics
13//! 4. classify drift against policy + emit DriftClassified event + metrics
14//! 5. branch on ReconcileResult:
15//!    * NoChange → FSM → Stable
16//!    * Refused → FSM → Refused
17//!    * HeldForApproval → FSM → Approving (caller drives further)
18//!    * Applied → apply + emit ApplyOutcome event + metrics + FSM →
19//!      Verifying → Stable
20//! 6. build a tamper-evident magma-bundle
21//! 7. return a typed ControllerOutcome carrying the bundle + final FSM state
22//!
23//! Per `theory/CONVERGENCE-SUBSTRATE.md` §IV.5 + §IV.7.
24
25#![deny(unsafe_code)]
26
27use std::sync::Arc;
28
29use async_trait::async_trait;
30use serde::{Deserialize, Serialize};
31use serde_json::Value;
32use thiserror::Error;
33
34use magma_budget::BudgetedReconciler;
35use magma_bundle::{Bundle, BundleError};
36use magma_converge::{Reconciler, ReconcilerError};
37use magma_drift::{DriftPolicy, ReconcileResult, classify, reconcile_with_policy};
38use magma_fsm::{LifecycleState, Phase, TransitionError};
39use magma_metrics::Metrics;
40use magma_stream::PlanStream;
41
42// ── Errors ────────────────────────────────────────────────────────
43
44#[derive(Debug, Error)]
45pub enum ControllerError {
46    #[error("reconciler: {0}")]
47    Reconciler(#[from] ReconcilerError),
48    #[error("fsm transition: {0}")]
49    FsmTransition(#[from] TransitionError),
50    #[error("bundle: {0}")]
51    Bundle(#[from] BundleError),
52}
53
54// ── Typed terminal result ─────────────────────────────────────────
55
56/// Output of one `reconcile(...)` call. Wraps the typed
57/// `ReconcileResult` from magma-drift (no duplicate enum) plus the
58/// FSM lifecycle snapshot and the tamper-evident Bundle.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct ControllerOutcome {
61    pub result: ReconcileResult,
62    pub bundle: Bundle,
63    pub lifecycle: LifecycleState,
64}
65
66impl ControllerOutcome {
67    /// Convenience: did the reconcile reach Stable?
68    pub fn fully_succeeded(&self) -> bool {
69        matches!(
70            self.result,
71            ReconcileResult::NoChange { .. } | ReconcileResult::Applied { .. }
72        ) && self.lifecycle.current == Phase::Stable
73    }
74}
75
76// ── ReconcileController ───────────────────────────────────────────
77
78/// The complete operator loop, parameterized by reconciler kind.
79pub struct ReconcileController<R: Reconciler> {
80    /// Wrapped reconciler with budget + retry built in.
81    reconciler: Arc<BudgetedReconciler<R>>,
82    /// Drift classification policy.
83    policy: DriftPolicy,
84    /// Shared event stream (typically wired with K8sEventSink +
85    /// JsonLinesSink + TracingSink by the operator).
86    stream: Arc<PlanStream>,
87    /// Prometheus metrics handle (shared across kinds).
88    metrics: Arc<Metrics>,
89    /// Workspace identifier (CR name + namespace, or the
90    /// operator-side state-name triple).
91    workspace: String,
92}
93
94impl<R: Reconciler> ReconcileController<R> {
95    pub fn new(
96        reconciler: BudgetedReconciler<R>,
97        policy: DriftPolicy,
98        stream: Arc<PlanStream>,
99        metrics: Arc<Metrics>,
100        workspace: impl Into<String>,
101    ) -> Self {
102        Self {
103            reconciler: Arc::new(reconciler),
104            policy,
105            stream,
106            metrics,
107            workspace: workspace.into(),
108        }
109    }
110
111    /// Reconciler kind for this controller (echoes the inner reconciler's
112    /// `kind()`).
113    pub fn kind(&self) -> &'static str {
114        self.reconciler.kind()
115    }
116
117    /// Run the full reconcile loop end-to-end.
118    pub async fn reconcile(&self, config: &Value) -> Result<ControllerOutcome, ControllerError> {
119        let mut lifecycle = LifecycleState::new();
120        lifecycle.transition(Phase::Planning, None, "controller: trigger")?;
121
122        // The composed dispatch — magma-budget owns concurrency +
123        // retry; magma-drift owns classify + decide + apply.
124        let result = reconcile_with_policy(&*self.reconciler, config, &self.policy).await?;
125
126        // Universal metric + stream emission via the typed
127        // ReconcileResult accessors — no per-variant branching.
128        let plan_id = result.plan_id().clone();
129        self.metrics.record_plan(result.plan());
130        self.stream.emit_plan(self.kind(), result.plan()).await;
131        if let Some(report) = result.report() {
132            self.metrics.record_drift(report);
133            self.stream.emit_drift(report).await;
134        }
135        if let Some(outcome) = result.outcome() {
136            self.metrics.record_outcome(outcome);
137            self.stream.emit_outcome(outcome).await;
138        }
139
140        // Drive the FSM through phases based on the typed result kind.
141        let (final_phase, reason) = match &result {
142            ReconcileResult::NoChange { .. } => (Phase::Stable, "no changes".into()),
143            ReconcileResult::Refused { refused, .. } => (
144                Phase::Refused,
145                format!("policy refused {refused} change(s)"),
146            ),
147            ReconcileResult::HeldForApproval { held, .. } => (
148                Phase::Approving,
149                format!("policy requires approval on {held} change(s)"),
150            ),
151            ReconcileResult::Applied { .. } => {
152                lifecycle.transition(Phase::Applying, Some(plan_id.clone()), "applying")?;
153                lifecycle.transition(Phase::Verifying, Some(plan_id.clone()), "applied")?;
154                (Phase::Stable, "verified, no drift".into())
155            }
156            ReconcileResult::AppliedWithFailures { outcome, .. } => {
157                lifecycle.transition(Phase::Applying, Some(plan_id.clone()), "applying")?;
158                lifecycle.transition(
159                    Phase::Verifying,
160                    Some(plan_id.clone()),
161                    "applied with failures",
162                )?;
163                (
164                    Phase::Failed,
165                    format!("{} resource(s) failed apply", outcome.failed.len()),
166                )
167            }
168        };
169        lifecycle.transition(final_phase, Some(plan_id), reason)?;
170
171        let drift_for_bundle = match result.report() {
172            Some(report) => report.clone(),
173            None => classify(result.plan(), &self.policy),
174        };
175        let bundle = Bundle::new(
176            self.kind(),
177            self.workspace.clone(),
178            result.plan().clone(),
179            result.outcome().cloned(),
180            drift_for_bundle,
181            lifecycle.clone(),
182            vec![],
183        )?;
184
185        Ok(ControllerOutcome {
186            result,
187            bundle,
188            lifecycle,
189        })
190    }
191}
192
193/// Erased ReconcileController surface, useful when storing many
194/// controllers of different kinds in one collection.
195#[async_trait]
196pub trait DynController: Send + Sync {
197    fn kind(&self) -> &'static str;
198    async fn reconcile(&self, config: &Value) -> Result<ControllerOutcome, ControllerError>;
199}
200
201#[async_trait]
202impl<R: Reconciler + 'static> DynController for ReconcileController<R> {
203    fn kind(&self) -> &'static str {
204        ReconcileController::kind(self)
205    }
206    async fn reconcile(&self, config: &Value) -> Result<ControllerOutcome, ControllerError> {
207        ReconcileController::reconcile(self, config).await
208    }
209}
210
211// ── Tests ──────────────────────────────────────────────────────────
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216    use magma_budget::{ConcurrencyLimit, RetryPolicy};
217    use magma_converge::inmemory::InMemoryKvReconciler;
218    use prometheus::Registry;
219    use serde_json::json;
220
221    fn make_controller() -> (ReconcileController<InMemoryKvReconciler>, Registry) {
222        let inner = InMemoryKvReconciler::new();
223        let budgeted =
224            BudgetedReconciler::new(inner, ConcurrencyLimit::new(4), RetryPolicy::none());
225        let registry = Registry::new();
226        let metrics = Arc::new(Metrics::register(&registry).unwrap());
227        let stream = Arc::new(PlanStream::new());
228        let controller = ReconcileController::new(
229            budgeted,
230            DriftPolicy::conservative_default(),
231            stream,
232            metrics,
233            "ws-1",
234        );
235        (controller, registry)
236    }
237
238    #[tokio::test]
239    async fn no_change_path_reaches_stable() {
240        let (controller, _registry) = make_controller();
241        // Empty config + empty state → no plan, FSM → Stable.
242        let outcome = controller.reconcile(&json!({})).await.unwrap();
243        assert!(matches!(outcome.result, ReconcileResult::NoChange { .. }));
244        assert_eq!(outcome.lifecycle.current, Phase::Stable);
245        assert!(outcome.fully_succeeded());
246    }
247
248    #[tokio::test]
249    async fn applied_path_walks_full_fsm() {
250        let (controller, _registry) = make_controller();
251        // Config with two creates → all Functional → AutoCorrectWithAlert → applied.
252        let outcome = controller
253            .reconcile(&json!({ "a": 1, "b": 2 }))
254            .await
255            .unwrap();
256        match &outcome.result {
257            ReconcileResult::Applied {
258                outcome: o, plan, ..
259            } => {
260                assert!(o.fully_succeeded());
261                assert_eq!(o.applied.len(), 2);
262                // Plan now carries the full change set.
263                assert_eq!(plan.change_count(), 2);
264            }
265            other => panic!("expected Applied, got {other:?}"),
266        }
267        assert_eq!(outcome.lifecycle.current, Phase::Stable);
268        assert_eq!(outcome.lifecycle.len(), 4);
269        let phases: Vec<Phase> = outcome.lifecycle.history.iter().map(|t| t.to).collect();
270        assert_eq!(
271            phases,
272            vec![
273                Phase::Planning,
274                Phase::Applying,
275                Phase::Verifying,
276                Phase::Stable
277            ]
278        );
279        // Bundle carries the full plan, not the empty-changes hack.
280        assert_eq!(outcome.bundle.change_count(), 2);
281    }
282
283    #[tokio::test]
284    async fn held_for_approval_path_stops_at_approving() {
285        // Pre-seed state with a key whose Delete (Critical) needs approval.
286        let inner = InMemoryKvReconciler::with_state(
287            [("doomed".to_string(), json!("x"))].into_iter().collect(),
288        );
289        let budgeted =
290            BudgetedReconciler::new(inner, ConcurrencyLimit::new(1), RetryPolicy::none());
291        let registry = Registry::new();
292        let metrics = Arc::new(Metrics::register(&registry).unwrap());
293        let stream = Arc::new(PlanStream::new());
294        let controller = ReconcileController::new(
295            budgeted,
296            DriftPolicy::conservative_default(),
297            stream,
298            metrics,
299            "ws-held",
300        );
301
302        let outcome = controller.reconcile(&json!({})).await.unwrap();
303        match &outcome.result {
304            ReconcileResult::HeldForApproval { held, plan, .. } => {
305                assert_eq!(*held, 1);
306                assert_eq!(plan.change_count(), 1);
307            }
308            other => panic!("expected HeldForApproval, got {other:?}"),
309        }
310        assert_eq!(outcome.lifecycle.current, Phase::Approving);
311        assert!(!outcome.fully_succeeded());
312    }
313
314    #[tokio::test]
315    async fn refused_path_stops_at_refused() {
316        let inner = InMemoryKvReconciler::new();
317        let budgeted =
318            BudgetedReconciler::new(inner, ConcurrencyLimit::new(1), RetryPolicy::none());
319        let registry = Registry::new();
320        let metrics = Arc::new(Metrics::register(&registry).unwrap());
321        let stream = Arc::new(PlanStream::new());
322        // Refuse-everything policy.
323        let policy = DriftPolicy {
324            rules: vec![magma_drift::PolicyRule {
325                name: "refuse-all".into(),
326                severity: None,
327                action: None,
328                address_prefix: None,
329                decision: magma_drift::DriftDecision::Refuse,
330            }],
331            fallback: magma_drift::DriftDecision::Refuse,
332        };
333        let controller = ReconcileController::new(budgeted, policy, stream, metrics, "ws-refuse");
334
335        let outcome = controller.reconcile(&json!({ "x": 1 })).await.unwrap();
336        match &outcome.result {
337            ReconcileResult::Refused { refused, plan, .. } => {
338                assert_eq!(*refused, 1);
339                assert_eq!(plan.change_count(), 1);
340            }
341            other => panic!("expected Refused, got {other:?}"),
342        }
343        assert_eq!(outcome.lifecycle.current, Phase::Refused);
344    }
345
346    #[tokio::test]
347    async fn metrics_recorded_during_reconcile() {
348        let (controller, registry) = make_controller();
349        controller.reconcile(&json!({ "a": 1 })).await.unwrap();
350
351        let encoder = prometheus::TextEncoder::new();
352        let mfs = registry.gather();
353        let mut buf = vec![];
354        prometheus::Encoder::encode(&encoder, &mfs, &mut buf).unwrap();
355        let text = String::from_utf8(buf).unwrap();
356        assert!(text.contains(r#"magma_plan_computed_total{kind="inmemory_kv"} 1"#));
357        assert!(
358            text.contains(r#"magma_apply_outcome_total{kind="inmemory_kv",result="applied"} 1"#)
359        );
360    }
361
362    #[tokio::test]
363    async fn dyn_controller_dispatch_works() {
364        let (controller, _registry) = make_controller();
365        let dyn_c: Arc<dyn DynController> = Arc::new(controller);
366        assert_eq!(dyn_c.kind(), "inmemory_kv");
367        let outcome = dyn_c.reconcile(&json!({ "y": 7 })).await.unwrap();
368        assert!(outcome.fully_succeeded());
369    }
370}