Skip to main content

stackless_core/def/
interp.rs

1//! The interpolation namespace (ARCHITECTURE.md §1).
2//!
3//! Env values reference a namespace evaluated per instance per
4//! substrate. `$PORT` is deliberately *not* an interpolation reference —
5//! it is injected by the local substrate into `run` commands only, so
6//! the tokenizer here only understands `${...}` forms.
7
8use std::collections::BTreeMap;
9
10use super::error::DefError;
11use crate::types::DnsName;
12
13/// A parsed `${...}` reference.
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
15pub enum Reference {
16    /// `${stack.name}`
17    StackName,
18    /// `${instance.name}`
19    InstanceName,
20    /// `${services.X.origin}`
21    ServiceOrigin(String),
22    /// `${endpoints.X.url}`
23    EndpointUrl(String),
24    /// `${datastores.X.url}` — legacy first-class datastore wiring kept
25    /// so instance snapshots can still resolve URLs from journaled
26    /// provision checkpoints after the section was removed from the schema.
27    DatastoreUrl(String),
28    /// `${secrets.KEY}`
29    Secret(String),
30    /// `${integrations.X.output}`
31    IntegrationOutput { integration: String, output: String },
32}
33
34/// Extract every `${...}` reference from a value.
35pub fn references(value: &str, location: &str) -> Result<Vec<Reference>, DefError> {
36    Reference::collect_in(value, location)
37}
38
39impl Reference {
40    /// Extract every `${...}` reference from a value.
41    ///
42    /// `location` names where the value lives (e.g. `services.api.env.DATABASE_URL`)
43    /// so errors point at the right line of the definition.
44    pub fn collect_in(value: &str, location: &str) -> Result<Vec<Self>, DefError> {
45        let mut refs = Vec::new();
46        let mut rest = value;
47        while let Some(start) = rest.find("${") {
48            let after = &rest[start + 2..];
49            let Some(end) = after.find('}') else {
50                return Err(DefError::ReferenceSyntax {
51                    location: location.to_owned(),
52                    reference: rest[start..].to_owned(),
53                    detail: "unterminated ${...}".into(),
54                });
55            };
56            refs.push(Self::parse(&after[..end], location)?);
57            rest = &after[end + 1..];
58        }
59        Ok(refs)
60    }
61
62    fn parse(inner: &str, location: &str) -> Result<Self, DefError> {
63        Self::parse_reference(inner, location)
64    }
65
66    fn parse_reference(inner: &str, location: &str) -> Result<Self, DefError> {
67        let parts: Vec<&str> = inner.split('.').collect();
68        let reference = match parts.as_slice() {
69            ["instance", "name"] => Reference::InstanceName,
70            ["stack", "name"] => Reference::StackName,
71            ["services", name, "origin"] => Reference::ServiceOrigin((*name).to_owned()),
72            ["endpoints", name, "url"] => Reference::EndpointUrl((*name).to_owned()),
73            ["datastores", name, "url"] => Reference::DatastoreUrl((*name).to_owned()),
74            ["secrets", key] => Reference::Secret((*key).to_owned()),
75            ["integrations", name, output] => Reference::IntegrationOutput {
76                integration: (*name).to_owned(),
77                output: (*output).to_owned(),
78            },
79            _ => {
80                return Err(DefError::ReferenceSyntax {
81                    location: location.to_owned(),
82                    reference: format!("${{{inner}}}"),
83                    detail: "not a recognized namespace form".into(),
84                });
85            }
86        };
87        Ok(reference)
88    }
89}
90
91/// The values a substrate supplies for one instance. Built per instance
92/// per substrate; resolution itself is substrate-blind.
93#[derive(Debug)]
94pub struct Namespace {
95    pub stack_name: DnsName,
96    pub instance_name: DnsName,
97    pub service_origins: BTreeMap<String, String>,
98    pub endpoint_urls: BTreeMap<String, String>,
99    /// Legacy `${datastores.X.url}` values reconstructed from journaled
100    /// `provision:` checkpoints (local container / render-postgres).
101    pub datastore_urls: BTreeMap<String, String>,
102    pub secrets: BTreeMap<String, String>,
103    pub integrations: BTreeMap<String, BTreeMap<String, String>>,
104}
105
106impl Default for Namespace {
107    fn default() -> Self {
108        Self {
109            stack_name: DnsName::from_stored("stack"),
110            instance_name: DnsName::from_stored("instance"),
111            service_origins: BTreeMap::new(),
112            endpoint_urls: BTreeMap::new(),
113            datastore_urls: BTreeMap::new(),
114            secrets: BTreeMap::new(),
115            integrations: BTreeMap::new(),
116        }
117    }
118}
119
120impl Namespace {
121    /// Bind named URLs without replacing the provider's service origins.
122    /// Rebind after changing origins, such as for a container's private network.
123    pub fn bind_endpoints(&mut self, def: &super::StackDef) {
124        self.endpoint_urls = def
125            .resolve_endpoints(&self.service_origins)
126            .into_iter()
127            .map(|(name, endpoint)| (name, endpoint.url))
128            .collect();
129    }
130
131    fn lookup(&self, reference: &Reference, location: &str) -> Result<String, DefError> {
132        match reference {
133            Reference::StackName => Ok(self.stack_name.as_str().to_owned()),
134            Reference::InstanceName => Ok(self.instance_name.as_str().to_owned()),
135            Reference::ServiceOrigin(name) => {
136                self.service_origins.get(name).cloned().ok_or_else(|| {
137                    DefError::UndeclaredReference {
138                        location: location.to_owned(),
139                        kind: "service",
140                        name: name.clone(),
141                    }
142                })
143            }
144            Reference::EndpointUrl(name) => {
145                self.endpoint_urls
146                    .get(name)
147                    .cloned()
148                    .ok_or_else(|| DefError::EndpointUnavailable {
149                        location: location.to_owned(),
150                        name: name.clone(),
151                    })
152            }
153            Reference::DatastoreUrl(name) => {
154                self.datastore_urls.get(name).cloned().ok_or_else(|| {
155                    DefError::UndeclaredReference {
156                        location: location.to_owned(),
157                        kind: "datastore",
158                        name: name.clone(),
159                    }
160                })
161            }
162            Reference::Secret(key) => {
163                self.secrets
164                    .get(key)
165                    .cloned()
166                    .ok_or_else(|| DefError::UndeclaredReference {
167                        location: location.to_owned(),
168                        kind: "secret",
169                        name: key.clone(),
170                    })
171            }
172            Reference::IntegrationOutput {
173                integration,
174                output,
175            } => self
176                .integrations
177                .get(integration)
178                .and_then(|outputs| outputs.get(output))
179                .cloned()
180                .ok_or_else(|| DefError::UndeclaredReference {
181                    location: location.to_owned(),
182                    kind: "integration output",
183                    name: format!("{integration}.{output}"),
184                }),
185        }
186    }
187
188    /// Load integration output checkpoints into the interpolation namespace.
189    ///
190    /// Payload shape is provider-agnostic:
191    /// `{ "outputs": { "secret_key": "...", "publishable_key": "..." } }`.
192    pub fn add_integration_checkpoints(&mut self, checkpoints: &[crate::state::Checkpoint]) {
193        for checkpoint in checkpoints {
194            let Some(name) = checkpoint.step_id.strip_prefix("integration:") else {
195                continue;
196            };
197            let Ok(payload) = serde_json::from_str::<serde_json::Value>(&checkpoint.payload) else {
198                continue;
199            };
200            let Some(outputs) = payload.get("outputs").and_then(|value| value.as_object()) else {
201                continue;
202            };
203            let entry = self.integrations.entry(name.to_owned()).or_default();
204            for (key, value) in outputs {
205                if let Some(value) = value.as_str() {
206                    entry.insert(key.clone(), value.to_owned());
207                }
208            }
209        }
210    }
211
212    pub fn integration_outputs_from_checkpoints(
213        checkpoints: &[crate::state::Checkpoint],
214    ) -> BTreeMap<String, BTreeMap<String, String>> {
215        let mut ns = Self::default();
216        ns.add_integration_checkpoints(checkpoints);
217        ns.integrations
218    }
219
220    /// Reconstruct legacy `${datastores.X.url}` values from journaled
221    /// `provision:` checkpoints.
222    ///
223    /// Local checkpoints store a single `url`. Render checkpoints store
224    /// `internal_url` / `external_url`; `prefer_external` selects which
225    /// (service env → internal, operator prepare / verify → external).
226    pub fn add_datastore_checkpoints(
227        &mut self,
228        checkpoints: &[crate::state::Checkpoint],
229        prefer_external: bool,
230    ) {
231        for checkpoint in checkpoints {
232            let Some(name) = checkpoint.step_id.strip_prefix("provision:") else {
233                continue;
234            };
235            let Ok(payload) = serde_json::from_str::<serde_json::Value>(&checkpoint.payload) else {
236                continue;
237            };
238            let url = payload
239                .get("url")
240                .and_then(|value| value.as_str())
241                .or_else(|| {
242                    let primary = if prefer_external {
243                        "external_url"
244                    } else {
245                        "internal_url"
246                    };
247                    let fallback = if prefer_external {
248                        "internal_url"
249                    } else {
250                        "external_url"
251                    };
252                    payload
253                        .get(primary)
254                        .and_then(|value| value.as_str())
255                        .or_else(|| payload.get(fallback).and_then(|value| value.as_str()))
256                });
257            if let Some(url) = url {
258                self.datastore_urls.insert(name.to_owned(), url.to_owned());
259            }
260        }
261    }
262
263    /// Substitute every `${...}` in `value` from this namespace.
264    pub fn resolve(&self, value: &str, location: &str) -> Result<String, DefError> {
265        let mut out = String::with_capacity(value.len());
266        let mut rest = value;
267        while let Some(start) = rest.find("${") {
268            out.push_str(&rest[..start]);
269            let after = &rest[start + 2..];
270            let Some(end) = after.find('}') else {
271                return Err(DefError::ReferenceSyntax {
272                    location: location.to_owned(),
273                    reference: rest[start..].to_owned(),
274                    detail: "unterminated ${...}".into(),
275                });
276            };
277            let reference = Reference::parse_reference(&after[..end], location)?;
278            out.push_str(&self.lookup(&reference, location)?);
279            rest = &after[end + 1..];
280        }
281        out.push_str(rest);
282        Ok(out)
283    }
284}
285
286/// Substitute every `${...}` in `value` from the namespace.
287pub fn resolve(value: &str, namespace: &Namespace, location: &str) -> Result<String, DefError> {
288    namespace.resolve(value, location)
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn tokenizes_all_namespace_forms() {
297        let refs = references(
298            "${stack.name} ${instance.name} ${services.web.origin} ${datastores.db.url} ${secrets.KEY} ${integrations.clerk.secret_key}",
299            "test",
300        )
301        .unwrap();
302        assert_eq!(
303            refs,
304            vec![
305                Reference::StackName,
306                Reference::InstanceName,
307                Reference::ServiceOrigin("web".into()),
308                Reference::DatastoreUrl("db".into()),
309                Reference::Secret("KEY".into()),
310                Reference::IntegrationOutput {
311                    integration: "clerk".into(),
312                    output: "secret_key".into(),
313                },
314            ]
315        );
316    }
317
318    #[test]
319    fn port_is_not_a_reference() {
320        assert!(references("vite --port $PORT", "test").unwrap().is_empty());
321    }
322
323    #[test]
324    fn unterminated_reference_fails() {
325        assert!(references("${services.web.origin", "test").is_err());
326    }
327
328    #[test]
329    fn unknown_form_fails() {
330        assert!(references("${services.web.port}", "test").is_err());
331    }
332
333    #[test]
334    fn resolves_mixed_text() {
335        let mut namespace = Namespace {
336            stack_name: DnsName::try_new("atto").unwrap(),
337            instance_name: DnsName::try_new("demo").unwrap(),
338            ..Namespace::default()
339        };
340        namespace
341            .service_origins
342            .insert("web".into(), "http://web.demo.localhost:4444".into());
343        let resolved = resolve(
344            "origin=${services.web.origin};i=${instance.name}",
345            &namespace,
346            "t",
347        )
348        .unwrap();
349        assert_eq!(resolved, "origin=http://web.demo.localhost:4444;i=demo");
350    }
351}