Skip to main content

stackless_core/engine/
plan.rs

1//! Step planning: one validated definition + the derived graph → the
2//! ordered steps every substrate executes (§3/§4 share the sequence:
3//! provision integrations → prepare → start services → health gate).
4
5use serde::{Deserialize, Serialize};
6
7use crate::def::{DefError, DependencyGraph, Node, StackDef};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum StepKind {
12    /// Provision a hosted third-party integration (Clerk in v0).
13    ProvisionIntegration,
14    /// Materialize a service's source into instance-owned space.
15    Materialize,
16    /// The once-after-materialization hook.
17    Setup,
18    /// The every-up hook, after dependencies are ready.
19    Prepare,
20    /// Start (or deploy) the service.
21    Start,
22    /// Run a finite job and persist its exit status.
23    RunJob,
24    /// Gate on the service's health contract through its public origin.
25    HealthGate,
26}
27
28impl StepKind {
29    fn id_prefix(self) -> &'static str {
30        match self {
31            Self::ProvisionIntegration => "integration",
32            Self::Materialize => "materialize",
33            Self::Setup => "setup",
34            Self::Prepare => "prepare",
35            Self::Start => "start",
36            Self::HealthGate => "health",
37            Self::RunJob => "job",
38        }
39    }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct Step {
44    /// Stable id, the journal's primary key: `"{kind}:{node}"`.
45    pub id: String,
46    pub kind: StepKind,
47    /// The service name the step belongs to.
48    pub node: String,
49}
50
51impl Step {
52    fn new(kind: StepKind, node: &str) -> Self {
53        Self {
54            id: format!("{}:{node}", kind.id_prefix()),
55            kind,
56            node: node.to_owned(),
57        }
58    }
59}
60
61impl StackDef {
62    /// Expand the topological order into lifecycle steps.
63    pub fn plan(&self) -> Result<Vec<Step>, DefError> {
64        let graph = DependencyGraph::derive(self)?;
65        let mut steps = Vec::new();
66        for node in graph.startup_order() {
67            match node {
68                Node::Integration(name) => {
69                    steps.push(Step::new(StepKind::ProvisionIntegration, name));
70                }
71                Node::Service(name) => {
72                    let Some(service) = self.services.get(name) else {
73                        continue;
74                    };
75                    steps.push(Step::new(StepKind::Materialize, name));
76                    if service.setup.is_some() {
77                        steps.push(Step::new(StepKind::Setup, name));
78                    }
79                    if service.prepare.is_some() {
80                        steps.push(Step::new(StepKind::Prepare, name));
81                    }
82                    if service.kind == crate::def::WorkloadKind::Job {
83                        steps.push(Step::new(StepKind::RunJob, name));
84                    } else {
85                        steps.push(Step::new(StepKind::Start, name));
86                        steps.push(Step::new(StepKind::HealthGate, name));
87                    }
88                }
89            }
90        }
91        Ok(steps)
92    }
93}
94
95/// Dependencies are on output production or readiness, never on list position.
96#[derive(Debug, Clone, Serialize)]
97pub struct ExecutionPlan {
98    pub steps: Vec<Step>,
99    pub dependencies: std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
100}
101
102impl ExecutionPlan {
103    pub fn ancestors(&self, id: &str) -> std::collections::BTreeSet<String> {
104        let mut found = std::collections::BTreeSet::new();
105        let mut pending = vec![id.to_owned()];
106        while let Some(id) = pending.pop() {
107            if let Some(dependencies) = self.dependencies.get(&id) {
108                for dependency in dependencies {
109                    if found.insert(dependency.clone()) {
110                        pending.push(dependency.clone());
111                    }
112                }
113            }
114        }
115        found
116    }
117}
118
119impl StackDef {
120    pub fn execution_plan(
121        &self,
122        provider: &str,
123        early_origins: bool,
124    ) -> Result<ExecutionPlan, DefError> {
125        self.execution_plan_with_placement(provider, |_| early_origins)
126    }
127
128    /// URL availability is a property of the target's hosting provider.
129    pub fn execution_plan_with_placement(
130        &self,
131        provider: &str,
132        early_origins: impl Fn(&str) -> bool,
133    ) -> Result<ExecutionPlan, DefError> {
134        let early = |target: &str| {
135            if self.services.get(target).is_some_and(|workload| {
136                workload
137                    .health
138                    .as_ref()
139                    .is_some_and(|health| health.is_tcp())
140            }) {
141                return false;
142            }
143            let provider = self
144                .services
145                .get(target)
146                .and_then(|workload| workload.on.as_deref())
147                .unwrap_or(provider);
148            early_origins(provider)
149        };
150        use crate::def::{DependencyCondition, WorkloadKind, interp::Reference};
151        use std::collections::{BTreeMap, BTreeSet};
152        let steps = self.plan()?;
153        let mut dependencies: BTreeMap<String, BTreeSet<String>> = steps
154            .iter()
155            .map(|step| (step.id.clone(), BTreeSet::new()))
156            .collect();
157        for (name, service) in &self.services {
158            let chain: Vec<_> = steps
159                .iter()
160                .filter(|step| step.node == *name && step.kind != StepKind::ProvisionIntegration)
161                .collect();
162            for pair in chain.windows(2) {
163                dependencies
164                    .entry(pair[1].id.clone())
165                    .or_default()
166                    .insert(pair[0].id.clone());
167            }
168            let consumer = chain
169                .iter()
170                .find(|step| step.kind != StepKind::Materialize)
171                .map(|step| step.id.clone());
172            let Some(consumer) = consumer else {
173                continue;
174            };
175            let inputs = dependencies.entry(consumer).or_default();
176            for (target, condition) in &service.depends_on {
177                let prefix = match condition {
178                    DependencyCondition::Started => "start",
179                    DependencyCondition::Ready => "health",
180                    DependencyCondition::Completed => "job",
181                };
182                inputs.insert(format!("{prefix}:{target}"));
183            }
184            let env = service.effective_env(name, service.on.as_deref().unwrap_or(provider))?;
185            for value in env.values() {
186                for reference in
187                    crate::def::interp::references(value, &format!("services.{name}.env"))?
188                {
189                    match reference {
190                        Reference::IntegrationOutput { integration, .. } => {
191                            inputs.insert(format!("integration:{integration}"));
192                        }
193                        Reference::ServiceOrigin(target) if !early(&target) => {
194                            inputs.insert(format!("start:{target}"));
195                        }
196                        Reference::EndpointUrl(endpoint) => {
197                            if let Some(endpoint) = self.endpoints.get(&endpoint)
198                                && endpoint.url.is_none()
199                                && !early(&endpoint.workload)
200                            {
201                                inputs.insert(format!("start:{}", endpoint.workload));
202                            }
203                        }
204                        _ => {}
205                    }
206                }
207            }
208            if service.kind == WorkloadKind::Job && inputs.contains(&format!("job:{name}")) {
209                return Err(DefError::WiringCycle {
210                    nodes: name.clone(),
211                });
212            }
213        }
214        let mut remaining = dependencies.clone();
215        let mut ordered = Vec::new();
216        while !remaining.is_empty() {
217            let next = remaining
218                .iter()
219                .find(|(_, deps)| deps.is_empty())
220                .map(|(id, _)| id.clone())
221                .ok_or_else(|| DefError::WiringCycle {
222                    nodes: remaining.keys().cloned().collect::<Vec<_>>().join(", "),
223                })?;
224            remaining.remove(&next);
225            for edges in remaining.values_mut() {
226                edges.remove(&next);
227            }
228            if let Some(step) = steps.iter().find(|step| step.id == next) {
229                ordered.push(step.clone());
230            }
231        }
232        Ok(ExecutionPlan {
233            steps: ordered,
234            dependencies,
235        })
236    }
237}
238
239impl StepKind {
240    /// Schedule starts before health waits so independent services can boot.
241    pub fn priority(self) -> u8 {
242        match self {
243            Self::Materialize => 0,
244            Self::ProvisionIntegration => 1,
245            Self::Setup => 2,
246            Self::Prepare => 3,
247            Self::RunJob => 4,
248            Self::Start => 5,
249            Self::HealthGate => 6,
250        }
251    }
252}