greentic-component 0.5.0

High-level component loader and store for Greentic components
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
#![cfg(all(feature = "cli", feature = "prepare"))]

#[path = "support/mod.rs"]
mod support;

use greentic_component::cmd::build;
use greentic_component::cmd::build::BuildArgs;
use greentic_component::embed_and_verify_wasm;
use greentic_component::error::ComponentError;
use greentic_component::scaffold::config_schema::ConfigSchemaInput;
use greentic_component::scaffold::deps::DependencyMode;
use greentic_component::scaffold::engine::{DEFAULT_WIT_WORLD, ScaffoldEngine, ScaffoldRequest};
use greentic_component::scaffold::runtime_capabilities::RuntimeCapabilitiesInput;
use predicates::prelude::*;
use serde_json::{Value, json};
use std::fs;
use std::path::Path;
use support::TestComponent;

const TEST_WIT: &str = r#"
package greentic:component@0.5.0;
world component {
    export describe: func();
}
 "#;

fn copy_component_v060_fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
    let temp = tempfile::TempDir::new().unwrap();
    let fixture_dir =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/contract/fixtures/component_v0_6_0");
    let workdir = temp.path().join("fixture");
    fs::create_dir_all(&workdir).unwrap();
    fs::copy(
        fixture_dir.join("component.wasm"),
        workdir.join("component.wasm"),
    )
    .unwrap();
    fs::copy(
        fixture_dir.join("component.manifest.json"),
        workdir.join("component.manifest.json"),
    )
    .unwrap();
    (
        temp,
        workdir.join("component.wasm"),
        workdir.join("component.manifest.json"),
    )
}

#[test]
fn inspect_outputs_json() {
    let component = TestComponent::new(TEST_WIT, &["describe"]);
    let manifest_path = component.manifest_path.to_str().unwrap();
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-inspect");
    cmd.arg(manifest_path)
        .arg("--json")
        .assert()
        .success()
        .stdout(predicate::str::contains("\"manifest\""));
}

#[test]
fn doctor_rejects_non_component_wasm() {
    let component = TestComponent::new(TEST_WIT, &["describe"]);
    let manifest_path = component.manifest_path.to_str().unwrap();
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-doctor");
    cmd.arg(manifest_path)
        .env("GREENTIC_SKIP_NODE_EXPORT_CHECK", "1")
        .assert()
        .failure()
        .stderr(predicate::str::contains("failed to load component"));
}

#[test]
fn inspect_accepts_manifest_override() {
    let component = TestComponent::new(TEST_WIT, &["describe"]);
    let wasm_path = component.wasm_path.to_str().unwrap();
    let manifest_path = component.manifest_path.to_str().unwrap();
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-inspect");
    cmd.arg(wasm_path)
        .arg("--manifest")
        .arg(manifest_path)
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "component: com.greentic.test.component",
        ));
}

#[test]
fn inspect_accepts_describe_fixture() {
    let describe_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/doctor/good_component_describe.cbor");
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-inspect");
    cmd.arg("--describe")
        .arg(describe_path)
        .arg("--json")
        .arg("--verify")
        .assert()
        .success()
        .stdout(predicate::str::contains("\"operations\""));
}

#[test]
fn inspect_reports_embedded_manifest_from_wasm_json() {
    let (_temp, wasm_path, manifest_path) = copy_component_v060_fixture();
    let manifest_raw = fs::read_to_string(&manifest_path).unwrap();
    let manifest = greentic_component::parse_manifest(&manifest_raw).unwrap();
    embed_and_verify_wasm(&wasm_path, &manifest).unwrap();

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-inspect");
    cmd.arg(wasm_path)
        .arg("--manifest")
        .arg(manifest_path)
        .arg("--json")
        .assert()
        .success()
        .stdout(predicate::str::contains("\"embedded\""))
        .stdout(predicate::str::contains("\"present\": true"))
        .stdout(predicate::str::contains("\"compare_manifest\""));
}

#[test]
fn inspect_human_output_includes_manifest_and_describe_sections_for_embedded_wasm() {
    let (_temp, wasm_path, manifest_path) = copy_component_v060_fixture();
    let manifest_raw = fs::read_to_string(&manifest_path).unwrap();
    let manifest = greentic_component::parse_manifest(&manifest_raw).unwrap();
    embed_and_verify_wasm(&wasm_path, &manifest).unwrap();

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-inspect");
    cmd.arg(wasm_path)
        .arg("--manifest")
        .arg(manifest_path)
        .assert()
        .success()
        .stdout(predicate::str::contains("manifest: "))
        .stdout(predicate::str::contains("embedded vs manifest: Match"))
        .stdout(predicate::str::contains("embedded manifest: present"))
        .stdout(predicate::str::contains(
            "world: greentic:component/component@0.6.0",
        ))
        .stdout(predicate::str::contains("operation names: handle_message"))
        .stdout(predicate::str::contains(
            "default operation: handle_message",
        ))
        .stdout(predicate::str::contains("supports: [Messaging]"))
        .stdout(predicate::str::contains("capabilities:"))
        .stdout(predicate::str::contains("secret requirements:"))
        .stdout(predicate::str::contains("profiles:"))
        .stdout(predicate::str::contains(
            "limits: memory_mb=128 wall_time_ms=1000",
        ))
        .stdout(predicate::str::contains("describe: available"))
        .stdout(predicate::str::contains("source: wit-world"))
        .stdout(predicate::str::contains("name: component"))
        .stdout(predicate::str::contains(
            "schema id: greentic:component/component@0.6.0",
        ))
        .stdout(predicate::str::contains(
            "world: greentic:component/component@0.6.0",
        ))
        .stdout(predicate::str::contains("versions: 0.6.0"))
        .stdout(predicate::str::contains("version count: 1"))
        .stdout(predicate::str::contains("functions: 2"))
        .stdout(predicate::str::contains(
            "reason: derived from exported WIT world",
        ));
}

#[test]
fn doctor_detects_scaffold_directory() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path().join("demo-detect");
    let engine = ScaffoldEngine::new();
    let request = ScaffoldRequest {
        name: "demo-detect".into(),
        path: root.clone(),
        template_id: "rust-wasi-p2-min".into(),
        org: "ai.greentic".into(),
        version: "0.1.0".into(),
        license: "MIT".into(),
        wit_world: DEFAULT_WIT_WORLD.into(),
        user_operations: vec!["handle_message".into()],
        default_operation: "handle_message".into(),
        runtime_capabilities: RuntimeCapabilitiesInput::default(),
        config_schema: ConfigSchemaInput::default(),
        non_interactive: true,
        year_override: Some(2030),
        dependency_mode: DependencyMode::Local,
    };
    engine.scaffold(request).unwrap();
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-doctor");
    cmd.arg(&root)
        .assert()
        .failure()
        .stderr(predicate::str::contains("unable to resolve wasm"));
}

#[test]
fn doctor_fails_when_built_wasm_is_missing_embedded_manifest() {
    let (_temp, wasm_path, _manifest_path) = copy_component_v060_fixture();
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-doctor");
    cmd.arg(wasm_path)
        .assert()
        .failure()
        .stdout(predicate::str::contains("doctor.embedded.missing"));
}

#[test]
fn doctor_no_longer_reports_missing_embedded_when_section_is_present() {
    let (_temp, wasm_path, manifest_path) = copy_component_v060_fixture();
    let manifest_raw = fs::read_to_string(&manifest_path).unwrap();
    let manifest = greentic_component::parse_manifest(&manifest_raw).unwrap();
    embed_and_verify_wasm(&wasm_path, &manifest).unwrap();

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("component-doctor");
    cmd.arg(wasm_path)
        .assert()
        .failure()
        .stdout(predicate::str::contains("doctor.embedded.missing").not());
}

#[test]
fn scaffold_makefile_uses_greentic_dev_commands() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path().join("demo-dev");
    let engine = ScaffoldEngine::new();
    let request = ScaffoldRequest {
        name: "demo-dev".into(),
        path: root.clone(),
        template_id: "rust-wasi-p2-min".into(),
        org: "ai.greentic".into(),
        version: "0.1.0".into(),
        license: "MIT".into(),
        wit_world: DEFAULT_WIT_WORLD.into(),
        user_operations: vec!["handle_message".into()],
        default_operation: "handle_message".into(),
        runtime_capabilities: RuntimeCapabilitiesInput::default(),
        config_schema: ConfigSchemaInput::default(),
        non_interactive: true,
        year_override: Some(2030),
        dependency_mode: DependencyMode::Local,
    };
    engine.scaffold(request).unwrap();

    let makefile =
        fs::read_to_string(root.join("Makefile")).expect("Makefile should be scaffolded");
    assert!(makefile.contains("greentic-dev component build --manifest ./component.manifest.json"));
    assert!(makefile.contains(
        "greentic-dev component doctor $(WASM_OUT) --manifest ./component.manifest.json"
    ));
}

#[test]
fn build_logs_resolved_component_world_version() {
    let temp = tempfile::TempDir::new().unwrap();
    let root = temp.path().join("build-log-world");
    let engine = ScaffoldEngine::new();
    let request = ScaffoldRequest {
        name: "build-log-world".into(),
        path: root.clone(),
        template_id: "rust-wasi-p2-min".into(),
        org: "ai.greentic".into(),
        version: "0.1.0".into(),
        license: "MIT".into(),
        wit_world: DEFAULT_WIT_WORLD.into(),
        user_operations: vec!["handle_message".into()],
        default_operation: "handle_message".into(),
        runtime_capabilities: RuntimeCapabilitiesInput::default(),
        config_schema: ConfigSchemaInput::default(),
        non_interactive: true,
        year_override: Some(2030),
        dependency_mode: DependencyMode::Local,
    };
    engine.scaffold(request).unwrap();
    let fixture_wasm =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/manifests/bin/component.wasm");

    let cargo_wrapper = root.join("fake_cargo.sh");
    std::fs::write(
        &cargo_wrapper,
        format!(
            r#"#!/bin/sh
set -e
if [ "${{1:-}}" = "component" ] && [ "${{2:-}}" = "--version" ]; then
  echo "cargo-component-component 0.21.1"
  exit 0
fi

wasm_path=$(python3 - <<'PY'
import json, os
path=os.path.join(os.getcwd(),"component.manifest.json")
try:
    with open(path, "r") as f:
        data=json.load(f)
    print(data.get("artifacts", {{}}).get("component_wasm") or "target/wasm32-wasip2/release/component.wasm")
except Exception:
    print("target/wasm32-wasip2/release/component.wasm")
PY
)
mkdir -p "$(dirname "$wasm_path")"
cp "{fixture_wasm}" "$wasm_path"

if [ "${{1:-}}" = "component" ] && [ "${{2:-}}" = "build" ]; then
  exit 0
fi

if [ "${{1:-}}" = "build" ]; then
  exit 0
fi

REAL_CARGO="$(command -v cargo)"
"$REAL_CARGO" "$@"
"#,
            fixture_wasm = fixture_wasm.display()
        ),
    )
    .expect("write cargo wrapper");
    let mut perms = std::fs::metadata(&cargo_wrapper)
        .expect("metadata")
        .permissions();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        perms.set_mode(0o755);
        std::fs::set_permissions(&cargo_wrapper, perms).expect("chmod");
    }

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("greentic-component");
    cmd.current_dir(&root)
        .env("CARGO", &cargo_wrapper)
        .env("CARGO_NET_OFFLINE", "true")
        .env("GREENTIC_SKIP_NODE_EXPORT_CHECK", "1")
        .arg("build")
        .assert()
        .success()
        .stdout(
            predicate::str::contains("Resolved manifest world: greentic:component/component@0.6.0")
                .and(predicate::str::contains("component@0.5.0").not()),
        );
}

#[test]
fn new_outputs_template_metadata_in_json() {
    let temp = tempfile::TempDir::new().unwrap();
    let project = temp.path().join("json-demo");
    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("greentic-component");
    let assert = cmd
        .arg("new")
        .arg("--name")
        .arg("json-demo")
        .arg("--org")
        .arg("ai.greentic")
        .arg("--path")
        .arg(&project)
        .arg("--no-check")
        .arg("--no-git")
        .arg("--json")
        .env("HOME", temp.path())
        .env("GREENTIC_TEMPLATE_YEAR", "2030")
        .assert()
        .success();
    let output = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout");
    let value: Value = serde_json::from_str(&output).expect("json");
    assert_eq!(
        value["scaffold"]["template"].as_str().unwrap(),
        "rust-wasi-p2-min"
    );
    assert_eq!(
        value["scaffold"]["template_description"].as_str().unwrap(),
        "Minimal Rust + WASI-P2 component starter"
    );
    assert_eq!(
        value["post_init"]["git"]["status"].as_str().unwrap(),
        "skipped"
    );
    assert!(
        value["post_init"]["events"]
            .as_array()
            .unwrap()
            .iter()
            .any(|event| event["stage"] == "git-init")
    );
}

#[test]
#[cfg(feature = "store")]
fn store_fetch_accepts_source_and_out_dir() {
    let temp = tempfile::TempDir::new().unwrap();
    let source_path = temp.path().join("component.wasm");
    fs::write(&source_path, b"fake-wasm").unwrap();

    let out_dir = temp.path().join("out");
    let cache_dir = temp.path().join("cache");
    let source_ref = format!("file://{}", source_path.display());

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("greentic-component");
    cmd.arg("store")
        .arg("fetch")
        .arg("--out")
        .arg(&out_dir)
        .arg("--cache-dir")
        .arg(&cache_dir)
        .arg(&source_ref)
        .assert()
        .success();

    let fetched = fs::read(out_dir.join("component.wasm")).expect("fetched component");
    assert_eq!(fetched, b"fake-wasm");
}

#[test]
#[cfg(feature = "store")]
fn store_fetch_accepts_wasm_output_path() {
    let temp = tempfile::TempDir::new().unwrap();
    let source_path = temp.path().join("component.wasm");
    fs::write(&source_path, b"fake-wasm").unwrap();

    let out_file = temp.path().join("offline_comp.wasm");
    let cache_dir = temp.path().join("cache");
    let source_ref = format!("file://{}", source_path.display());

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("greentic-component");
    cmd.arg("store")
        .arg("fetch")
        .arg("--out")
        .arg(&out_file)
        .arg("--cache-dir")
        .arg(&cache_dir)
        .arg(&source_ref)
        .assert()
        .success();

    let fetched = fs::read(&out_file).expect("fetched component");
    assert_eq!(fetched, b"fake-wasm");
}

#[test]
#[cfg(feature = "store")]
fn store_fetch_accepts_directory_source() {
    let temp = tempfile::TempDir::new().unwrap();
    let source_dir = temp.path().join("source");
    fs::create_dir_all(&source_dir).unwrap();
    fs::write(source_dir.join("component.wasm"), b"fake-wasm").unwrap();
    fs::write(
        source_dir.join("component.manifest.json"),
        r#"{"artifacts":{"component_wasm":"component.wasm"}}"#,
    )
    .unwrap();

    let out_dir = temp.path().join("out");
    let cache_dir = temp.path().join("cache");
    let source_ref = source_dir.to_string_lossy().to_string();

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("greentic-component");
    cmd.arg("store")
        .arg("fetch")
        .arg("--out")
        .arg(&out_dir)
        .arg("--cache-dir")
        .arg(&cache_dir)
        .arg(&source_ref)
        .assert()
        .success();

    let fetched = fs::read(out_dir.join("component.wasm")).expect("fetched component");
    assert_eq!(fetched, b"fake-wasm");
}

#[test]
fn test_command_writes_trace_on_failure() {
    let temp = tempfile::TempDir::new().unwrap();
    let trace_path = temp.path().join("trace.json");
    let input_path = temp.path().join("input.json");
    fs::write(&input_path, "{}").unwrap();

    let manifest_path =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/manifests/valid.component.json");
    let wasm_path =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/manifests/bin/component.wasm");

    let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("greentic-component");
    cmd.arg("test")
        .arg("--wasm")
        .arg(&wasm_path)
        .arg("--manifest")
        .arg(&manifest_path)
        .arg("--op")
        .arg("invalid_op")
        .arg("--input")
        .arg(&input_path)
        .arg("--trace-out")
        .arg(&trace_path)
        .assert()
        .failure();

    let trace = fs::read_to_string(&trace_path).expect("trace should be written");
    let value: Value = serde_json::from_str(&trace).expect("trace JSON");
    assert_eq!(value["trace_version"].as_u64(), Some(1));
    assert!(value["error"]["code"].as_str().is_some());
}

#[test]
fn build_fails_on_empty_operation_schemas() {
    let component = TestComponent::new(TEST_WIT, &["describe"]);
    rewrite_operation_schemas_to_empty(&component.manifest_path);

    let args = BuildArgs {
        manifest: component.manifest_path.clone(),
        cargo_bin: Some(true_bin()),
        no_flow: true,
        no_infer_config: true,
        no_write_schema: true,
        force_write_schema: false,
        no_validate: true,
        json: false,
        permissive: false,
    };

    let err = build::run(args).expect_err("build should fail when schemas are empty");
    let component_err = err
        .downcast_ref::<ComponentError>()
        .expect("expected a ComponentError");
    assert_eq!(component_err.code(), "E_OP_SCHEMA_EMPTY");
}

#[test]
fn build_permissive_allows_empty_operation_schemas() {
    let component = TestComponent::new(TEST_WIT, &["describe"]);
    rewrite_operation_schemas_to_empty(&component.manifest_path);

    let args = BuildArgs {
        manifest: component.manifest_path.clone(),
        cargo_bin: Some(true_bin()),
        no_flow: true,
        no_infer_config: true,
        no_write_schema: true,
        force_write_schema: false,
        no_validate: true,
        json: false,
        permissive: true,
    };

    build::run(args).expect("permissive build should succeed");
}

fn true_bin() -> std::path::PathBuf {
    if let Some(path) = std::env::var_os("TRUE_BIN") {
        return std::path::PathBuf::from(path);
    }
    if let Some(path) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&path) {
            let candidate = dir.join("true");
            if candidate.is_file() {
                return candidate;
            }
        }
    }
    std::path::PathBuf::from("true")
}

fn rewrite_operation_schemas_to_empty(manifest_path: &Path) {
    let mut manifest: Value =
        serde_json::from_str(&fs::read_to_string(manifest_path).expect("read manifest")).unwrap();
    if let Some(operations) = manifest
        .get_mut("operations")
        .and_then(|value| value.as_array_mut())
    {
        for operation in operations {
            operation["input_schema"] = json!({});
            operation["output_schema"] = json!({});
        }
    }
    fs::write(
        manifest_path,
        serde_json::to_string_pretty(&manifest).unwrap(),
    )
    .unwrap();
}