lightshuttle-export 0.5.0

Manifest to deployment artifact transpilation 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Helm emitter: renders an [`ExportModel`] into a chart with a
//! `Chart.yaml`, a `values.yaml` and one template per resource.
//!
//! Two engines live here. `Chart.yaml` and `values.yaml` are real data,
//! so they are typed structs serialised with `serde_norway`. The
//! `templates/*.yaml` files are Go templates: their `{{ ... }}`
//! directives are literals, written as text, while the structural parts
//! (ports, probes, volumes) are derived from the resolved spec.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::time::Duration;

use lightshuttle_manifest::ImagePullPolicy;
use lightshuttle_spec::{ContainerSpec, HealthcheckSpec, ImageSource, VolumeSource};
use serde::Serialize;

use crate::emit::Emitter;
use crate::error::Result;
use crate::model::{ExportModel, ExportProject, Target};
use crate::resolve::{
    SECRET_MARKERS, chart_name_for, chart_version_for, dns_name, enabled_for,
    image_pull_policy_for, namespace_for, replicas_for,
};

/// Emits a Helm chart from the export model.
///
/// The produced artifact set contains:
///
/// - `Chart.yaml`: chart name and version derived from the project metadata or
///   `export.helm` overrides via [`crate::resolve::chart_name_for`] and
///   [`crate::resolve::chart_version_for`].
/// - `values.yaml`: namespace, per-service replica count, image coordinates,
///   and environment variables split into `env` (plain) and `secrets`
///   (placeholders only, never real values).
/// - `templates/<name>.yaml`: one multi-document Go-template file per enabled
///   resource, containing a `Deployment`, optionally a `Service`,
///   a `ConfigMap`, a `Secret`, and `PersistentVolumeClaim` entries.
///
/// # Example
///
/// ```rust,no_run
/// use lightshuttle_export::{lower, HelmEmitter, Emitter};
/// use lightshuttle_manifest::Manifest;
///
/// # fn main() -> lightshuttle_export::Result<()> {
/// let manifest: Manifest = todo!("parse from YAML");
/// let model = lower(&manifest)?;
/// let artifacts = HelmEmitter.emit(&model)?;
/// for file in &artifacts.files {
///     println!("{}", file.path.display());
/// }
/// // Prints: Chart.yaml, values.yaml, templates/<name>.yaml ...
/// # Ok(())
/// # }
/// ```
pub struct HelmEmitter;

impl Emitter for HelmEmitter {
    fn target(&self) -> Target {
        Target::Helm
    }

    fn emit(&self, model: &ExportModel) -> Result<crate::ExportArtifacts> {
        let export = model.export.as_ref();
        let mut artifacts = crate::ExportArtifacts::new();

        artifacts.push("Chart.yaml", chart_yaml(&model.project, export)?);
        artifacts.push("values.yaml", values_yaml(model)?);

        for service in &model.services {
            if !enabled_for(Target::Helm, &service.spec.resource, export) {
                continue;
            }
            let name = dns_name(&service.spec.resource);
            artifacts.push(
                format!("templates/{name}.yaml"),
                resource_template(&service.spec, &name),
            );
        }

        Ok(artifacts)
    }
}

fn chart_yaml(
    project: &ExportProject,
    export: Option<&lightshuttle_manifest::ExportConfig>,
) -> Result<String> {
    let chart = Chart {
        api_version: "v2",
        name: dns_name(&chart_name_for(&project.name, export)),
        version: chart_version_for(project.version.as_deref(), export),
        description: format!("Helm chart for {} generated by LightShuttle", project.name),
    };
    to_yaml(&chart)
}

fn values_yaml(model: &ExportModel) -> Result<String> {
    let export = model.export.as_ref();
    let namespace = namespace_for(&model.project.name, export);

    let mut services: BTreeMap<String, ServiceValues> = BTreeMap::new();
    for service in &model.services {
        if !enabled_for(Target::Helm, &service.spec.resource, export) {
            continue;
        }
        let name = dns_name(&service.spec.resource);
        let (env, secrets) = split_env(&service.spec.env);
        let (repository, tag) = split_image(&service.spec.image);
        services.insert(
            name,
            ServiceValues {
                replicas: replicas_for(Target::Helm, &service.spec.resource, export),
                image: ImageValues {
                    repository,
                    tag,
                    pull_policy: pull_policy_str(image_pull_policy_for(
                        &service.spec.resource,
                        export,
                    ))
                    .to_owned(),
                },
                env,
                secrets,
            },
        );
    }

    to_yaml(&Values {
        namespace,
        services,
    })
}

/// Build the multi-document template for one resource.
fn resource_template(spec: &ContainerSpec, name: &str) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "{{{{- $svc := index .Values.services {name:?} -}}}}");
    out.push_str(&deployment_block(spec, name));
    if !spec.ports.is_empty() {
        out.push_str("---\n");
        out.push_str(&service_block(spec, name));
    }
    if !split_env(&spec.env).0.is_empty() {
        out.push_str("---\n");
        out.push_str(&configmap_block(name));
    }
    if !split_env(&spec.env).1.is_empty() {
        out.push_str("---\n");
        out.push_str(&secret_block(name));
    }
    for volume in &spec.volumes {
        if let VolumeSource::Named(vol) = &volume.source {
            out.push_str("---\n");
            out.push_str(&pvc_block(name, &dns_name(vol)));
        }
    }
    out
}

fn deployment_block(spec: &ContainerSpec, name: &str) -> String {
    let mut s = String::new();
    let (has_config, has_secret) = {
        let (config_env, secret_env) = split_env(&spec.env);
        (!config_env.is_empty(), !secret_env.is_empty())
    };

    let _ = write!(
        s,
        "apiVersion: apps/v1\n\
         kind: Deployment\n\
         metadata:\n\
         \x20 name: {name}\n\
         \x20 namespace: {{{{ .Values.namespace }}}}\n\
         \x20 labels:\n\
         \x20\x20\x20 app: {name}\n\
         spec:\n\
         \x20 replicas: {{{{ $svc.replicas }}}}\n\
         \x20 selector:\n\
         \x20\x20\x20 matchLabels:\n\
         \x20\x20\x20\x20\x20 app: {name}\n\
         \x20 template:\n\
         \x20\x20\x20 metadata:\n\
         \x20\x20\x20\x20\x20 labels:\n\
         \x20\x20\x20\x20\x20\x20\x20 app: {name}\n\
         \x20\x20\x20 spec:\n\
         \x20\x20\x20\x20\x20 containers:\n\
         \x20\x20\x20\x20\x20 - name: {name}\n\
         \x20\x20\x20\x20\x20\x20\x20 image: \"{{{{ $svc.image.repository }}}}:{{{{ $svc.image.tag }}}}\"\n\
         \x20\x20\x20\x20\x20\x20\x20 imagePullPolicy: {{{{ $svc.image.pullPolicy }}}}\n"
    );

    if !spec.ports.is_empty() {
        s.push_str("        ports:\n");
        for port in &spec.ports {
            let _ = writeln!(s, "        - containerPort: {}", port.container_port);
        }
    }
    if has_config || has_secret {
        s.push_str("        envFrom:\n");
        if has_config {
            let _ = writeln!(
                s,
                "        - configMapRef:\n            name: {name}-config"
            );
        }
        if has_secret {
            let _ = writeln!(s, "        - secretRef:\n            name: {name}-secret");
        }
    }
    let mounts: Vec<(String, &str)> = named_mounts(spec);
    if !mounts.is_empty() {
        s.push_str("        volumeMounts:\n");
        for (vol, target) in &mounts {
            let _ = writeln!(s, "        - name: {vol}\n          mountPath: {target}");
        }
    }
    if let Some(entrypoint) = &spec.entrypoint {
        s.push_str("        command:\n");
        for arg in entrypoint {
            let _ = writeln!(s, "        - {}", yaml_scalar(arg));
        }
    }
    if let Some(args) = &spec.command {
        s.push_str("        args:\n");
        for arg in args {
            let _ = writeln!(s, "        - {}", yaml_scalar(arg));
        }
    }
    if let Some(dir) = &spec.working_dir {
        let _ = writeln!(s, "        workingDir: {dir}");
    }
    if let Some(hc) = &spec.healthcheck {
        let probe = probe_block(hc);
        let _ = write!(s, "        readinessProbe:\n{probe}");
        let _ = write!(s, "        livenessProbe:\n{probe}");
    }
    if !mounts.is_empty() {
        s.push_str("      volumes:\n");
        for (vol, _) in &mounts {
            let _ = writeln!(
                s,
                "      - name: {vol}\n        persistentVolumeClaim:\n          claimName: {name}-{vol}"
            );
        }
    }
    s
}

fn service_block(spec: &ContainerSpec, name: &str) -> String {
    let mut s = String::new();
    let _ = write!(
        s,
        "apiVersion: v1\n\
         kind: Service\n\
         metadata:\n\
         \x20 name: {name}\n\
         \x20 namespace: {{{{ .Values.namespace }}}}\n\
         \x20 labels:\n\
         \x20\x20\x20 app: {name}\n\
         spec:\n\
         \x20 selector:\n\
         \x20\x20\x20 app: {name}\n\
         \x20 ports:\n"
    );
    for port in &spec.ports {
        let _ = writeln!(
            s,
            "  - port: {p}\n    targetPort: {p}",
            p = port.container_port
        );
    }
    if spec.ports.is_empty() {
        s.push_str("  []\n");
    }
    s
}

fn configmap_block(name: &str) -> String {
    format!(
        "apiVersion: v1\n\
         kind: ConfigMap\n\
         metadata:\n\
         \x20 name: {name}-config\n\
         \x20 namespace: {{{{ .Values.namespace }}}}\n\
         \x20 labels:\n\
         \x20\x20\x20 app: {name}\n\
         data:\n\
         {{{{- range $k, $v := $svc.env }}}}\n\
         \x20 {{{{ $k }}}}: {{{{ $v | quote }}}}\n\
         {{{{- end }}}}\n"
    )
}

fn secret_block(name: &str) -> String {
    format!(
        "apiVersion: v1\n\
         kind: Secret\n\
         metadata:\n\
         \x20 name: {name}-secret\n\
         \x20 namespace: {{{{ .Values.namespace }}}}\n\
         \x20 labels:\n\
         \x20\x20\x20 app: {name}\n\
         stringData:\n\
         {{{{- range $k, $v := $svc.secrets }}}}\n\
         \x20 {{{{ $k }}}}: {{{{ $v | quote }}}}\n\
         {{{{- end }}}}\n"
    )
}

fn pvc_block(name: &str, volume: &str) -> String {
    format!(
        "apiVersion: v1\n\
         kind: PersistentVolumeClaim\n\
         metadata:\n\
         \x20 name: {name}-{volume}\n\
         \x20 namespace: {{{{ .Values.namespace }}}}\n\
         \x20 labels:\n\
         \x20\x20\x20 app: {name}\n\
         spec:\n\
         \x20 accessModes:\n\
         \x20 - ReadWriteOnce\n\
         \x20 resources:\n\
         \x20\x20\x20 requests:\n\
         \x20\x20\x20\x20\x20 storage: 1Gi\n"
    )
}

fn probe_block(hc: &HealthcheckSpec) -> String {
    let command = match hc.test.first().map(String::as_str) {
        Some("CMD") => hc.test[1..].to_vec(),
        Some("CMD-SHELL") if hc.test.len() > 1 => {
            vec!["sh".to_owned(), "-c".to_owned(), hc.test[1..].join(" ")]
        }
        _ => hc.test.clone(),
    };
    let mut s = String::from("          exec:\n            command:\n");
    for arg in &command {
        let _ = writeln!(s, "            - {arg}");
    }
    let _ = writeln!(s, "          periodSeconds: {}", secs(hc.interval));
    let _ = writeln!(s, "          timeoutSeconds: {}", secs(hc.timeout));
    let _ = writeln!(s, "          failureThreshold: {}", hc.retries);
    let _ = writeln!(
        s,
        "          initialDelaySeconds: {}",
        secs(hc.start_period)
    );
    s
}

/// Named volume mounts as `(volume_name, mount_path)`.
fn named_mounts(spec: &ContainerSpec) -> Vec<(String, &str)> {
    spec.volumes
        .iter()
        .filter_map(|v| match &v.source {
            VolumeSource::Named(name) => Some((dns_name(name), v.target.as_str())),
            _ => None,
        })
        .collect()
}

/// Secret values are replaced with a placeholder so the exported
/// chart never contains real credentials.
fn split_env(
    env: &std::collections::HashMap<String, String>,
) -> (BTreeMap<String, String>, BTreeMap<String, String>) {
    let mut config = BTreeMap::new();
    let mut secret = BTreeMap::new();
    for (key, value) in env {
        if SECRET_MARKERS
            .iter()
            .any(|m| key.to_ascii_uppercase().contains(m))
        {
            secret.insert(key.clone(), "***".to_owned());
        } else {
            config.insert(key.clone(), value.clone());
        }
    }
    (config, secret)
}

/// Split an image reference into `(repository, tag)` on the last colon.
fn split_image(image: &ImageSource) -> (String, String) {
    let reference = match image {
        ImageSource::Pull(img) => img.clone(),
        ImageSource::Build { tag, .. } => tag.clone(),
    };
    match reference.rsplit_once(':') {
        Some((repo, tag)) if !repo.is_empty() => (repo.to_owned(), tag.to_owned()),
        _ => (reference, "latest".to_owned()),
    }
}

fn pull_policy_str(policy: ImagePullPolicy) -> &'static str {
    match policy {
        ImagePullPolicy::Always => "Always",
        ImagePullPolicy::IfNotPresent => "IfNotPresent",
        ImagePullPolicy::Never => "Never",
    }
}

#[allow(clippy::cast_possible_truncation)]
fn secs(d: Duration) -> u32 {
    d.as_secs().min(u64::from(u32::MAX)) as u32
}

fn to_yaml<T: Serialize>(value: &T) -> Result<String> {
    serde_norway::to_string(value).map_err(|e| crate::ExportError::Unsupported {
        resource: "<helm>".to_owned(),
        target: "helm",
        reason: format!("failed to serialise chart data: {e}"),
    })
}

/// Column, counted from the start of the line, at which a
/// `command:`/`args:` list item's scalar begins: `        - ` is eight
/// spaces, a dash and a space.
const ARGV_SCALAR_COLUMN: usize = 10;

/// Render a single string as a YAML scalar for splicing into the
/// hand-written `command:`/`args:` blocks below, closing the Go
/// `text/template` injection hazard those blocks are exposed to.
///
/// Two mechanisms are layered here, in this order:
///
/// 1. The value is quoted exactly as `serde_norway` would quote it when
///    serialising the same value as part of a typed struct (as the
///    Kubernetes emitter does): an argument containing `: ` is
///    single-quoted so it is not read as a YAML mapping, and a
///    multi-line argument becomes a literal block scalar.
/// 2. Helm renders every file under a chart's `templates/` directory
///    through Go `text/template` BEFORE any YAML parser sees it, so
///    YAML quoting alone does nothing against `{{`: a value quoted as
///    `'{{ .Values.x }}'` is handed to Go's templater as the literal
///    characters `{{ .Values.x }}`, which Go evaluates as a template
///    action at `helm install` time, quotes or not. Every `{{` in the
///    already-serialised scalar is therefore additionally escaped to
///    the Helm literal `{{ "{{" }}`, which Go renders back to a literal
///    `{{` before the YAML parser ever runs. This is the point where
///    the Helm emitter's raw template text deliberately diverges from
///    what the Kubernetes emitter emits for the same value: the two
///    agree again only after Helm renders.
///
/// A multi-line value also needs its block scalar body re-indented:
/// `serde_norway` indents a block scalar's body two columns from the
/// document root, but the result here is spliced after a `        - `
/// list marker, so an unindented body would dedent out of the list
/// item and the chart would fail to parse. The body is shifted to
/// [`ARGV_SCALAR_COLUMN`], the column where the list item's scalar
/// starts.
fn yaml_scalar(value: &str) -> String {
    let serialised = serde_norway::to_string(value).map_or_else(
        |_| value.to_owned(),
        |s| s.strip_suffix('\n').unwrap_or(&s).to_owned(),
    );
    let escaped = serialised.replace("{{", r#"{{ "{{" }}"#);
    reindent_block_scalar(&escaped, ARGV_SCALAR_COLUMN)
}

/// Shift the body of a literal or folded block scalar (`serde_norway`'s
/// `|`, `|-`, `|2-`, ... forms) from its default two-column indentation
/// to `column`. A plain or quoted single-line scalar has no body to
/// shift and is returned unchanged.
fn reindent_block_scalar(scalar: &str, column: usize) -> String {
    let Some(newline_at) = scalar.find('\n') else {
        return scalar.to_owned();
    };
    let (header, body) = scalar.split_at(newline_at);
    let pad = " ".repeat(column.saturating_sub(2));
    let mut out = header.to_owned();
    for line in body[1..].split('\n') {
        out.push('\n');
        if !line.is_empty() {
            out.push_str(&pad);
        }
        out.push_str(line);
    }
    out
}

// --- Typed chart data ---------------------------------------------------

#[derive(Serialize)]
struct Chart {
    #[serde(rename = "apiVersion")]
    api_version: &'static str,
    name: String,
    version: String,
    description: String,
}

#[derive(Serialize)]
struct Values {
    namespace: String,
    services: BTreeMap<String, ServiceValues>,
}

#[derive(Serialize)]
struct ServiceValues {
    replicas: u32,
    image: ImageValues,
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    env: BTreeMap<String, String>,
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    secrets: BTreeMap<String, String>,
}

#[derive(Serialize)]
struct ImageValues {
    repository: String,
    tag: String,
    #[serde(rename = "pullPolicy")]
    pull_policy: String,
}