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