Skip to main content

stackless_core/
routing.rs

1//! Dispatch by hosting placement. Resource ownership remains in the journal.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::time::Duration;
5
6use crate::capabilities::Capabilities;
7use crate::def::{DefError, Namespace, StackDef, placement::placement_key};
8use crate::engine::{Step, plan::ExecutionPlan};
9use crate::state::{Checkpoint, ResourceRecord, Store};
10use crate::substrate::{
11    InstanceContext, NamespacePurpose, Observation, ServiceLog, SpendInfo, StepContext,
12    StepResource, Substrate, SubstrateFault,
13};
14
15pub struct RoutedSubstrate {
16    default: String,
17    definition: StackDef,
18    store: Option<Store>,
19    providers: BTreeMap<String, Box<dyn Substrate>>,
20}
21
22impl std::fmt::Debug for RoutedSubstrate {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        f.debug_struct("RoutedSubstrate")
25            .field("default", &self.default)
26            .field("providers", &self.providers.keys().collect::<Vec<_>>())
27            .finish_non_exhaustive()
28    }
29}
30
31impl RoutedSubstrate {
32    /// Include adapters from both the desired definition and the retained journal.
33    /// Construction performs no provider operations.
34    pub fn new(
35        store: Option<Store>,
36        default: String,
37        mut definition: StackDef,
38        recorded: BTreeMap<String, String>,
39        providers: BTreeMap<String, Box<dyn Substrate>>,
40    ) -> Result<Self, SubstrateFault> {
41        let required: BTreeSet<_> = definition
42            .placements(&default)
43            .into_values()
44            .chain(recorded.values().cloned())
45            .chain(std::iter::once(default.clone()))
46            .collect();
47        for name in required {
48            if providers
49                .get(&name)
50                .is_none_or(|provider| provider.name() != name)
51            {
52                return Err(crate::capabilities::unsupported_feature(
53                    &name,
54                    "placement",
55                    "an unregistered hosting adapter",
56                ));
57            }
58        }
59        for workload in definition.services.values_mut() {
60            workload.on.get_or_insert_with(|| default.clone());
61        }
62        for resource in definition.integrations.values_mut() {
63            resource.on.get_or_insert_with(|| default.clone());
64        }
65        Ok(Self {
66            default,
67            definition,
68            store,
69            providers,
70        })
71    }
72
73    fn provider(&self, name: &str) -> &dyn Substrate {
74        // The constructor checks the complete routing domain.
75        self.providers[name].as_ref()
76    }
77
78    fn desired(&self, step: &Step) -> &dyn Substrate {
79        self.provider(self.definition.step_provider(&self.default, step))
80    }
81
82    fn recorded_provider(&self, owner: &str, step: &str) -> Result<&dyn Substrate, SubstrateFault> {
83        let placements = self
84            .store
85            .as_ref()
86            .ok_or_else(|| {
87                crate::capabilities::unsupported_feature(
88                    &self.default,
89                    step,
90                    "resource observation without a state journal",
91                )
92            })?
93            .placements(owner)
94            .map_err(|error| SubstrateFault::from_fault(&error))?;
95        let name = placement_key(step)
96            .and_then(|key| placements.get(&key))
97            .map(String::as_str)
98            .unwrap_or(&self.default);
99        self.providers.get(name).map(Box::as_ref).ok_or_else(|| {
100            crate::capabilities::unsupported_feature(
101                name,
102                step,
103                "an unregistered recorded hosting adapter",
104            )
105        })
106    }
107
108    fn origins(
109        &self,
110        instance: &InstanceContext<'_>,
111        prior: &[Checkpoint],
112        secrets: &BTreeMap<String, String>,
113        purpose: NamespacePurpose,
114    ) -> BTreeMap<String, String> {
115        let raw = InstanceContext {
116            routed_origins: None,
117            ..*instance
118        };
119        let mut origins = BTreeMap::new();
120        for (name, provider) in &self.providers {
121            let namespace =
122                provider.build_namespace(&self.definition, &raw, prior, secrets, purpose);
123            for (service, origin) in namespace.service_origins {
124                if self
125                    .definition
126                    .services
127                    .get(&service)
128                    .is_some_and(|spec| spec.on.as_deref() == Some(name))
129                    && !origin.is_empty()
130                {
131                    origins.insert(service, origin);
132                }
133            }
134        }
135        origins
136    }
137}
138
139#[async_trait::async_trait]
140impl Substrate for RoutedSubstrate {
141    fn name(&self) -> &str {
142        &self.default
143    }
144
145    fn capabilities(&self) -> Capabilities {
146        self.provider(&self.default).capabilities()
147    }
148
149    fn can_manage_resource(&self, resource: &ResourceRecord) -> bool {
150        self.recorded_provider(&resource.owner_id, &resource.step_id)
151            .is_ok_and(|provider| provider.can_manage_resource(resource))
152    }
153
154    fn execution_plan(&self, def: &StackDef) -> Result<ExecutionPlan, DefError> {
155        def.execution_plan_with_placement(&self.default, |name| {
156            self.providers
157                .get(name)
158                .is_some_and(|provider| provider.capabilities().early_origins)
159        })
160    }
161
162    fn validate(&self, def: &StackDef) -> Result<(), SubstrateFault> {
163        let mut requested = def.clone();
164        for workload in requested.services.values_mut() {
165            workload.on.get_or_insert_with(|| self.default.clone());
166        }
167        for resource in requested.integrations.values_mut() {
168            resource.on.get_or_insert_with(|| self.default.clone());
169        }
170        if crate::engine::revision::digest(&requested)?
171            != crate::engine::revision::digest(&self.definition)?
172        {
173            return Err(SubstrateFault::from_fault(
174                &crate::state::StateError::ResourceInvariant {
175                    detail: "routing adapter and requested definition differ".into(),
176                },
177            ));
178        }
179        let active: BTreeSet<_> = self
180            .definition
181            .placements(&self.default)
182            .into_values()
183            .collect();
184        for name in active {
185            let provider = self.provider(&name);
186            provider.capabilities().validate(&name, &self.definition)?;
187            provider.validate_definition(&self.definition)?;
188        }
189        self.execution_plan(&self.definition)
190            .map_err(|error| SubstrateFault::from_fault(&error))?;
191        Ok(())
192    }
193
194    fn validate_definition(&self, def: &StackDef) -> Result<(), SubstrateFault> {
195        self.validate(def)
196    }
197
198    fn supports_source_override(&self) -> bool {
199        self.provider(&self.default).supports_source_override()
200    }
201
202    fn supports_source_override_for(&self, def: &StackDef, service: &str) -> bool {
203        let name = def
204            .services
205            .get(service)
206            .and_then(|spec| spec.on.as_deref())
207            .unwrap_or(&self.default);
208        self.provider(name)
209            .supports_source_override_for(def, service)
210    }
211
212    fn default_lease(&self) -> Duration {
213        self.providers
214            .values()
215            .map(|provider| provider.default_lease())
216            .min()
217            .unwrap_or_default()
218    }
219
220    fn service_origin(
221        &self,
222        _def: &StackDef,
223        instance: &InstanceContext<'_>,
224        service: &str,
225    ) -> String {
226        self.origins(
227            instance,
228            instance.checkpoints,
229            &BTreeMap::new(),
230            NamespacePurpose::ServiceEnv,
231        )
232        .remove(service)
233        .unwrap_or_default()
234    }
235
236    fn build_namespace(
237        &self,
238        _def: &StackDef,
239        instance: &InstanceContext<'_>,
240        prior: &[Checkpoint],
241        secrets: &BTreeMap<String, String>,
242        purpose: NamespacePurpose,
243    ) -> Namespace {
244        let origins = self.origins(instance, prior, secrets, purpose);
245        let routed = InstanceContext {
246            routed_origins: Some(&origins),
247            ..*instance
248        };
249        let mut namespace = self.provider(&self.default).build_namespace(
250            &self.definition,
251            &routed,
252            prior,
253            secrets,
254            purpose,
255        );
256        routed.bind_namespace(&mut namespace, &self.definition);
257        namespace
258    }
259
260    async fn execute(&self, ctx: StepContext<'_>) -> Result<StepResource, SubstrateFault> {
261        let origins = self.origins(
262            ctx.instance,
263            ctx.prior,
264            &BTreeMap::new(),
265            NamespacePurpose::ServiceEnv,
266        );
267        let instance = InstanceContext {
268            routed_origins: Some(&origins),
269            ..*ctx.instance
270        };
271        self.desired(ctx.step)
272            .execute(StepContext {
273                instance: &instance,
274                def: &self.definition,
275                ..ctx
276            })
277            .await
278    }
279
280    fn step_revision(&self, ctx: &StepContext<'_>) -> Result<String, SubstrateFault> {
281        let origins = self.origins(
282            ctx.instance,
283            ctx.prior,
284            &BTreeMap::new(),
285            NamespacePurpose::ServiceEnv,
286        );
287        let instance = InstanceContext {
288            routed_origins: Some(&origins),
289            ..*ctx.instance
290        };
291        self.desired(ctx.step).step_revision(&StepContext {
292            operation_id: ctx.operation_id,
293            store: ctx.store,
294            instance: &instance,
295            def: &self.definition,
296            step: ctx.step,
297            source_overrides: ctx.source_overrides,
298            dirty: ctx.dirty,
299            prior: ctx.prior,
300            parent_resources: ctx.parent_resources,
301            cancelled: ctx.cancelled.clone(),
302        })
303    }
304
305    fn refresh_each_operation(&self, step: &Step) -> bool {
306        self.desired(step).refresh_each_operation(step)
307    }
308
309    async fn reconcile(
310        &self,
311        ctx: StepContext<'_>,
312        previous: &Checkpoint,
313    ) -> Result<StepResource, SubstrateFault> {
314        let origins = self.origins(
315            ctx.instance,
316            ctx.prior,
317            &BTreeMap::new(),
318            NamespacePurpose::ServiceEnv,
319        );
320        let instance = InstanceContext {
321            routed_origins: Some(&origins),
322            ..*ctx.instance
323        };
324        self.desired(ctx.step)
325            .reconcile(
326                StepContext {
327                    instance: &instance,
328                    def: &self.definition,
329                    ..ctx
330                },
331                previous,
332            )
333            .await
334    }
335
336    async fn observe(
337        &self,
338        instance: &InstanceContext<'_>,
339        checkpoint: &Checkpoint,
340    ) -> Result<Observation, SubstrateFault> {
341        self.recorded_provider(instance.id, &checkpoint.step_id)?
342            .observe(instance, checkpoint)
343            .await
344    }
345
346    async fn destroy(
347        &self,
348        instance: &InstanceContext<'_>,
349        checkpoint: &Checkpoint,
350    ) -> Result<(), SubstrateFault> {
351        self.recorded_provider(instance.id, &checkpoint.step_id)?
352            .destroy(instance, checkpoint)
353            .await
354    }
355
356    async fn destroy_record(
357        &self,
358        store: &Store,
359        instance: &InstanceContext<'_>,
360        resource: &ResourceRecord,
361    ) -> Result<(), SubstrateFault> {
362        self.recorded_provider(instance.id, &resource.step_id)?
363            .destroy_record(store, instance, resource)
364            .await
365    }
366
367    async fn observe_record(
368        &self,
369        store: &Store,
370        instance: &InstanceContext<'_>,
371        resource: &ResourceRecord,
372    ) -> Result<Observation, SubstrateFault> {
373        self.recorded_provider(instance.id, &resource.step_id)?
374            .observe_record(store, instance, resource)
375            .await
376    }
377
378    async fn restore_routes(
379        &self,
380        store: &Store,
381        instance: &InstanceContext<'_>,
382    ) -> Result<(), SubstrateFault> {
383        for provider in self.providers.values() {
384            provider.restore_routes(store, instance).await?;
385        }
386        Ok(())
387    }
388
389    async fn finalize_teardown(
390        &self,
391        instance: &InstanceContext<'_>,
392    ) -> Result<(), SubstrateFault> {
393        for provider in self.providers.values() {
394            provider.finalize_teardown(instance).await?;
395        }
396        Ok(())
397    }
398
399    async fn spend(&self) -> Option<SpendInfo> {
400        let mut entries = Vec::new();
401        for provider in self.providers.values() {
402            if let Some(info) = provider.spend().await {
403                entries.push(info);
404            }
405        }
406        match entries.len() {
407            0 => None,
408            1 => entries.pop(),
409            _ => Some(SpendInfo {
410                provider: "mixed".into(),
411                cap_usd: entries.iter().map(|entry| entry.cap_usd).sum(),
412                summary: entries
413                    .iter()
414                    .map(|entry| entry.summary.as_str())
415                    .collect::<Vec<_>>()
416                    .join("; "),
417                data: Some(serde_json::json!({ "providers": entries })),
418            }),
419        }
420    }
421
422    async fn fetch_logs(
423        &self,
424        store: &Store,
425        _def: &StackDef,
426        instance: &InstanceContext<'_>,
427        services: &[String],
428        tail: usize,
429    ) -> Result<Option<Vec<ServiceLog>>, SubstrateFault> {
430        let mut groups: BTreeMap<&str, Vec<String>> = BTreeMap::new();
431        for service in services {
432            let provider = self.recorded_provider(instance.id, &format!("start:{service}"))?;
433            groups
434                .entry(provider.name())
435                .or_default()
436                .push(service.clone());
437        }
438        let mut result = None;
439        let mut unavailable = Vec::new();
440        for (name, services) in groups {
441            if let Some(mut logs) = self
442                .provider(name)
443                .fetch_logs(store, &self.definition, instance, &services, tail)
444                .await?
445            {
446                result.get_or_insert_with(Vec::new).append(&mut logs);
447            } else {
448                unavailable.extend(services.into_iter().map(|service| ServiceLog {
449                    service,
450                    source: "unavailable",
451                    log_path: None,
452                    lines: Vec::new(),
453                }));
454            }
455        }
456        if let Some(logs) = &mut result {
457            logs.extend(unavailable);
458        }
459        Ok(result)
460    }
461}