Skip to main content

alef_component_runtime/
manifest.rs

1use serde::{Deserialize, Serialize};
2use std::collections::BTreeMap;
3use std::path::{Path, PathBuf};
4
5pub const COMPONENT_MANIFEST_SCHEMA: u32 = 2;
6pub const COMPONENT_ABI_VERSION: u32 = 1;
7
8/// One contract a component provides, alongside the Rust type implementing it.
9///
10/// A component may provide more than one contract (one producer entrypoint per
11/// contract); each entry keeps its own `contract_hash` so a change to any single
12/// contract's ABI is independently detectable.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(deny_unknown_fields)]
15pub struct ComponentProvidedContract {
16    pub contract: String,
17    pub interface_version: u32,
18    pub contract_hash: String,
19    pub implementation: String,
20}
21
22/// Whether a component is downloaded on demand or must be linked into the binding
23/// ahead of time. `alef`'s config-resolution code (`alef::codegen::component`) re-exports
24/// this type and exposes it on the resolved component config as a forward-looking
25/// hook; no loader or backend acts on `Bundled` yet.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum ComponentDeliveryMode {
29    Download,
30    Bundled,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct ComponentIdentity {
36    pub crate_name: String,
37    pub component: String,
38    pub version: String,
39    pub target: String,
40    pub feature_hash: String,
41    /// Hash of the first (lexicographically, by contract name) contract this
42    /// component provides. For a component providing exactly one contract --
43    /// the only shape the v1 loader fully validates today -- this is that
44    /// contract's real hash. See [`ComponentManifest::provides`] for the
45    /// complete, per-contract list.
46    pub contract_hash: String,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct ComponentLibrary {
52    pub file: String,
53    pub sha256: String,
54    pub size: u64,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct ComponentManifest {
60    pub schema_version: u32,
61    pub abi_version: u32,
62    pub identity: ComponentIdentity,
63    /// Every contract this component provides, sorted by contract name.
64    pub provides: Vec<ComponentProvidedContract>,
65    pub features: Vec<String>,
66    pub default_features: bool,
67    pub library: ComponentLibrary,
68}
69
70impl ComponentManifest {
71    pub fn canonical_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
72        canonical_json(self)
73    }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct ComponentSignature {
79    pub algorithm: String,
80    pub key_id: String,
81    pub signature: String,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(deny_unknown_fields)]
86pub struct ComponentArtifactRecord {
87    pub manifest: ComponentManifest,
88    pub manifest_sha256: String,
89    pub archive: String,
90    pub archive_sha256: String,
91    pub archive_size: u64,
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub signature: Option<ComponentSignature>,
94    /// Input fingerprint of the build (see `alef component plan`). Not covered by the signature:
95    /// it is a build-planning hint recorded next to the signed manifest, absent in older records.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub input_hash: Option<String>,
98}
99
100impl ComponentArtifactRecord {
101    #[must_use]
102    pub fn record_path(&self, output_dir: &Path) -> PathBuf {
103        output_dir.join(format!("{}.record.json", self.archive))
104    }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(deny_unknown_fields)]
109pub struct ComponentLock {
110    pub schema_version: u32,
111    pub public_keys: BTreeMap<String, String>,
112    pub artifacts: Vec<ComponentLockEntry>,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(deny_unknown_fields)]
117pub struct ComponentLockEntry {
118    pub identity: ComponentIdentity,
119    /// Every contract this component provides, mirrored from the manifest so
120    /// a consumer can inspect them without downloading and parsing the archive.
121    pub provides: Vec<ComponentProvidedContract>,
122    /// Whether `identity.target` downloads this artifact or must link it into the
123    /// binding. Every entry produced by `alef component lock` today is `Download`;
124    /// no backend builds or locks a `Bundled` artifact yet.
125    pub mode: ComponentDeliveryMode,
126    pub url: String,
127    pub sha256: String,
128    pub size: u64,
129    pub manifest_sha256: String,
130    pub key_id: String,
131    /// Input fingerprint of the build that produced this artifact, copied from its record. Used
132    /// by `alef component plan` to decide whether the artifact can be reused; absent in older
133    /// locks. Not read by the loader.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub input_hash: Option<String>,
136}
137
138pub fn canonical_json<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
139    let mut bytes = serde_json::to_vec(value)?;
140    bytes.push(b'\n');
141    Ok(bytes)
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn canonical_json_is_compact_and_newline_terminated() {
150        let identity = ComponentIdentity {
151            crate_name: "demo-core".into(),
152            component: "fast".into(),
153            version: "1.0.0".into(),
154            target: "aarch64-apple-darwin".into(),
155            feature_hash: "11".repeat(32),
156            contract_hash: "22".repeat(32),
157        };
158        let bytes = canonical_json(&identity).unwrap();
159        assert!(bytes.ends_with(b"\n"));
160        assert!(!bytes.contains(&b' '));
161    }
162
163    #[test]
164    fn lock_entry_without_input_hash_still_parses_and_omits_it_when_absent() {
165        let json = r#"{"schema_version":2,"public_keys":{},"artifacts":[{"identity":{"crate_name":"c","component":"x","version":"1","target":"t","feature_hash":"f","contract_hash":"h"},"provides":[],"mode":"download","url":"u","sha256":"s","size":1,"manifest_sha256":"m","key_id":""}]}"#;
166        let lock: ComponentLock = serde_json::from_str(json).unwrap();
167        assert_eq!(lock.artifacts[0].input_hash, None);
168        assert!(
169            !String::from_utf8(canonical_json(&lock).unwrap())
170                .unwrap()
171                .contains("input_hash")
172        );
173        let with_hash = json.replace("\"key_id\":\"\"", "\"key_id\":\"\",\"input_hash\":\"abc\"");
174        let lock: ComponentLock = serde_json::from_str(&with_hash).unwrap();
175        assert_eq!(lock.artifacts[0].input_hash.as_deref(), Some("abc"));
176    }
177
178    #[test]
179    fn lock_rejects_unknown_fields() {
180        let json = r#"{"schema_version":1,"public_keys":{},"artifacts":[],"extra":true}"#;
181        assert!(serde_json::from_str::<ComponentLock>(json).is_err());
182    }
183}