1use 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#[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#[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
67pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum NamespacePurpose {
91 ServiceEnv,
93 OperatorPrepare,
95 Verify,
97}
98
99#[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#[derive(Debug, Clone)]
120pub struct ServiceLog {
121 pub service: String,
122 pub source: &'static str,
124 pub log_path: Option<String>,
126 pub lines: Vec<String>,
127}
128
129#[derive(Debug, Clone)]
132pub struct StepResource {
133 pub resource_kind: String,
134 pub resource_id: String,
135 pub payload: String,
137}
138
139#[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 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 pub fn resource_name(&self, logical_name: &str) -> String {
174 namespaced_resource_name(self.resource_namespace, logical_name)
175 }
176
177 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#[derive(Debug)]
203pub struct StepContext<'a> {
204 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 pub source_overrides: &'a BTreeMap<String, String>,
212 pub dirty: bool,
215 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 fn name(&self) -> &str;
234
235 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 fn validate_definition(&self, def: &StackDef) -> Result<(), SubstrateFault>;
278
279 fn supports_source_override(&self) -> bool;
282
283 fn default_lease(&self) -> Duration;
285
286 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 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 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 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 async fn reconcile(
333 &self,
334 ctx: StepContext<'_>,
335 _previous: &Checkpoint,
336 ) -> Result<StepResource, SubstrateFault> {
337 self.execute(ctx).await
338 }
339
340 async fn observe(
342 &self,
343 instance: &InstanceContext<'_>,
344 checkpoint: &Checkpoint,
345 ) -> Result<Observation, SubstrateFault>;
346
347 async fn destroy(
351 &self,
352 instance: &InstanceContext<'_>,
353 checkpoint: &Checkpoint,
354 ) -> Result<(), SubstrateFault>;
355
356 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 async fn restore_routes(
379 &self,
380 _store: &crate::state::Store,
381 _instance: &InstanceContext<'_>,
382 ) -> Result<(), SubstrateFault> {
383 Ok(())
384 }
385
386 async fn finalize_teardown(
389 &self,
390 _instance: &InstanceContext<'_>,
391 ) -> Result<(), SubstrateFault> {
392 Ok(())
393 }
394
395 async fn spend(&self) -> Option<SpendInfo> {
398 None
399 }
400
401 async fn spend_line(&self) -> Option<String> {
403 self.spend().await.map(|info| info.summary)
404 }
405
406 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}