Skip to main content

stackless_core/
substrate.rs

1//! The `Substrate` trait — the one provider seam (ARCHITECTURE.md §8).
2//!
3//! Core never names a substrate; providers implement this trait and the
4//! binary registers them by name. Everything per-substrate flows
5//! through here: validation, capabilities, defaults, and the resource
6//! operations the lifecycle engine drives (execute / observe /
7//! destroy). Adding a provider must require zero changes to the engine
8//! or state modules.
9
10use std::collections::BTreeMap;
11use std::time::Duration;
12
13use serde::{Deserialize, Serialize};
14
15use crate::def::{Namespace, StackDef};
16use crate::engine::Step;
17use crate::fault::{ErrorContext, Fault};
18use crate::state::Checkpoint;
19
20/// Structured spend data for cloud `--json` envelopes (§4).
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct SpendInfo {
23    pub provider: String,
24    pub cap_usd: u32,
25    pub summary: String,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub data: Option<serde_json::Value>,
28}
29
30/// A substrate failure, flattened at the trait boundary so the §2
31/// error contract (stable code + remediation) crosses it intact
32/// whatever error enum the provider uses internally.
33#[derive(Debug, thiserror::Error)]
34#[error("{message}")]
35pub struct SubstrateFault {
36    pub code: Box<str>,
37    pub message: String,
38    pub remediation: String,
39    pub context: Box<ErrorContext>,
40}
41
42impl SubstrateFault {
43    pub fn from_fault(fault: &dyn Fault) -> Self {
44        Self {
45            code: fault.code().into(),
46            message: fault.to_string(),
47            remediation: fault.remediation(),
48            context: Box::new(fault.context()),
49        }
50    }
51}
52
53impl Fault for SubstrateFault {
54    fn code(&self) -> &str {
55        &self.code
56    }
57
58    fn remediation(&self) -> String {
59        self.remediation.clone()
60    }
61
62    fn context(&self) -> ErrorContext {
63        self.context.as_ref().clone()
64    }
65}
66
67/// Steps that perform work but create no destructible resource (hooks,
68/// health gates) record this kind; teardown drops their checkpoints
69/// without a destroy/observe round-trip.
70pub const ACTION_RESOURCE_KIND: &str = "action";
71
72pub fn action_resource(step_id: &str) -> StepResource {
73    StepResource {
74        resource_kind: ACTION_RESOURCE_KIND.into(),
75        resource_id: step_id.to_owned(),
76        payload: "{}".into(),
77    }
78}
79
80pub fn present_or_gone(present: bool) -> Observation {
81    if present {
82        Observation::Present
83    } else {
84        Observation::Gone
85    }
86}
87
88/// Which env resolution path is building a namespace.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum NamespacePurpose {
91    /// Service runtime env (Render: internal DB URLs).
92    ServiceEnv,
93    /// Operator-side prepare hooks (Render: external DB URLs).
94    OperatorPrepare,
95    /// `stackless verify` env resolution.
96    Verify,
97}
98
99/// What a recorded resource looks like when re-checked against the
100/// substrate (invariant 4: the manifest says where to look, the
101/// substrate says what's true).
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum Observation {
104    Present,
105    Drifted { settings: Vec<SettingDrift> },
106    Gone,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct SettingDrift {
111    pub setting: String,
112    pub expected: String,
113    pub actual: String,
114}
115
116/// One service's recent logs as a substrate retrieved them, for the `logs`
117/// verb. The substrate owns where the lines come from (a cloud API, a local
118/// file); the CLI only renders them.
119#[derive(Debug, Clone)]
120pub struct ServiceLog {
121    pub service: String,
122    /// Provenance tag for `--json` output (e.g. `"render_api"`, `"file"`).
123    pub source: &'static str,
124    /// Local log file path, when the lines were read from disk.
125    pub log_path: Option<String>,
126    pub lines: Vec<String>,
127}
128
129/// What `execute` hands back for the journal: the resource the step
130/// created (or re-affirmed), recorded before the engine proceeds.
131#[derive(Debug, Clone)]
132pub struct StepResource {
133    pub resource_kind: String,
134    pub resource_id: String,
135    /// Substrate-specific JSON needed to re-find the resource later.
136    pub payload: String,
137}
138
139/// Identity and recorded handles for one instance. Names are user-facing;
140/// resource namespaces belong to one birth and survive retries.
141#[derive(Debug, Clone, Copy)]
142pub struct InstanceContext<'a> {
143    pub name: &'a str,
144    pub id: &'a str,
145    pub resource_namespace: &'a str,
146    pub checkpoints: &'a [Checkpoint],
147    /// Cross-provider URLs supplied by the routing adapter. Missing outputs stay missing.
148    pub routed_origins: Option<&'a BTreeMap<String, String>>,
149}
150
151impl<'a> InstanceContext<'a> {
152    pub fn from_record(
153        record: &'a crate::state::InstanceRecord,
154        checkpoints: &'a [Checkpoint],
155    ) -> Self {
156        Self {
157            name: record.name.as_str(),
158            id: &record.instance_id,
159            resource_namespace: &record.resource_namespace,
160            checkpoints,
161            routed_origins: None,
162        }
163    }
164
165    pub fn bind_namespace(&self, namespace: &mut Namespace, def: &StackDef) {
166        if let Some(origins) = self.routed_origins {
167            namespace.service_origins = origins.clone();
168        }
169        namespace.bind_endpoints(def);
170    }
171
172    /// Stripe resource name, bounded to 52 bytes for new identities.
173    pub fn resource_name(&self, logical_name: &str) -> String {
174        namespaced_resource_name(self.resource_namespace, logical_name)
175    }
176
177    /// Preserve legacy provider names until those instances are destroyed.
178    pub fn provider_resource_name(&self, stack: &str, logical_name: &str) -> String {
179        if self.resource_namespace == self.name {
180            format!("{stack}-{}-{logical_name}", self.name)
181        } else {
182            self.resource_name(logical_name)
183        }
184    }
185}
186
187pub fn namespaced_resource_name(namespace: &str, logical_name: &str) -> String {
188    use sha2::{Digest, Sha256};
189    if namespace.len() == 35
190        && namespace.starts_with("sl-")
191        && namespace[3..].bytes().all(|b| b.is_ascii_hexdigit())
192    {
193        let digest = Sha256::digest(logical_name.as_bytes());
194        let suffix: String = digest[..8].iter().map(|b| format!("{b:02x}")).collect();
195        format!("{namespace}-{suffix}")
196    } else {
197        format!("{namespace}-{logical_name}")
198    }
199}
200
201/// Everything a substrate gets to execute one step.
202#[derive(Debug)]
203pub struct StepContext<'a> {
204    /// Stable across controller recovery of the same accepted operation.
205    pub operation_id: &'a str,
206    pub store: &'a crate::state::Store,
207    pub instance: &'a InstanceContext<'a>,
208    pub def: &'a StackDef,
209    pub step: &'a Step,
210    /// Recorded `--source` pins (service → path), local-only.
211    pub source_overrides: &'a BTreeMap<String, String>,
212    /// Snapshot `--source` pins into instance-owned space instead of using
213    /// them in place.
214    pub dirty: bool,
215    /// Checkpoints recorded so far, in order — earlier steps' resources
216    /// (ports, paths, connection strings) live here.
217    pub prior: &'a [Checkpoint],
218    pub parent_resources: &'a [&'a str],
219    pub cancelled: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
220}
221
222impl StepContext<'_> {
223    pub fn is_cancelled(&self) -> bool {
224        self.cancelled
225            .as_ref()
226            .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire))
227    }
228}
229
230#[async_trait::async_trait]
231pub trait Substrate: Send + Sync {
232    /// The name instances are bound to at creation (`--on <name>`).
233    fn name(&self) -> &str;
234
235    /// Route inventory records without granting ownership of their resources.
236    fn can_manage_resource(&self, resource: &crate::state::ResourceRecord) -> bool {
237        resource.provider == self.name()
238    }
239
240    fn capabilities(&self) -> crate::capabilities::Capabilities;
241
242    fn execution_plan(
243        &self,
244        def: &StackDef,
245    ) -> Result<crate::engine::plan::ExecutionPlan, crate::def::DefError> {
246        def.execution_plan(self.name(), self.capabilities().early_origins)
247    }
248
249    fn supports_source_override_for(&self, _def: &StackDef, _service: &str) -> bool {
250        self.supports_source_override()
251    }
252
253    fn validate(&self, def: &StackDef) -> Result<(), SubstrateFault> {
254        if def
255            .services
256            .values()
257            .any(|workload| workload.on.as_ref().is_some_and(|on| on != self.name()))
258            || def
259                .integrations
260                .values()
261                .any(|resource| resource.on.as_ref().is_some_and(|on| on != self.name()))
262        {
263            return Err(crate::capabilities::unsupported_feature(
264                self.name(),
265                "placement",
266                "mixed provider placement",
267            ));
268        }
269        self.capabilities().validate(self.name(), def)?;
270        self.execution_plan(def)
271            .map_err(|error| SubstrateFault::from_fault(&error))?;
272        self.validate_definition(def)
273    }
274
275    /// Substrate-specific shape validation of the definition — core has
276    /// already checked everything substrate-blind.
277    fn validate_definition(&self, def: &StackDef) -> Result<(), SubstrateFault>;
278
279    /// Whether `--source service=path` pins are allowed here. Local
280    /// substrates say yes; deploy-from-ref substrates say no (§1).
281    fn supports_source_override(&self) -> bool;
282
283    /// Per-substrate lease default (§6).
284    fn default_lease(&self) -> Duration;
285
286    /// The origin `${services.X.origin}` resolves to for this substrate.
287    fn service_origin(
288        &self,
289        def: &StackDef,
290        instance: &InstanceContext<'_>,
291        service: &str,
292    ) -> String {
293        self.build_namespace(
294            def,
295            instance,
296            instance.checkpoints,
297            &BTreeMap::new(),
298            NamespacePurpose::ServiceEnv,
299        )
300        .service_origins
301        .remove(service)
302        .unwrap_or_default()
303    }
304
305    /// Build the interpolation namespace for one instance.
306    fn build_namespace(
307        &self,
308        def: &StackDef,
309        instance: &InstanceContext<'_>,
310        prior: &[Checkpoint],
311        secrets: &BTreeMap<String, String>,
312        purpose: NamespacePurpose,
313    ) -> Namespace;
314
315    /// Execute one step, returning the resource for the journal.
316    async fn execute(&self, ctx: StepContext<'_>) -> Result<StepResource, SubstrateFault>;
317
318    fn step_revision(&self, ctx: &StepContext<'_>) -> Result<String, SubstrateFault> {
319        crate::engine::revision::step_revision(ctx, self)
320    }
321
322    /// Whether a new operation must re-evaluate this step despite a matching revision.
323    fn refresh_each_operation(&self, step: &Step) -> bool {
324        matches!(
325            step.kind,
326            crate::engine::StepKind::Prepare | crate::engine::StepKind::HealthGate
327        )
328    }
329
330    /// Apply changed inputs to an existing resource. Providers must preserve
331    /// its ownership handle or explicitly replace and retire it in the journal.
332    async fn reconcile(
333        &self,
334        ctx: StepContext<'_>,
335        _previous: &Checkpoint,
336    ) -> Result<StepResource, SubstrateFault> {
337        self.execute(ctx).await
338    }
339
340    /// Re-check a recorded resource against reality.
341    async fn observe(
342        &self,
343        instance: &InstanceContext<'_>,
344        checkpoint: &Checkpoint,
345    ) -> Result<Observation, SubstrateFault>;
346
347    /// Destroy a recorded resource. Returning `Ok` is a claim the
348    /// engine immediately verifies with `observe` — silence is not
349    /// success (invariant 4).
350    async fn destroy(
351        &self,
352        instance: &InstanceContext<'_>,
353        checkpoint: &Checkpoint,
354    ) -> Result<(), SubstrateFault>;
355
356    /// Recover and destroy unfinished inventory without losing newly discovered handles.
357    async fn destroy_record(
358        &self,
359        _store: &crate::state::Store,
360        instance: &InstanceContext<'_>,
361        resource: &crate::state::ResourceRecord,
362    ) -> Result<(), SubstrateFault> {
363        self.destroy(instance, &resource.checkpoint(instance.name))
364            .await
365    }
366
367    async fn observe_record(
368        &self,
369        _store: &crate::state::Store,
370        instance: &InstanceContext<'_>,
371        resource: &crate::state::ResourceRecord,
372    ) -> Result<Observation, SubstrateFault> {
373        self.observe(instance, &resource.checkpoint(instance.name))
374            .await
375    }
376
377    /// Rebuild controller routes from verified runtime handles after restart.
378    async fn restore_routes(
379        &self,
380        _store: &crate::state::Store,
381        _instance: &InstanceContext<'_>,
382    ) -> Result<(), SubstrateFault> {
383        Ok(())
384    }
385
386    /// Substrate-wide cleanup after verified teardown (e.g. delete a
387    /// shared Stripe Projects environment).
388    async fn finalize_teardown(
389        &self,
390        _instance: &InstanceContext<'_>,
391    ) -> Result<(), SubstrateFault> {
392        Ok(())
393    }
394
395    /// Structured spend for `--json` envelopes (§4). Substrates that spend
396    /// nothing (local) return `None`.
397    async fn spend(&self) -> Option<SpendInfo> {
398        None
399    }
400
401    /// Human spend line after `up`/`down` (§4 — never silently nothing).
402    async fn spend_line(&self) -> Option<String> {
403        self.spend().await.map(|info| info.summary)
404    }
405
406    /// Recent logs for `services` (§2 — recent window, no streaming). `None`
407    /// means this substrate has no log facility (the daemon never saw the
408    /// processes and there is no remote log API); the CLI reports that rather
409    /// than inventing output.
410    async fn fetch_logs(
411        &self,
412        _store: &crate::state::Store,
413        _def: &StackDef,
414        _instance: &InstanceContext<'_>,
415        _services: &[String],
416        _tail: usize,
417    ) -> Result<Option<Vec<ServiceLog>>, SubstrateFault> {
418        Ok(None)
419    }
420}