forjar 1.24.0

Rust-native Infrastructure as Code — bare-metal first, BLAKE3 state, provenance tracing
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
517
518
519
520
521
522
523
524
525
526
//! FJ-2104: Build container image from resource definitions.
//!
//! Wires `assemble_image()` into the `forjar build` CLI command,
//! converting resource definitions into `ImageBuildPlan` + `LayerEntry` sets.

use crate::core::store::layer_builder::LayerEntry;
use crate::core::store::overlay_export;
use crate::core::types::{
    ForjarConfig, ImageBuildMetrics, ImageBuildPlan, LayerMetric, LayerStrategy, OciLayerConfig,
    Resource,
};

/// FJ-2104: Build container image from a resource definition.
#[allow(clippy::too_many_arguments)]
pub(crate) fn cmd_build(
    file: &std::path::Path,
    resource: &str,
    load: bool,
    push: bool,
    far: bool,
    sandbox: bool,
    json: bool,
) -> Result<(), String> {
    // Refs #212: `--json` used to print "not yet implemented, flag ignored"
    // and then the human build log, so `forjar build --json | jq` failed while
    // the command exited 0. It now emits a real manifest — and refuses the
    // combinations whose stdout it cannot own, rather than emitting JSON with
    // `docker load` progress interleaved into it.
    if json {
        reject_json_stdout_conflicts(load, push, far, sandbox)?;
    }
    let config = super::helpers::parse_and_validate(file)?;
    let res = config
        .resources
        .get(resource)
        .ok_or_else(|| format!("resource '{resource}' not found"))?;
    if !matches!(res.resource_type, crate::core::types::ResourceType::Image) {
        return Err(format!("resource '{resource}' is not type: image"));
    }

    let plan = build_plan_from_resource(resource, res, &config)?;
    let output_dir = std::path::Path::new("state/images").join(resource);
    std::fs::create_dir_all(&output_dir).map_err(|e| format!("create output dir: {e}"))?;

    if sandbox {
        return cmd_build_sandbox(resource, &plan, &config, &output_dir, load, push, far);
    }

    let layer_entries = collect_layer_entries(&plan, &config)?;

    // FJ-2403/E16: Check build cache — skip rebuild if inputs unchanged.
    let input_hash = compute_layer_input_hash(&layer_entries);
    if let Some(cached) = check_build_cache(&output_dir, &input_hash) {
        if json {
            print_build_json(&plan.tag, &output_dir, None, true);
            return Ok(());
        }
        println!("\nBuilding {resource} ({}) — CACHED", plan.tag);
        println!("  {cached}");
        println!("  Input hash: {input_hash}");
        run_distribution(resource, &plan.tag, &output_dir, load, push, far)?;
        return Ok(());
    }

    let start = std::time::Instant::now();
    let result = crate::core::store::image_assembler::assemble_image(
        &plan,
        &layer_entries,
        &output_dir,
        &OciLayerConfig::default(),
        None, // E12: default to host architecture
    )?;
    let duration = start.elapsed();

    if !json {
        print_build_report(resource, &plan.tag, &result, &output_dir, duration);
    }

    // FJ-2403/E17: Collect and persist image build metrics.
    record_build_metrics(&plan.tag, &result, duration, &output_dir);
    write_build_cache(&output_dir, &input_hash);

    if json {
        print_build_json(&plan.tag, &output_dir, Some(&result), false);
        return Ok(());
    }

    run_distribution(resource, &plan.tag, &output_dir, load, push, far)
}

/// The human build log: one line per layer, then the image summary.
fn print_build_report(
    resource: &str,
    tag: &str,
    result: &crate::core::store::image_assembler::AssembledImage,
    output_dir: &std::path::Path,
    duration: std::time::Duration,
) {
    println!("\nBuilding {resource} ({tag})");
    for (i, layer) in result.layers.iter().enumerate() {
        println!(
            "  Layer {}/{}: {} files, {} -> {} bytes",
            i + 1,
            result.layers.len(),
            layer.file_count,
            layer.uncompressed_size,
            layer.compressed_size
        );
    }
    println!(
        "\n  Image: {} ({} layers, {} bytes)",
        tag,
        result.layers.len(),
        result.total_size
    );
    println!("  Layout: {}", output_dir.display());
    println!("  Built in {:.1}s", duration.as_secs_f64());
}

/// FJ-2403/E17: Collect and persist image build metrics. A write failure warns
/// on stderr and is otherwise ignored, as it was inline.
fn record_build_metrics(
    tag: &str,
    result: &crate::core::store::image_assembler::AssembledImage,
    duration: std::time::Duration,
    output_dir: &std::path::Path,
) {
    let metrics = ImageBuildMetrics {
        tag: tag.to_string(),
        layer_count: result.layers.len(),
        total_size: result.total_size,
        layers: result
            .layers
            .iter()
            .map(|l| LayerMetric {
                file_count: l.file_count,
                uncompressed_size: l.uncompressed_size,
                compressed_size: l.compressed_size,
            })
            .collect(),
        duration_secs: duration.as_secs_f64(),
        built_at: crate::tripwire::eventlog::now_iso8601(),
        forjar_version: env!("CARGO_PKG_VERSION").to_string(),
        target_arch: std::env::consts::ARCH.to_string(),
    };
    if let Err(e) = metrics.write_to(output_dir) {
        eprintln!("  warning: {e}");
    }
}

/// Refs #212: the flags `--json` cannot share stdout with.
///
/// Lifted out of `cmd_build` unchanged, including the order the flags are
/// tested in, which decides which one the message names.
fn reject_json_stdout_conflicts(
    load: bool,
    push: bool,
    far: bool,
    sandbox: bool,
) -> Result<(), String> {
    let blocking = [
        (load, "--load"),
        (push, "--push"),
        (far, "--far"),
        (sandbox, "--sandbox"),
    ];
    if let Some((_, flag)) = blocking.into_iter().find(|(on, _)| *on) {
        return Err(format!(
            "--json is not supported together with {flag}: {flag} streams \
             human-readable progress on stdout, which would not parse as JSON. \
             Run the build with --json first, then {flag} separately."
        ));
    }
    Ok(())
}

/// Hand a finished layout to the distribution flags, in the order a build
/// has always applied them: `--load`, then `--push`, then `--far`.
fn run_distribution(
    resource: &str,
    tag: &str,
    output_dir: &std::path::Path,
    load: bool,
    push: bool,
    far: bool,
) -> Result<(), String> {
    if load {
        cmd_build_load(output_dir)?;
    }
    if push {
        cmd_build_push(tag, output_dir)?;
    }
    if far {
        cmd_build_far(resource, output_dir)?;
    }
    Ok(())
}

/// Refs #212: the machine-readable form of a build.
///
/// Reports the layout that is on disk, not a synthesised description of one:
/// `layout_exists` is a stat of `index.json`, so a consumer can tell a real
/// build from a claim. On a cache hit there is no fresh `AssembledImage`, and
/// the manifest is read back from the layout the earlier build wrote.
fn print_build_json(
    tag: &str,
    output_dir: &std::path::Path,
    result: Option<&crate::core::store::image_assembler::AssembledImage>,
    cached: bool,
) {
    let layers: Vec<serde_json::Value> = result
        .map(|r| {
            r.layers
                .iter()
                .map(|l| {
                    serde_json::json!({
                        "file_count": l.file_count,
                        "uncompressed_size": l.uncompressed_size,
                        "compressed_size": l.compressed_size,
                        "digest": l.digest,
                    })
                })
                .collect()
        })
        .unwrap_or_default();
    let doc = serde_json::json!({
        "tag": tag,
        "layout": output_dir.display().to_string(),
        "layout_exists": output_dir.join("index.json").exists(),
        "cached": cached,
        "layers": layers,
        "layer_count": result.map(|r| r.layers.len()),
        "total_size": result.map(|r| r.total_size),
    });
    println!(
        "{}",
        serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string())
    );
}

/// FJ-2103: Build image inside container sandbox (Docker/Podman).
#[allow(clippy::too_many_arguments)]
fn cmd_build_sandbox(
    resource: &str,
    plan: &ImageBuildPlan,
    config: &ForjarConfig,
    output_dir: &std::path::Path,
    load: bool,
    push: bool,
    far: bool,
) -> Result<(), String> {
    use crate::core::store::container_build;

    // Generate apply scripts from non-image resources in the config
    let apply_scripts: Vec<String> = config
        .resources
        .iter()
        .filter(|(_, r)| !matches!(r.resource_type, crate::core::types::ResourceType::Image))
        .filter_map(|(_, r)| {
            let resolved = crate::core::resolver::resolve_resource_templates(
                r,
                &config.params,
                &config.machines,
            )
            .ok()?;
            crate::core::codegen::apply_script(&resolved).ok()
        })
        .collect();

    println!("\nBuilding {resource} ({}) via container sandbox", plan.tag);
    println!("  Scripts: {}", apply_scripts.len());

    let result = container_build::build_image_in_container(plan, &apply_scripts, output_dir)?;

    println!("  {}", container_build::format_container_build(&result));
    println!("  Layout: {}", output_dir.display());

    run_distribution(resource, &plan.tag, output_dir, load, push, far)
}

/// Refs #210: the one place an image resource's reference is decided.
///
/// `tag:` on an image resource is honoured as a FULL reference
/// (`registry/repo:tag`) when it names one; it used to be parsed and silently
/// dropped, so a resource declaring `ghcr.io/foo/bar:1.2.3` built — and
/// pushed — under a name nobody wrote. `--push` reuses this exact string, so
/// the pushed reference is by construction the reference that was built.
fn resource_image_reference(name: &str, res: &Resource) -> String {
    let declared = res.tag.as_deref().map(str::trim).filter(|t| !t.is_empty());
    if let Some(full) = declared.filter(|t| t.contains('/') || t.contains(':')) {
        return full.to_string();
    }
    let version = declared
        .or(res.version.as_deref())
        .unwrap_or(DEFAULT_IMAGE_TAG);
    let image_name = res.name.as_deref().unwrap_or(name);
    format!("{image_name}:{version}")
}

/// Tag assumed when an image resource declares no version.
const DEFAULT_IMAGE_TAG: &str = "latest";

/// Build an ImageBuildPlan from a resource definition.
fn build_plan_from_resource(
    name: &str,
    res: &Resource,
    config: &ForjarConfig,
) -> Result<ImageBuildPlan, String> {
    // GH-91: config not yet used for build plan customization
    let _ = config;
    let image_reference = resource_image_reference(name, res);

    // Check for base image layers
    let mut layers = Vec::new();
    if let Some(ref base) = res.image {
        let base_dir = std::path::Path::new("state/images").join(base.replace([':', '/'], "_"));
        if base_dir.exists() {
            if let Ok(base_layers) = crate::core::store::base_image::extract_base_layers(&base_dir)
            {
                println!(
                    "  {}",
                    crate::core::store::base_image::format_base_info(base, &base_layers)
                );
            }
        }
    }

    // E13: Automatic layer splitting by file type.
    // Config files go to a separate layer for better cache reuse.
    let all_paths: Vec<String> = res.path.iter().cloned().collect();
    let (config_paths, app_paths) = split_paths_by_type(&all_paths);

    if !config_paths.is_empty() && !app_paths.is_empty() {
        // Two layers: app binaries first (changes less), config on top (changes more)
        layers.push(LayerStrategy::Files { paths: app_paths });
        layers.push(LayerStrategy::Files {
            paths: config_paths,
        });
    } else {
        layers.push(LayerStrategy::Files { paths: all_paths });
    }

    Ok(ImageBuildPlan {
        tag: image_reference,
        base_image: res.image.clone(),
        layers,
        labels: vec![],
        entrypoint: res.command.clone().map(|e| vec![e]),
    })
}

/// Collect LayerEntry sets for each layer in the plan.
fn collect_layer_entries(
    plan: &ImageBuildPlan,
    config: &ForjarConfig,
) -> Result<Vec<Vec<LayerEntry>>, String> {
    plan.layers
        .iter()
        .map(|strategy| collect_strategy_entries(strategy, config))
        .collect()
}

fn collect_strategy_entries(
    strategy: &LayerStrategy,
    config: &ForjarConfig,
) -> Result<Vec<LayerEntry>, String> {
    match strategy {
        LayerStrategy::Files { paths } => Ok(collect_file_entries(paths, config)),
        LayerStrategy::Packages { names } => {
            let content = names.join("\n");
            Ok(vec![LayerEntry::file(
                "var/lib/forjar/packages.list",
                content.as_bytes(),
                0o644,
            )])
        }
        LayerStrategy::Build {
            command: _,
            workdir,
        } => collect_build_entries(workdir.as_deref()),
        LayerStrategy::Derivation { store_path } => collect_derivation_entries(store_path),
    }
}

fn collect_file_entries(paths: &[String], config: &ForjarConfig) -> Vec<LayerEntry> {
    paths
        .iter()
        .map(|path| {
            if let Some(res) = config
                .resources
                .values()
                .find(|r| r.path.as_deref() == Some(path))
            {
                let content = res.content.as_deref().unwrap_or("").as_bytes();
                let mode = res
                    .mode
                    .as_deref()
                    .and_then(|m| u32::from_str_radix(m, 8).ok())
                    .unwrap_or(0o644);
                LayerEntry::file(path, content, mode)
            } else {
                LayerEntry::file(path, b"", 0o644)
            }
        })
        .collect()
}

/// FJ-2103: Scan overlay upper dir for Build layer strategy.
fn collect_build_entries(workdir: Option<&str>) -> Result<Vec<LayerEntry>, String> {
    let overlay_dir = workdir
        .map(std::path::Path::new)
        .unwrap_or_else(|| std::path::Path::new("/tmp/forjar-overlay"));
    if overlay_dir.exists() {
        let scan = overlay_export::scan_overlay_upper(overlay_dir, overlay_dir)
            .map_err(|e| format!("overlay scan: {e}"))?;
        Ok(overlay_export::merge_overlay_entries(&scan))
    } else {
        Ok(vec![])
    }
}

/// Scan derivation store path for layer entries.
fn collect_derivation_entries(store_path: &str) -> Result<Vec<LayerEntry>, String> {
    let p = std::path::Path::new(store_path);
    if p.exists() {
        let scan = overlay_export::scan_overlay_upper(p, p)
            .map_err(|e| format!("derivation scan: {e}"))?;
        Ok(scan.entries)
    } else {
        Ok(vec![])
    }
}

/// E13: Split file paths into config and app layers.
///
/// Config files (yaml, toml, json, conf, cfg, ini, env, properties)
/// go to a separate layer from application binaries. This provides
/// better cache reuse since configs change more frequently than binaries.
fn split_paths_by_type(paths: &[String]) -> (Vec<String>, Vec<String>) {
    let config_exts = [
        ".yaml",
        ".yml",
        ".toml",
        ".json",
        ".conf",
        ".cfg",
        ".ini",
        ".env",
        ".properties",
    ];
    let mut config_paths = Vec::new();
    let mut app_paths = Vec::new();
    for path in paths {
        let lower = path.to_lowercase();
        if config_exts.iter().any(|ext| lower.ends_with(ext)) {
            config_paths.push(path.clone());
        } else {
            app_paths.push(path.clone());
        }
    }
    (config_paths, app_paths)
}

/// FJ-2403/E16: Compute a BLAKE3 hash of all layer input content.
fn compute_layer_input_hash(layer_entries: &[Vec<LayerEntry>]) -> String {
    let mut hasher = blake3::Hasher::new();
    for entries in layer_entries {
        for entry in entries {
            hasher.update(entry.path.as_bytes());
            hasher.update(&entry.content);
            hasher.update(&entry.mode.to_le_bytes());
        }
    }
    hasher.finalize().to_hex().to_string()
}

/// FJ-2403/E16: Check if a cached build with the same input hash exists.
/// Returns a cache-hit message if found, None otherwise.
fn check_build_cache(output_dir: &std::path::Path, input_hash: &str) -> Option<String> {
    let cache_path = output_dir.join("build-cache.hash");
    let cached_hash = std::fs::read_to_string(&cache_path).ok()?;
    if cached_hash.trim() == input_hash {
        let metrics_path = output_dir.join("build-metrics.json");
        if metrics_path.exists() {
            return Some(format!(
                "Layer inputs unchanged (hash: {:.16}…), skipping rebuild",
                input_hash
            ));
        }
    }
    None
}

/// FJ-2403/E16: Write the input hash for cache checking on next build.
fn write_build_cache(output_dir: &std::path::Path, input_hash: &str) {
    let cache_path = output_dir.join("build-cache.hash");
    let _ = std::fs::write(cache_path, input_hash);
}

/// Exposed for testing.
#[cfg(test)]
pub(crate) fn test_build_plan_from_resource(
    name: &str,
    res: &Resource,
    config: &ForjarConfig,
) -> Result<ImageBuildPlan, String> {
    build_plan_from_resource(name, res, config)
}

/// Exposed for testing.
#[cfg(test)]
pub(crate) fn test_collect_layer_entries(
    plan: &ImageBuildPlan,
    config: &ForjarConfig,
) -> Result<Vec<Vec<LayerEntry>>, String> {
    collect_layer_entries(plan, config)
}

/// Exposed for testing.
#[cfg(test)]
pub(crate) fn test_split_paths_by_type(paths: &[String]) -> (Vec<String>, Vec<String>) {
    split_paths_by_type(paths)
}

// Distribution functions (load/push/far) extracted to build_distribution.rs.
use super::build_distribution::{cmd_build_far, cmd_build_load, cmd_build_push};