Skip to main content

engenho_controllers/
drv.rs

1//! `DrvController` — reconciles `DerivationCR` objects through a
2//! `DerivationCacheBackend` (typically a `TieredCache`).
3//!
4//! Each `DerivationCR` in the store names a `drv_hash` the cluster
5//! should hold realisations for. The controller's job is to make
6//! sure those realisations are present in the cache tier the
7//! consumer can read from + to patch the CR's status with the
8//! resolved output paths.
9//!
10//! ## Reconcile rule
11//!
12//! For each `DerivationCR`:
13//!   1. Read `spec.drvHash` (hex string).
14//!   2. Look up the drv in the cache. If absent → mark CR
15//!      `status.phase = "DrvUnknown"`, skip.
16//!   3. List realisations. If non-empty → patch CR status with
17//!      `phase = "Realised"` + `realisations: [{name, path}]`.
18//!   4. If no realisations → mark `phase = "Pending"` (consumer
19//!      controller — R-DRV-BUILD — picks it up).
20//!
21//! Idempotent: re-tick with no change is a no-op (status patches
22//! only fire when the computed phase / realisations differ).
23
24use std::sync::Arc;
25
26use async_trait::async_trait;
27use engenho_store::{
28    StoreMesh,
29    command::{Reason, ResourceCommand},
30};
31use engenho_substrate::{DerivationCacheBackend, DrvHash};
32use serde_json::{Value, json};
33
34use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
35use crate::effect::Effect;
36use crate::error::ControllerError;
37
38/// Controller that propagates derivation state from a cache backend
39/// into the K8s store as `DerivationCR.status`.
40pub struct DrvController {
41    store: Arc<StoreMesh>,
42    cache: Arc<dyn DerivationCacheBackend>,
43    namespace: Option<String>,
44}
45
46impl DrvController {
47    /// New controller.
48    #[must_use]
49    pub fn new(
50        store: Arc<StoreMesh>,
51        cache: Arc<dyn DerivationCacheBackend>,
52        namespace: Option<String>,
53    ) -> Self {
54        Self {
55            store,
56            cache,
57            namespace,
58        }
59    }
60
61    /// Parse a `DrvHash` from a hex string. Pure helper.
62    ///
63    /// # Errors
64    /// Returns None if the string isn't 64 lowercase hex characters.
65    #[must_use]
66    pub fn parse_drv_hash(s: &str) -> Option<DrvHash> {
67        if s.len() != 64 || !s.chars().all(|c| c.is_ascii_hexdigit()) {
68            return None;
69        }
70        let mut bytes = [0u8; 32];
71        for i in 0..32 {
72            bytes[i] = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).ok()?;
73        }
74        Some(DrvHash::new(bytes))
75    }
76}
77
78#[async_trait]
79impl Controller for DrvController {
80    fn name(&self) -> &'static str {
81        "drv"
82    }
83
84    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
85        let drs = self
86            .store
87            .list("engenho.io", "v1", "Derivation", self.namespace.as_deref())
88            .await;
89        let mut report = ReconcileReport::default();
90        report.objects_examined = drs.len();
91
92        for (cr_key, cr_value) in &drs {
93            let drv_hash_str = cr_value
94                .get("spec")
95                .and_then(|s| s.get("drvHash"))
96                .and_then(|h| h.as_str());
97            let Some(hash_str) = drv_hash_str else {
98                report.objects_skipped += 1;
99                continue;
100            };
101            let Some(hash) = Self::parse_drv_hash(hash_str) else {
102                report.objects_skipped += 1;
103                continue;
104            };
105
106            // Phase computation.
107            let phase: &str;
108            let realisations_json: Value;
109            match self
110                .cache
111                .get_drv(&hash)
112                .await
113                .map_err(|e| ControllerError::Internal(e.to_string()))?
114            {
115                None => {
116                    phase = "DrvUnknown";
117                    realisations_json = json!([]);
118                }
119                Some(_drv) => {
120                    let realisations = self
121                        .cache
122                        .list_realisations(&hash)
123                        .await
124                        .map_err(|e| ControllerError::Internal(e.to_string()))?;
125                    if realisations.is_empty() {
126                        phase = "Pending";
127                        realisations_json = json!([]);
128                    } else {
129                        phase = "Realised";
130                        realisations_json = serde_json::to_value(
131                            realisations
132                                .iter()
133                                .map(|r| {
134                                    json!({
135                                        "name": r.output_name,
136                                        "path": r.output_path.as_str(),
137                                    })
138                                })
139                                .collect::<Vec<_>>(),
140                        )
141                        .unwrap_or(json!([]));
142                    }
143                }
144            }
145
146            // Idempotency: only patch when the computed status differs.
147            let current_phase = cr_value
148                .get("status")
149                .and_then(|s| s.get("phase"))
150                .and_then(|p| p.as_str());
151            let current_realisations = cr_value
152                .get("status")
153                .and_then(|s| s.get("realisations"))
154                .cloned();
155            if current_phase == Some(phase)
156                && current_realisations.as_ref() == Some(&realisations_json)
157            {
158                continue;
159            }
160
161            let applied = self
162                .store
163                .propose(ResourceCommand::patch(
164                    cr_key.clone(),
165                    json!({
166                        "status": {
167                            "phase": phase,
168                            "realisations": realisations_json,
169                        }
170                    }),
171                    Reason::Controller,
172                ))
173                .await?;
174            report.record(Effect::of(applied.op));
175        }
176        Ok(report.into())
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn parse_drv_hash_accepts_64_hex_chars() {
186        let s = "a".repeat(64);
187        let h = DrvController::parse_drv_hash(&s).unwrap();
188        assert_eq!(h.0[0], 0xaa);
189        assert_eq!(h.0[31], 0xaa);
190    }
191
192    #[test]
193    fn parse_drv_hash_rejects_wrong_length() {
194        assert!(DrvController::parse_drv_hash("abc").is_none());
195        assert!(DrvController::parse_drv_hash(&"a".repeat(63)).is_none());
196        assert!(DrvController::parse_drv_hash(&"a".repeat(65)).is_none());
197    }
198
199    #[test]
200    fn parse_drv_hash_rejects_non_hex() {
201        let bad = "g".repeat(64);
202        assert!(DrvController::parse_drv_hash(&bad).is_none());
203        let bad = format!("{}{}", "a".repeat(63), "Z");
204        assert!(DrvController::parse_drv_hash(&bad).is_none());
205    }
206
207    #[test]
208    fn parse_drv_hash_round_trips_via_to_hex() {
209        let h = DrvHash::from_bytes(b"engenho-substrate");
210        let back = DrvController::parse_drv_hash(&h.to_hex()).unwrap();
211        assert_eq!(back, h);
212    }
213
214    #[test]
215    fn controller_name_is_stable() {
216        struct F;
217        #[async_trait]
218        impl Controller for F {
219            fn name(&self) -> &'static str {
220                "drv"
221            }
222            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
223                Ok(ReconcileReport::default().into())
224            }
225        }
226        assert_eq!(F.name(), "drv");
227    }
228}