lightshuttle-manifest 0.5.0

Manifest types, parser, and JSON Schema for LightShuttle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Substitution engine for `${...}` interpolations in manifest string values.
//!
//! Two reference schemes are supported:
//!
//! - `${env.NAME}`: substituted with the value of the environment variable
//!   `NAME`. The form `${env.NAME:-default}` uses `default` when `NAME` is
//!   unset or empty.
//! - `${resources.name.property}`: substituted with a runtime property of
//!   the named resource (e.g. `host`, `port`, `password`). Properties are
//!   injected by the runtime layer, not by this crate.
//!
//! The escape form `${{ ... }}` emits a literal `${ ... }` without
//! triggering substitution.
//!
//! # Usage
//!
//! Build an [`InterpolationContext`] with the available values, then create
//! an [`Interpolator`] to resolve or scan individual strings.
//!
//! ```rust
//! use lightshuttle_manifest::interpolate::{InterpolationContext, Interpolator};
//!
//! let ctx = InterpolationContext::new()
//!     .with_env([("PORT".to_string(), "8080".to_string())]);
//! let interpolator = Interpolator::new(&ctx);
//! let result = interpolator.resolve("http://localhost:${env.PORT}").unwrap();
//! assert_eq!(result, "http://localhost:8080");
//! ```

use std::collections::HashMap;
use std::iter::Peekable;
use std::str::Chars;

use indexmap::IndexMap;

use crate::error::{ManifestError, Result};

/// Maximum nesting depth accepted for `${...}` interpolations. A top-level
/// reference is depth 1; a reference inside an `env` default is depth 2; and
/// so on. Opening a reference beyond this depth raises
/// [`ManifestError::InterpolationTooDeep`].
pub const MAX_INTERPOLATION_DEPTH: usize = 10;

/// Runtime context that backs an [`Interpolator`].
///
/// Holds the set of environment variables and the runtime-resolved properties
/// of each resource (host, port, password, etc.). The context is immutable
/// once built; the builder methods consume `self` and return a new value.
///
/// # Building a context
///
/// ```rust
/// use lightshuttle_manifest::interpolate::InterpolationContext;
/// use indexmap::IndexMap;
///
/// let mut props = IndexMap::new();
/// props.insert("host".to_string(), "127.0.0.1".to_string());
/// props.insert("port".to_string(), "5432".to_string());
///
/// let ctx = InterpolationContext::new()
///     .with_env([("DB_NAME".to_string(), "mydb".to_string())])
///     .with_resource("db", props);
/// ```
#[derive(Debug, Default, Clone)]
pub struct InterpolationContext {
    env: HashMap<String, String>,
    resources: HashMap<String, IndexMap<String, String>>,
}

impl InterpolationContext {
    /// Create an empty context with no environment variables and no resources.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a context pre-populated with the current process environment.
    ///
    /// Equivalent to calling `new()` followed by
    /// `with_env(std::env::vars())`.
    #[must_use]
    pub fn from_env() -> Self {
        Self {
            env: std::env::vars().collect(),
            resources: HashMap::new(),
        }
    }

    /// Add or override a batch of environment variables.
    ///
    /// Later calls to `with_env` for the same key win; the last value set
    /// is the one used during resolution.
    #[must_use]
    pub fn with_env<I>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (String, String)>,
    {
        self.env.extend(vars);
        self
    }

    /// Register (or replace) the runtime-resolved properties for a named
    /// resource.
    ///
    /// `name` must match the resource key as declared in the manifest.
    /// The `properties` map is keyed by property name (e.g. `"host"`,
    /// `"port"`, `"password"`).
    #[must_use]
    pub fn with_resource(
        mut self,
        name: impl Into<String>,
        properties: IndexMap<String, String>,
    ) -> Self {
        self.resources.insert(name.into(), properties);
        self
    }
}

/// Parsed form of a `${...}` interpolation reference.
///
/// Produced by the internal parser and used by [`Interpolator::resolve`] and
/// [`Interpolator::scan`]. Consumers of the crate can inspect the scanned
/// references to build static dependency maps without performing actual
/// value resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reference {
    /// A `${resources.<name>.<property>}` reference.
    ///
    /// Resolved against the properties registered for the named resource in
    /// the [`InterpolationContext`].
    Resource {
        /// Name of the target resource as declared in the manifest.
        name: String,
        /// Property key on that resource (e.g. `"host"`, `"port"`).
        property: String,
    },

    /// A `${env.<NAME>}` or `${env.<NAME>:-<default>}` reference.
    ///
    /// Resolved against the environment variables in the
    /// [`InterpolationContext`]. When `default` is `Some`, it is used as
    /// a fallback when the variable is unset or empty.
    Env {
        /// Environment variable name.
        name: String,
        /// Optional fallback value used when `name` is unset or empty.
        default: Option<String>,
    },
}

impl Reference {
    /// Returns the target resource name when this is a
    /// [`Reference::Resource`], or `None` for an environment reference.
    ///
    /// Used to derive implicit dependencies: a `${resources.<name>.*}`
    /// interpolation makes the enclosing resource depend on `<name>`.
    #[must_use]
    pub fn resource_name(self) -> Option<String> {
        match self {
            Self::Resource { name, .. } => Some(name),
            Self::Env { .. } => None,
        }
    }
}

/// Interpolation engine bound to an [`InterpolationContext`].
///
/// Create one with [`Interpolator::new`], then call [`Interpolator::resolve`]
/// to substitute references in a string, or [`Interpolator::scan`] to
/// enumerate references without substituting them.
pub struct Interpolator<'ctx> {
    ctx: &'ctx InterpolationContext,
}

impl<'ctx> Interpolator<'ctx> {
    /// Create an interpolator that resolves references against `ctx`.
    #[must_use]
    pub fn new(ctx: &'ctx InterpolationContext) -> Self {
        Self { ctx }
    }

    /// Resolve all `${...}` references in `input` and return the resulting
    /// string.
    ///
    /// Literal braces can be escaped with `${{ ... }}`, which emits
    /// `${ ... }` verbatim. Any unknown scheme or unresolvable reference
    /// returns a [`ManifestError`].
    ///
    /// ```rust
    /// use lightshuttle_manifest::interpolate::{InterpolationContext, Interpolator};
    ///
    /// let ctx = InterpolationContext::new()
    ///     .with_env([("HOST".to_string(), "localhost".to_string())]);
    /// let interpolator = Interpolator::new(&ctx);
    ///
    /// let out = interpolator.resolve("connect to ${env.HOST}").unwrap();
    /// assert_eq!(out, "connect to localhost");
    /// ```
    pub fn resolve(&self, input: &str) -> Result<String> {
        self.resolve_at(input, 1)
    }

    fn resolve_at(&self, input: &str, depth: usize) -> Result<String> {
        let mut output = String::with_capacity(input.len());
        let mut chars = input.chars().peekable();

        while let Some(c) = chars.next() {
            if c != '$' {
                output.push(c);
                continue;
            }

            if chars.peek() != Some(&'{') {
                output.push('$');
                continue;
            }
            chars.next();

            // Escape form `${{ ... }}`
            if chars.peek() == Some(&'{') {
                chars.next();
                let body = consume_until_double_close(&mut chars, input)?;
                output.push('$');
                output.push('{');
                output.push_str(&body);
                output.push('}');
                continue;
            }

            let body = consume_balanced_body(&mut chars, input, depth)?;
            let reference = parse_reference(&body)?;
            let resolved = match &reference {
                Reference::Env {
                    name,
                    default: Some(raw_default),
                } => {
                    if let Some(value) = self.ctx.env.get(name).filter(|v| !v.is_empty()) {
                        value.clone()
                    } else {
                        self.resolve_at(raw_default, depth + 1)?
                    }
                }
                _ => self.lookup(&reference)?,
            };
            output.push_str(&resolved);
        }

        Ok(output)
    }

    /// Scan `input` and return every [`Reference`] it contains without
    /// resolving values.
    ///
    /// Useful for static analysis: the validation pass calls `scan` to
    /// verify that every `${resources.name.property}` expression refers
    /// to a resource that exists in the manifest, before any container
    /// is started.
    ///
    /// Returns a [`ManifestError`] if the interpolation syntax is invalid
    /// (e.g. unterminated `${`).
    pub fn scan(&self, input: &str) -> Result<Vec<Reference>> {
        let mut refs = Vec::new();
        scan_at(input, 1, &mut refs)?;
        Ok(refs)
    }

    fn lookup(&self, reference: &Reference) -> Result<String> {
        match reference {
            Reference::Resource { name, property } => {
                let resource = self
                    .ctx
                    .resources
                    .get(name)
                    .ok_or_else(|| ManifestError::UnknownResource(name.clone()))?;
                let value =
                    resource
                        .get(property)
                        .ok_or_else(|| ManifestError::UnknownProperty {
                            resource: name.clone(),
                            property: property.clone(),
                            kind: "<runtime>",
                        })?;
                Ok(value.clone())
            }
            Reference::Env { name, default } => {
                if let Some(value) = self.ctx.env.get(name).filter(|v| !v.is_empty()) {
                    Ok(value.clone())
                } else if let Some(fallback) = default {
                    Ok(fallback.clone())
                } else {
                    Err(ManifestError::EnvUnset(name.clone()))
                }
            }
        }
    }
}

/// Consume a brace-balanced `${...}` body, the opening `${` already consumed.
///
/// Nested `${` sequences are counted so the outer reference's body is returned
/// intact (e.g. `env.X:-${env.Y}` for `${env.X:-${env.Y}}`). `depth` is the
/// nesting level of the reference being consumed (1 at the top level); opening
/// a nested reference beyond [`MAX_INTERPOLATION_DEPTH`] raises
/// [`ManifestError::InterpolationTooDeep`].
fn consume_balanced_body(
    chars: &mut Peekable<Chars<'_>>,
    full: &str,
    depth: usize,
) -> Result<String> {
    let mut body = String::new();
    let mut nesting = 1usize;

    while let Some(c) = chars.next() {
        if c == '$' && chars.peek() == Some(&'{') {
            chars.next();
            nesting += 1;
            if depth + (nesting - 1) > MAX_INTERPOLATION_DEPTH {
                return Err(ManifestError::InterpolationTooDeep {
                    limit: MAX_INTERPOLATION_DEPTH,
                    context: full.to_owned(),
                });
            }
            body.push('$');
            body.push('{');
        } else if c == '}' {
            nesting -= 1;
            if nesting == 0 {
                return Ok(body);
            }
            body.push('}');
        } else {
            body.push(c);
        }
    }

    Err(ManifestError::InvalidInterpolation(format!(
        "unterminated `${{` in `{full}`"
    )))
}

fn consume_until_double_close(chars: &mut Peekable<Chars<'_>>, full: &str) -> Result<String> {
    let mut body = String::new();
    while let Some(c) = chars.next() {
        if c == '}' && chars.peek() == Some(&'}') {
            chars.next();
            return Ok(body);
        }
        body.push(c);
    }
    Err(ManifestError::InvalidInterpolation(format!(
        "unterminated `${{{{` in `{full}`"
    )))
}

/// Scan `input` for `${...}` references at nesting `depth`, appending each
/// found [`Reference`] to `out` in order and descending into `env` defaults
/// so nested references surface too.
fn scan_at(input: &str, depth: usize, out: &mut Vec<Reference>) -> Result<()> {
    let mut chars = input.chars().peekable();

    while let Some(c) = chars.next() {
        if c != '$' || chars.peek() != Some(&'{') {
            continue;
        }
        chars.next();

        if chars.peek() == Some(&'{') {
            chars.next();
            consume_until_double_close(&mut chars, input)?;
            continue;
        }

        let body = consume_balanced_body(&mut chars, input, depth)?;
        let reference = parse_reference(&body)?;
        if let Reference::Env {
            default: Some(raw_default),
            ..
        } = &reference
        {
            scan_at(raw_default, depth + 1, out)?;
        }
        out.push(reference);
    }

    Ok(())
}

fn parse_reference(body: &str) -> Result<Reference> {
    if let Some(rest) = body.strip_prefix("resources.") {
        let (name, property) = rest.split_once('.').ok_or_else(|| {
            ManifestError::InvalidInterpolation(format!(
                "resource reference missing property in `${{{body}}}`"
            ))
        })?;
        if name.is_empty() || property.is_empty() {
            return Err(ManifestError::InvalidInterpolation(format!(
                "empty resource reference in `${{{body}}}`"
            )));
        }
        if name.contains("${") || property.contains("${") {
            return Err(ManifestError::InvalidInterpolation(format!(
                "nested interpolation is only allowed in an env default, not in `${{{body}}}`"
            )));
        }
        Ok(Reference::Resource {
            name: name.to_owned(),
            property: property.to_owned(),
        })
    } else if let Some(rest) = body.strip_prefix("env.") {
        if let Some((name, default)) = rest.split_once(":-") {
            if name.contains("${") {
                return Err(ManifestError::InvalidInterpolation(format!(
                    "nested interpolation is only allowed in an env default, not in the variable name of `${{{body}}}`"
                )));
            }
            Ok(Reference::Env {
                name: name.to_owned(),
                default: Some(default.to_owned()),
            })
        } else {
            if rest.contains("${") {
                return Err(ManifestError::InvalidInterpolation(format!(
                    "nested interpolation is only allowed in an env default, not in `${{{body}}}`"
                )));
            }
            Ok(Reference::Env {
                name: rest.to_owned(),
                default: None,
            })
        }
    } else {
        Err(ManifestError::InvalidInterpolation(format!(
            "unknown reference scheme in `${{{body}}}`"
        )))
    }
}