greentic-component 0.4.75

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
use std::borrow::Cow;
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};

use directories::BaseDirs;
use thiserror::Error;

use crate::manifest::{ComponentManifest, parse_manifest};
use crate::signing::{SigningError, verify_manifest_hash};

const MANIFEST_NAME: &str = "component.manifest.json";

#[derive(Debug, Clone)]
pub struct ComponentHandle {
    pub manifest: ComponentManifest,
    pub wasm_path: PathBuf,
    pub root: PathBuf,
    pub manifest_path: PathBuf,
}

#[derive(Debug, Error)]
pub enum LoadError {
    #[error(
        "component not found for `{0}`; if pointing at a wasm file, pass --manifest <path/to/component.manifest.json>"
    )]
    NotFound(String),
    #[error("failed to read {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("manifest parse failed at {path}: {source}")]
    Manifest {
        path: PathBuf,
        #[source]
        source: crate::manifest::ManifestError,
    },
    #[error("missing artifact `{path}` declared in manifest")]
    MissingArtifact { path: PathBuf },
    #[error("hash verification failed: {0}")]
    Signing(#[from] SigningError),
}

pub fn discover(path_or_id: &str) -> Result<ComponentHandle, LoadError> {
    discover_with_manifest(path_or_id, None)
}

pub fn discover_with_manifest(
    path_or_id: &str,
    manifest_override: Option<&Path>,
) -> Result<ComponentHandle, LoadError> {
    if let Some(manifest_path) = manifest_override {
        return load_from_manifest(manifest_path);
    }
    let normalized = normalize_path_or_id(path_or_id);
    let normalized_str = normalized.as_ref();
    if let Some(handle) = try_explicit(normalized_str)? {
        return Ok(handle);
    }
    if let Some(handle) = try_workspace(normalized_str)? {
        return Ok(handle);
    }
    if let Some(handle) = try_registry(path_or_id)? {
        return Ok(handle);
    }
    Err(LoadError::NotFound(path_or_id.to_string()))
}

fn try_explicit(arg: &str) -> Result<Option<ComponentHandle>, LoadError> {
    let path = Path::new(arg);
    if !path.exists() {
        return Ok(None);
    }

    let target = if path.is_dir() {
        path.join(MANIFEST_NAME)
    } else if path.extension().and_then(OsStr::to_str) == Some("json") {
        path.to_path_buf()
    } else if path.extension().and_then(OsStr::to_str) == Some("wasm") {
        path.parent()
            .map(|dir| dir.join(MANIFEST_NAME))
            .unwrap_or_else(|| path.to_path_buf())
    } else {
        path.join(MANIFEST_NAME)
    };

    if target.exists() {
        return load_from_manifest(&target).map(Some);
    }

    Ok(None)
}

fn try_workspace(id: &str) -> Result<Option<ComponentHandle>, LoadError> {
    let cwd = std::env::current_dir().map_err(|e| LoadError::Io {
        path: PathBuf::from("."),
        source: e,
    })?;
    let target = cwd.join("target").join("wasm32-wasip2");
    let file_name = format!("{id}.wasm");

    for profile in ["release", "debug"] {
        let candidate = target.join(profile).join(&file_name);
        if candidate.exists() {
            let manifest_path = candidate
                .parent()
                .map(|dir| dir.join(MANIFEST_NAME))
                .unwrap_or_else(|| candidate.with_extension("manifest.json"));
            if manifest_path.exists() {
                return load_from_manifest(&manifest_path).map(Some);
            }
        }
    }

    Ok(None)
}

fn try_registry(id: &str) -> Result<Option<ComponentHandle>, LoadError> {
    let Some(base) = BaseDirs::new() else {
        return Ok(None);
    };
    let registry_root = base.home_dir().join(".greentic").join("components");
    if !registry_root.exists() {
        return Ok(None);
    }

    let mut candidates = Vec::new();
    for entry in fs::read_dir(&registry_root).map_err(|err| LoadError::Io {
        path: registry_root.clone(),
        source: err,
    })? {
        let entry = entry.map_err(|err| LoadError::Io {
            path: registry_root.clone(),
            source: err,
        })?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if name == id || (!id.contains('@') && name.starts_with(id)) {
            candidates.push(entry.path());
        }
    }

    candidates.sort();
    candidates.reverse();

    for dir in candidates {
        let manifest_path = dir.join(MANIFEST_NAME);
        if manifest_path.exists() {
            return load_from_manifest(&manifest_path).map(Some);
        }
    }

    Ok(None)
}

fn load_from_manifest(path: &Path) -> Result<ComponentHandle, LoadError> {
    let contents = fs::read_to_string(path).map_err(|source| LoadError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    let manifest = parse_manifest(&contents).map_err(|source| LoadError::Manifest {
        path: path.to_path_buf(),
        source,
    })?;
    let root = path
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| PathBuf::from("."));
    let wasm_path = root.join(manifest.artifacts.component_wasm());
    if !wasm_path.exists() {
        return Err(LoadError::MissingArtifact { path: wasm_path });
    }
    verify_manifest_hash(&manifest, &root)?;
    Ok(ComponentHandle {
        manifest,
        wasm_path,
        root,
        manifest_path: path.to_path_buf(),
    })
}

fn normalize_path_or_id(input: &str) -> Cow<'_, str> {
    if let Some(rest) = input.strip_prefix("file://") {
        Cow::Owned(rest.to_string())
    } else {
        Cow::Borrowed(input)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::{Mutex, OnceLock};

    fn cwd_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    fn manifest_json(artifact: &str, hash: &str) -> String {
        format!(
            r#"{{
  "id": "com.greentic.test.component",
  "name": "Test Component",
  "version": "0.1.0",
  "world": "greentic:component/component@0.6.0",
  "describe_export": "describe",
  "operations": [{{
    "name": "run",
    "input_schema": {{"type":"object","properties":{{}},"required":[],"additionalProperties":false}},
    "output_schema": {{"type":"object","properties":{{}},"required":[],"additionalProperties":false}}
  }}],
  "default_operation": "run",
  "supports": ["messaging"],
  "profiles": {{"default": "stateless", "supported": ["stateless"]}},
  "secret_requirements": [],
  "capabilities": {{
    "wasi": {{
      "filesystem": {{"mode":"none","mounts":[]}},
      "random": true,
      "clocks": true
    }},
    "host": {{
      "messaging": {{"inbound": true, "outbound": true}},
      "telemetry": {{"scope": "tenant"}}
    }}
  }},
  "config_schema": {{"type":"object","properties":{{}},"required":[],"additionalProperties":false}},
  "limits": {{"memory_mb": 64, "wall_time_ms": 1000}},
  "artifacts": {{"component_wasm": "{artifact}"}},
  "hashes": {{"component_wasm": "{hash}"}},
  "dev_flows": {{
    "default": {{
      "format": "flow-ir-json",
      "graph": {{
        "nodes": [{{"id":"start","type":"start"}}, {{"id":"end","type":"end"}}],
        "edges": [{{"from":"start","to":"end"}}]
      }}
    }}
  }}
}}"#
        )
    }

    fn write_component_fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().expect("fixture dir");
        let wasm_path = dir.path().join("component.wasm");
        fs::write(&wasm_path, b"fixture-wasm").expect("write wasm");
        let hash = format!("blake3:{}", blake3::hash(b"fixture-wasm").to_hex());
        let manifest_path = dir.path().join(MANIFEST_NAME);
        fs::write(&manifest_path, manifest_json("component.wasm", &hash)).expect("write manifest");
        (dir, manifest_path, wasm_path)
    }

    #[test]
    fn normalize_path_or_id_strips_file_scheme_only() {
        assert_eq!(
            normalize_path_or_id("file:///tmp/component"),
            "/tmp/component"
        );
        assert_eq!(normalize_path_or_id("component-id"), "component-id");
    }

    #[test]
    fn discover_with_manifest_uses_override_before_searching_by_id() {
        let (_dir, manifest_path, wasm_path) = write_component_fixture();

        let handle =
            discover_with_manifest("not-a-real-component", Some(&manifest_path)).expect("load");

        assert_eq!(handle.manifest_path, manifest_path);
        assert_eq!(handle.wasm_path, wasm_path);
    }

    #[test]
    fn load_from_manifest_reports_missing_artifact() {
        let dir = tempfile::tempdir().expect("fixture dir");
        let manifest_path = dir.path().join(MANIFEST_NAME);
        fs::write(
            &manifest_path,
            manifest_json(
                "missing/component.wasm",
                "blake3:0000000000000000000000000000000000000000000000000000000000000000",
            ),
        )
        .expect("write manifest");

        let err = load_from_manifest(&manifest_path).expect_err("artifact should be missing");
        assert!(
            matches!(err, LoadError::MissingArtifact { path } if path.ends_with("missing/component.wasm"))
        );
    }

    #[test]
    fn try_explicit_discovers_manifest_next_to_wasm() {
        let (_dir, manifest_path, wasm_path) = write_component_fixture();

        let handle = try_explicit(wasm_path.to_str().expect("utf-8 path"))
            .expect("try_explicit succeeds")
            .expect("fixture should resolve");

        assert_eq!(handle.manifest_path, manifest_path);
        assert_eq!(handle.wasm_path, wasm_path);
    }

    #[test]
    fn try_explicit_returns_none_for_missing_paths() {
        let missing = tempfile::tempdir()
            .expect("tempdir")
            .path()
            .join("missing-component");

        let resolved = try_explicit(missing.to_str().expect("utf-8")).expect("lookup succeeds");

        assert!(resolved.is_none());
    }

    #[test]
    fn try_explicit_discovers_manifest_inside_directory() {
        let (_dir, manifest_path, wasm_path) = write_component_fixture();
        let component_dir = manifest_path.parent().expect("manifest parent");

        let handle = try_explicit(component_dir.to_str().expect("utf-8"))
            .expect("try_explicit succeeds")
            .expect("fixture should resolve");

        assert_eq!(handle.manifest_path, manifest_path);
        assert_eq!(handle.wasm_path, wasm_path);
    }

    #[test]
    fn discover_reports_not_found_when_no_locations_match() {
        let err = discover("com.greentic.missing.component").expect_err("missing component");

        assert!(matches!(err, LoadError::NotFound(id) if id == "com.greentic.missing.component"));
    }

    #[test]
    fn load_from_manifest_reports_parse_errors() {
        let dir = tempfile::tempdir().expect("fixture dir");
        let manifest_path = dir.path().join(MANIFEST_NAME);
        fs::write(&manifest_path, "{not valid json").expect("write invalid manifest");

        let err = load_from_manifest(&manifest_path).expect_err("invalid manifest should fail");

        assert!(matches!(err, LoadError::Manifest { path, .. } if path == manifest_path));
    }

    #[test]
    fn load_from_manifest_returns_handle_for_valid_fixture() {
        let (_dir, manifest_path, wasm_path) = write_component_fixture();

        let handle = load_from_manifest(&manifest_path).expect("valid manifest should load");

        assert_eq!(
            handle.root,
            manifest_path.parent().expect("manifest parent")
        );
        assert_eq!(handle.manifest_path, manifest_path);
        assert_eq!(handle.wasm_path, wasm_path);
    }

    #[test]
    fn try_explicit_accepts_manifest_json_path_directly() {
        let (_dir, manifest_path, wasm_path) = write_component_fixture();

        let handle = try_explicit(manifest_path.to_str().expect("utf-8 path"))
            .expect("lookup succeeds")
            .expect("fixture should resolve");

        assert_eq!(handle.manifest_path, manifest_path);
        assert_eq!(handle.wasm_path, wasm_path);
    }

    #[test]
    fn try_explicit_returns_none_for_existing_non_manifest_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let existing = dir.path().join("notes.txt");
        fs::write(&existing, b"notes").expect("write note");

        let handle = try_explicit(existing.to_str().expect("utf-8")).expect("lookup succeeds");

        assert!(handle.is_none());
    }

    #[test]
    fn try_workspace_discovers_component_from_target_directory() {
        let _guard = cwd_lock().lock().expect("cwd lock");
        let original_cwd = std::env::current_dir().expect("cwd");
        let dir = tempfile::tempdir().expect("tempdir");
        std::env::set_current_dir(dir.path()).expect("set cwd");

        let profile_dir = dir.path().join("target/wasm32-wasip2/release");
        fs::create_dir_all(&profile_dir).expect("create target dir");
        let wasm_path = profile_dir.join("com.greentic.test.component.wasm");
        fs::write(&wasm_path, b"fixture-wasm").expect("write wasm");
        let hash = format!("blake3:{}", blake3::hash(b"fixture-wasm").to_hex());
        let manifest_path = profile_dir.join(MANIFEST_NAME);
        fs::write(
            &manifest_path,
            manifest_json("com.greentic.test.component.wasm", &hash),
        )
        .expect("write manifest");

        let handle = try_workspace("com.greentic.test.component")
            .expect("workspace lookup")
            .expect("fixture should resolve");

        assert_eq!(handle.manifest_path, manifest_path);
        assert_eq!(handle.wasm_path, wasm_path);

        std::env::set_current_dir(original_cwd).expect("restore cwd");
    }

    #[test]
    fn try_workspace_ignores_wasm_without_adjacent_manifest() {
        let _guard = cwd_lock().lock().expect("cwd lock");
        let original_cwd = std::env::current_dir().expect("cwd");
        let dir = tempfile::tempdir().expect("tempdir");
        std::env::set_current_dir(dir.path()).expect("set cwd");

        let profile_dir = dir.path().join("target/wasm32-wasip2/release");
        fs::create_dir_all(&profile_dir).expect("create target dir");
        fs::write(
            profile_dir.join("com.greentic.test.component.wasm"),
            b"fixture-wasm",
        )
        .expect("write wasm");

        let handle = try_workspace("com.greentic.test.component").expect("workspace lookup");

        assert!(handle.is_none());

        std::env::set_current_dir(original_cwd).expect("restore cwd");
    }
}