Skip to main content

engenho_controllers/
store_ledger.rs

1//! `StoreBackedLedger` — `MaterializationLedger` impl backed by
2//! `engenho-store`. Receipts commit through the store's existing
3//! Raft path; reads aggregate the committed receipts back into a
4//! `QuorumTracker`.
5//!
6//! This is the load-bearing impl that makes
7//! `ConfirmacaoPolicy::RaftCommitted` meaningful: receipts are
8//! durable, replicated, byzantine-fault-tolerant within the
9//! cluster's existing consensus group.
10//!
11//! ## Wire shape
12//!
13//! Each receipt commits as a typed resource:
14//!
15//!   group: engenho.io
16//!   version: v1
17//!   kind: `MaterializationReceipt`
18//!   namespace: configurable (default: engenho-system)
19//!   name: {stage_id}-{kind}-{subject_hex_short}-{emitter_hex_short}
20//!   spec.receipt: <serialized MaterializationReceipt>
21//!   `spec.stage_id`: {`stage_id`}
22//!   spec.threshold: {usize}
23//!
24//! ## Aggregation
25//!
26//! `outcome()` walks all receipts matching a `LedgerKey`, folds them
27//! into a `QuorumTracker` built with the stored threshold, and returns
28//! the tracker's own verdict. It never computes a verdict itself: the
29//! verdict is sealed, so there is no second copy of the fold here.
30//! A receipt whose stored threshold is missing or zero is skipped like
31//! an undecodable one.
32//! `forget_stage` deletes every receipt resource for the stage.
33
34use std::num::NonZeroUsize;
35use std::sync::Arc;
36
37use async_trait::async_trait;
38use engenho_store::{
39    StoreMesh,
40    command::{Reason, ResourceCommand},
41    resource::ResourceKey,
42};
43use engenho_substrate::{
44    LedgerError, LedgerKey, MaterializationLedger, MaterializationReceipt, QuorumTracker,
45    QuorumVerdict, ReceiptKind, StageId,
46};
47use serde_json::json;
48
49/// Default namespace for receipt resources.
50pub const DEFAULT_RECEIPT_NAMESPACE: &str = "engenho-system";
51
52/// `MaterializationLedger` backed by engenho-store.
53pub struct StoreBackedLedger {
54    store: Arc<StoreMesh>,
55    namespace: String,
56}
57
58impl StoreBackedLedger {
59    /// New ledger writing receipts to the default namespace
60    /// (`engenho-system`).
61    #[must_use]
62    pub fn new(store: Arc<StoreMesh>) -> Self {
63        Self::with_namespace(store, DEFAULT_RECEIPT_NAMESPACE.into())
64    }
65
66    /// New ledger with explicit namespace.
67    #[must_use]
68    pub fn with_namespace(store: Arc<StoreMesh>, namespace: String) -> Self {
69        Self { store, namespace }
70    }
71
72    /// Compose the resource name for a receipt. Uses short hex
73    /// prefixes to keep names readable while ensuring uniqueness
74    /// per (stage, kind, subject, emitter) tuple.
75    #[must_use]
76    pub fn receipt_name(stage_id: &StageId, receipt: &MaterializationReceipt) -> String {
77        let kind_tag = match &receipt.kind {
78            ReceiptKind::Drv => "drv".to_string(),
79            ReceiptKind::Nar => "nar".to_string(),
80            ReceiptKind::Realisation => "realisation".to_string(),
81            ReceiptKind::BuildResult => "build-result".to_string(),
82            ReceiptKind::Shape(t) => format!("shape-{}", sanitize(t)),
83        };
84        let subj_short = hex_short(&receipt.subject);
85        let emit_short = hex_short(&receipt.emitter.0);
86        format!(
87            "{}-{}-{}-{}",
88            sanitize(stage_id.as_str()),
89            kind_tag,
90            subj_short,
91            emit_short,
92        )
93    }
94
95    fn resource_key_for(
96        &self,
97        stage_id: &StageId,
98        receipt: &MaterializationReceipt,
99    ) -> ResourceKey {
100        ResourceKey::namespaced(
101            "engenho.io",
102            "v1",
103            "MaterializationReceipt",
104            &self.namespace,
105            Self::receipt_name(stage_id, receipt),
106        )
107    }
108}
109
110#[async_trait]
111impl MaterializationLedger for StoreBackedLedger {
112    fn name(&self) -> &'static str {
113        "store-backed"
114    }
115
116    async fn ingest(
117        &self,
118        stage_id: &StageId,
119        threshold: NonZeroUsize,
120        receipt: &MaterializationReceipt,
121    ) -> Result<QuorumVerdict, LedgerError> {
122        // Commit the receipt as a typed resource.
123        let receipt_json = serde_json::to_value(receipt)
124            .map_err(|e| LedgerError::Backend(format!("encode receipt: {e}")))?;
125        let key = self.resource_key_for(stage_id, receipt);
126        let value = json!({
127            "apiVersion": "engenho.io/v1",
128            "kind": "MaterializationReceipt",
129            "metadata": {
130                "name": Self::receipt_name(stage_id, receipt),
131                "namespace": self.namespace,
132            },
133            "spec": {
134                "stage_id": stage_id.as_str(),
135                "threshold": threshold.get(),
136                "receipt": receipt_json,
137            },
138        });
139        self.store
140            .propose(ResourceCommand::Put {
141                key,
142                value,
143                expected: None,
144                reason: Reason::Controller,
145            })
146            .await
147            .map_err(|e| LedgerError::Backend(format!("store propose: {e}")))?;
148
149        // Re-aggregate to produce the outcome.
150        let ledger_key = LedgerKey {
151            stage_id: stage_id.clone(),
152            kind: receipt.kind.clone(),
153            subject: receipt.subject,
154        };
155        match self.outcome(&ledger_key).await? {
156            Some(verdict) => Ok(verdict),
157            // The list did not show the receipt just committed: report
158            // the empty fold (pending, nothing counted) rather than guess.
159            None => {
160                Ok(QuorumTracker::new(receipt.kind.clone(), receipt.subject, threshold).verdict())
161            }
162        }
163    }
164
165    async fn outcome(&self, key: &LedgerKey) -> Result<Option<QuorumVerdict>, LedgerError> {
166        let all = self
167            .store
168            .list(
169                "engenho.io",
170                "v1",
171                "MaterializationReceipt",
172                Some(&self.namespace),
173            )
174            .await;
175        let mut tracker: Option<QuorumTracker> = None;
176        for (_, v) in all {
177            let spec = match v.get("spec") {
178                Some(s) => s,
179                None => continue,
180            };
181            let stage_id = spec
182                .get("stage_id")
183                .and_then(|s| s.as_str())
184                .map(StageId::new);
185            if stage_id.as_ref() != Some(&key.stage_id) {
186                continue;
187            }
188            let receipt: MaterializationReceipt = match spec
189                .get("receipt")
190                .cloned()
191                .and_then(|r| serde_json::from_value(r).ok())
192            {
193                Some(r) => r,
194                None => continue,
195            };
196            if receipt.kind != key.kind || receipt.subject != key.subject {
197                continue;
198            }
199            // The first committed receipt fixes the threshold (operators
200            // shouldn't disagree on threshold for the same key).
201            let Some(threshold) = spec
202                .get("threshold")
203                .and_then(serde_json::Value::as_u64)
204                .and_then(|n| usize::try_from(n).ok())
205                .and_then(NonZeroUsize::new)
206            else {
207                continue;
208            };
209            tracker
210                .get_or_insert_with(|| {
211                    QuorumTracker::new(receipt.kind.clone(), receipt.subject, threshold)
212                })
213                .ingest(&receipt);
214        }
215        Ok(tracker.map(|t| t.verdict()))
216    }
217
218    async fn forget_stage(&self, stage_id: &StageId) -> Result<(), LedgerError> {
219        let all = self
220            .store
221            .list(
222                "engenho.io",
223                "v1",
224                "MaterializationReceipt",
225                Some(&self.namespace),
226            )
227            .await;
228        for (key, v) in all {
229            let stage = v
230                .get("spec")
231                .and_then(|s| s.get("stage_id"))
232                .and_then(|s| s.as_str())
233                .map(StageId::new);
234            if stage.as_ref() == Some(stage_id) {
235                self.store
236                    .propose(ResourceCommand::delete(key, Reason::Controller))
237                    .await
238                    .map_err(|e| LedgerError::Backend(format!("store delete: {e}")))?;
239            }
240        }
241        Ok(())
242    }
243}
244
245fn sanitize(s: &str) -> String {
246    s.chars()
247        .map(|c| match c {
248            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' => c,
249            _ => '-',
250        })
251        .collect::<String>()
252        .trim_matches('-')
253        .to_lowercase()
254}
255
256fn hex_short(bytes: &[u8]) -> String {
257    const HEX: &[u8] = b"0123456789abcdef";
258    let mut s = String::with_capacity(8);
259    for b in bytes.iter().take(4) {
260        s.push(HEX[(b >> 4) as usize] as char);
261        s.push(HEX[(b & 0x0f) as usize] as char);
262    }
263    s
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269    use engenho_substrate::{NodeId, ReceiptKind};
270
271    fn rcpt_drv(emitter: u8, evidence: u8) -> MaterializationReceipt {
272        MaterializationReceipt::for_drv([7u8; 32], NodeId::new([emitter; 32]), 100, [evidence; 32])
273    }
274
275    fn rcpt_shape(emitter: u8, evidence: u8, tag: &str) -> MaterializationReceipt {
276        MaterializationReceipt::new(
277            ReceiptKind::Shape(tag.to_string()),
278            [7u8; 32],
279            NodeId::new([emitter; 32]),
280            100,
281            [evidence; 32],
282        )
283    }
284
285    fn stage() -> StageId {
286        StageId::new("build-image")
287    }
288
289    fn nz(n: usize) -> NonZeroUsize {
290        NonZeroUsize::new(n).expect("test thresholds are non-zero")
291    }
292
293    async fn test_store(name: &str) -> Arc<StoreMesh> {
294        use engenho_store::{InProcessRouter, default_config};
295        let router = InProcessRouter::new();
296        let cfg = default_config(name).unwrap();
297        let store = Arc::new(
298            StoreMesh::start(1, "in-process://1".into(), router, cfg)
299                .await
300                .unwrap(),
301        );
302        store.initialize_singleton().await.unwrap();
303        assert!(
304            store
305                .wait_for_leadership(std::time::Duration::from_secs(3))
306                .await
307        );
308        store
309    }
310
311    fn drv_key() -> LedgerKey {
312        LedgerKey {
313            stage_id: stage(),
314            kind: ReceiptKind::Drv,
315            subject: [7u8; 32],
316        }
317    }
318
319    // ── outcome: the tracker's verdict, not a second fold ──────
320
321    #[tokio::test]
322    async fn outcome_is_the_trackers_verdict_against_the_stored_threshold() {
323        let ledger = StoreBackedLedger::new(test_store("store-ledger-threshold").await);
324        let first = ledger
325            .ingest(&stage(), nz(3), &rcpt_drv(1, 5))
326            .await
327            .unwrap();
328        let read = ledger
329            .outcome(&drv_key())
330            .await
331            .unwrap()
332            .expect("slot exists");
333        assert_eq!(read.state(), engenho_substrate::QuorumState::Pending);
334        assert_eq!((read.confirmed(), read.threshold()), (1, nz(3)));
335        assert_eq!(read, first);
336        ledger
337            .ingest(&stage(), nz(3), &rcpt_drv(2, 5))
338            .await
339            .unwrap();
340        let last = ledger
341            .ingest(&stage(), nz(3), &rcpt_drv(3, 5))
342            .await
343            .unwrap();
344        assert!(last.is_reached());
345        assert_eq!(ledger.outcome(&drv_key()).await.unwrap(), Some(last));
346    }
347
348    #[tokio::test]
349    async fn a_receipt_with_a_zero_threshold_is_not_counted() {
350        let store = test_store("store-ledger-zero").await;
351        let ledger = StoreBackedLedger::new(store.clone());
352        let receipt = rcpt_drv(1, 5);
353        let name = StoreBackedLedger::receipt_name(&stage(), &receipt);
354        store
355            .propose(ResourceCommand::Put {
356                key: ResourceKey::namespaced(
357                    "engenho.io",
358                    "v1",
359                    "MaterializationReceipt",
360                    DEFAULT_RECEIPT_NAMESPACE,
361                    &name,
362                ),
363                value: json!({
364                    "apiVersion": "engenho.io/v1",
365                    "kind": "MaterializationReceipt",
366                    "metadata": {"name": name, "namespace": DEFAULT_RECEIPT_NAMESPACE},
367                    "spec": {
368                        "stage_id": stage().as_str(),
369                        "threshold": 0,
370                        "receipt": serde_json::to_value(&receipt).unwrap(),
371                    },
372                }),
373                expected: None,
374                reason: Reason::Controller,
375            })
376            .await
377            .unwrap();
378        assert_eq!(ledger.outcome(&drv_key()).await.unwrap(), None);
379    }
380
381    // ── receipt_name ──────────────────────────────────────────
382
383    #[test]
384    fn receipt_name_includes_stage_kind_subject_emitter() {
385        let r = rcpt_drv(1, 5);
386        let name = StoreBackedLedger::receipt_name(&stage(), &r);
387        assert!(name.starts_with("build-image-drv-"));
388        assert!(name.contains("0707")); // subject prefix (4 bytes hex)
389        assert!(name.contains("0101")); // emitter prefix (4 bytes hex)
390    }
391
392    #[test]
393    fn receipt_name_sanitizes_stage_id() {
394        let r = rcpt_drv(1, 5);
395        let name = StoreBackedLedger::receipt_name(&StageId::new("build/with.slash"), &r);
396        assert!(!name.contains('/'));
397        assert!(!name.contains('.'));
398    }
399
400    #[test]
401    fn receipt_name_uses_kind_tag() {
402        let r_drv = rcpt_drv(1, 5);
403        let r_nar =
404            MaterializationReceipt::for_nar([7u8; 32], NodeId::new([1u8; 32]), 100, [5u8; 32]);
405        let r_shape = rcpt_shape(1, 5, "oci_image");
406        assert!(StoreBackedLedger::receipt_name(&stage(), &r_drv).contains("-drv-"));
407        assert!(StoreBackedLedger::receipt_name(&stage(), &r_nar).contains("-nar-"));
408        let shape_name = StoreBackedLedger::receipt_name(&stage(), &r_shape);
409        assert!(shape_name.contains("shape-oci-image"));
410    }
411
412    #[test]
413    fn receipt_name_per_emitter_is_unique() {
414        let r1 = rcpt_drv(1, 5);
415        let r2 = rcpt_drv(2, 5);
416        let n1 = StoreBackedLedger::receipt_name(&stage(), &r1);
417        let n2 = StoreBackedLedger::receipt_name(&stage(), &r2);
418        assert_ne!(n1, n2);
419    }
420
421    #[test]
422    fn sanitize_drops_special_chars() {
423        assert_eq!(sanitize("hello/world"), "hello-world");
424        assert_eq!(sanitize("X.Y.Z"), "x-y-z");
425        assert_eq!(sanitize("--leading-trailing--"), "leading-trailing");
426    }
427
428    #[test]
429    fn hex_short_is_8_chars_lowercase_hex() {
430        let h = hex_short(&[0xab, 0xcd, 0xef, 0x12, 0x34]);
431        assert_eq!(h, "abcdef12");
432        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
433    }
434
435    #[test]
436    fn default_namespace_constant() {
437        assert_eq!(DEFAULT_RECEIPT_NAMESPACE, "engenho-system");
438    }
439}