Skip to main content

stackless_core/engine/
revision.rs

1//! Stable digests of the inputs each lifecycle step consumes.
2
3use serde_json::json;
4use sha2::{Digest, Sha256};
5
6use super::StepKind;
7use crate::substrate::{StepContext, SubstrateFault};
8
9pub fn digest(value: &impl serde::Serialize) -> Result<String, SubstrateFault> {
10    let bytes = serde_json::to_vec(value).map_err(|_| SubstrateFault {
11        code: "engine.revision_invalid".into(),
12        message: "cannot serialize desired inputs".into(),
13        remediation: "repair the definition before retrying".into(),
14        context: Box::default(),
15    })?;
16    Ok(format!("{:x}", Sha256::digest(bytes)))
17}
18
19pub fn step_revision(
20    ctx: &StepContext<'_>,
21    substrate: &(impl crate::substrate::Substrate + ?Sized),
22) -> Result<String, SubstrateFault> {
23    let provider = substrate.name();
24    let name = &ctx.step.node;
25    let value = if ctx.step.kind == StepKind::ProvisionIntegration {
26        json!({"integration":ctx.def.integrations.get(name), "project":ctx.def.stack.projects})
27    } else if let Some(service) = ctx.def.services.get(name) {
28        match ctx.step.kind {
29            StepKind::Materialize => {
30                json!({"source":service.source,"override":ctx.source_overrides.get(name),"dirty":ctx.dirty,"image":service.image,"setup":service.setup,"prepare":service.prepare,"runtime":service.substrates.get(provider)})
31            }
32            StepKind::Setup => {
33                json!({"source":service.source,"setup":service.setup,"env":service.env,"secrets":service.secrets,"timeout_secs":service.timeout_secs,"runtime":service.substrates.get(provider)})
34            }
35            StepKind::HealthGate => json!({"health":service.health}),
36            _ => {
37                json!({"source":service.source,"prepare":service.prepare,"env":service.env,"secrets":service.secrets,"runtime":service.substrates.get(provider),"stack":ctx.def.stack.substrates.get(provider),"root_origin":service.root_origin,"run":service.run,"kind":service.kind,"image":service.image,"timeout_secs":service.timeout_secs})
38            }
39        }
40    } else {
41        serde_json::Value::Null
42    };
43    let mut origin_inputs = std::collections::BTreeSet::new();
44    let mut endpoint_inputs = std::collections::BTreeMap::new();
45    let mut integration_steps = std::collections::BTreeSet::new();
46    if let Some(service) = ctx.def.services.get(name) {
47        for value in service
48            .effective_env(name, provider)
49            .map_err(|error| SubstrateFault::from_fault(&error))?
50            .values()
51        {
52            for reference in crate::def::interp::references(value, "env")
53                .map_err(|error| SubstrateFault::from_fault(&error))?
54            {
55                match reference {
56                    crate::def::Reference::IntegrationOutput { integration, .. } => {
57                        integration_steps.insert(format!("integration:{integration}"));
58                    }
59                    crate::def::Reference::ServiceOrigin(service) => {
60                        origin_inputs.insert(service);
61                    }
62                    crate::def::Reference::EndpointUrl(endpoint) => {
63                        if let Some(spec) = ctx.def.endpoints.get(&endpoint) {
64                            endpoint_inputs.insert(endpoint, spec);
65                        }
66                    }
67                    _ => {}
68                }
69            }
70        }
71    }
72    let upstream: Vec<_> = if matches!(
73        ctx.step.kind,
74        StepKind::Setup | StepKind::Prepare | StepKind::Start | StepKind::RunJob
75    ) {
76        ctx.prior
77            .iter()
78            .filter(|cp| {
79                cp.step_id == format!("materialize:{name}")
80                    || integration_steps.contains(&cp.step_id)
81            })
82            .map(|cp| {
83                let payload = if cp.resource_kind == "source-snapshot" {
84                    let value: serde_json::Value =
85                        serde_json::from_str(&cp.payload).map_err(|_| SubstrateFault {
86                            code: "engine.revision_invalid".into(),
87                            message: "invalid source snapshot checkpoint".into(),
88                            remediation: "inspect the recorded source snapshot".into(),
89                            context: Box::default(),
90                        })?;
91                    if matches!(ctx.step.kind, StepKind::Setup | StepKind::Prepare) {
92                        // Hooks consume the working copy, including setup output. A new
93                        // snapshot needs its own execution even when the commit is unchanged.
94                        json!({"repo":value["repo"],"commit":value["commit"],"digest":value["digest"],"snapshot":value["key"]})
95                    } else {
96                        json!({"repo":value["repo"],"commit":value["commit"],"digest":value["digest"]})
97                    }
98                } else {
99                    serde_json::Value::String(cp.payload.clone())
100                };
101                Ok((cp.step_id.clone(), payload))
102            })
103            .collect::<Result<Vec<_>, SubstrateFault>>()?
104    } else {
105        Vec::new()
106    };
107    let mut inputs = json!({"kind":ctx.step.kind,"input":value,"upstream":upstream});
108    if (!endpoint_inputs.is_empty() || !origin_inputs.is_empty())
109        && matches!(
110            ctx.step.kind,
111            StepKind::Setup | StepKind::Prepare | StepKind::Start | StepKind::RunJob
112        )
113    {
114        let mut namespace = substrate.build_namespace(
115            ctx.def,
116            ctx.instance,
117            ctx.prior,
118            &std::collections::BTreeMap::new(),
119            crate::substrate::NamespacePurpose::ServiceEnv,
120        );
121        namespace.bind_endpoints(ctx.def);
122        let endpoint_urls: std::collections::BTreeMap<_, _> = endpoint_inputs
123            .keys()
124            .map(|name| (name, namespace.endpoint_urls.get(name)))
125            .collect();
126        if !endpoint_inputs.is_empty() {
127            inputs["endpoint_urls"] = json!(endpoint_urls);
128            inputs["endpoints"] = json!(endpoint_inputs);
129        }
130        if !origin_inputs.is_empty() {
131            let origins: std::collections::BTreeMap<_, _> = origin_inputs
132                .iter()
133                .map(|name| (name, namespace.service_origins.get(name)))
134                .collect();
135            inputs["service_origins"] = json!(origins);
136        }
137    }
138    digest(&inputs)
139}