Skip to main content

alef_component_runtime/
error.rs

1use std::path::PathBuf;
2
3#[derive(Debug, thiserror::Error)]
4pub enum ComponentError {
5    #[error("component `{component_id}` has no artifact for target `{target}`")]
6    ArtifactNotFound { component_id: String, target: String },
7    #[error(
8        "component `{component_id}` is not locked; the embedded components.lock.json is still \
9         the empty bootstrap lock `alef generate` writes before any artifact exists -- run \
10         `alef component lock` to populate it"
11    )]
12    ComponentsNotLocked { component_id: String },
13    #[error("component `{component}` is bundled for this target and cannot be downloaded")]
14    BundledComponentNotLoadable { component: String },
15    #[error("component `{component_id}` does not provide contract `{contract}`")]
16    ContractNotProvided { component_id: String, contract: String },
17    #[error("invalid SHA-256 digest `{0}`")]
18    InvalidDigest(String),
19    #[error("artifact digest mismatch: expected {expected}, got {actual}")]
20    DigestMismatch { expected: String, actual: String },
21    #[error("artifact size mismatch: expected {expected} bytes, got {actual} bytes")]
22    SizeMismatch { expected: u64, actual: u64 },
23    #[error("artifact signature is required")]
24    SignatureRequired,
25    #[error("invalid Ed25519 signature encoding")]
26    InvalidSignatureEncoding,
27    #[error("artifact signature verification failed")]
28    SignatureVerification,
29    #[error("component manifest is not in canonical JSON form")]
30    NonCanonicalManifest,
31    #[error("component manifest digest does not match the lock")]
32    ManifestDigestMismatch,
33    #[error("component manifest identity does not match the lock")]
34    ManifestIdentityMismatch,
35    #[error("component manifest schema or ABI version is unsupported")]
36    UnsupportedManifest,
37    #[error("component signature uses unsupported algorithm `{0}`")]
38    UnsupportedSignatureAlgorithm(String),
39    #[error("component signature key `{0}` is not embedded in the lock")]
40    UnknownSignatureKey(String),
41    #[error("component signature key does not match the lock entry")]
42    SignatureKeyMismatch,
43    #[error("unsafe archive entry `{0}`")]
44    UnsafeArchiveEntry(String),
45    #[error("component archive has more than {max} entries (found at least {actual})")]
46    TooManyArchiveEntries { max: usize, actual: usize },
47    #[error("extracted component archive entry exceeds the {limit}-byte size limit ({actual} bytes)")]
48    ExtractedSizeExceeded { limit: u64, actual: u64 },
49    #[error("artifact library path `{0}` is not a safe relative path")]
50    UnsafeLibraryPath(String),
51    #[error("component library is missing at `{0}`")]
52    MissingLibrary(PathBuf),
53    #[error("failed to download `{url}`: {message}")]
54    Download { url: String, message: String },
55    #[error("component `{component}` is not cached and network access is disabled (would fetch `{url}`)")]
56    Offline { component: String, url: String },
57    #[error("component download was cancelled")]
58    Cancelled,
59    #[error("failed to load component library `{path}`: {message}")]
60    LibraryLoad { path: PathBuf, message: String },
61    #[error("component library does not export the requested entry point: {0}")]
62    MissingEntrypoint(String),
63    #[error("component entrypoint failed with status {0}")]
64    EntrypointFailed(i32),
65    #[error("component returned an invalid descriptor: {0}")]
66    InvalidDescriptor(&'static str),
67    #[error(
68        "component ABI {actual_major}.{actual_minor} is incompatible with host ABI {expected_major}.{expected_minor}"
69    )]
70    IncompatibleAbi {
71        expected_major: u32,
72        expected_minor: u32,
73        actual_major: u32,
74        actual_minor: u32,
75    },
76    #[error("component identity mismatch: expected `{expected}`, got `{actual}`")]
77    IdentityMismatch { expected: String, actual: String },
78    #[error("component contract hash does not match the requested contract")]
79    ContractHashMismatch,
80    #[error("component feature-set hash does not match the requested feature set")]
81    FeatureSetHashMismatch,
82    #[error("component lock contains duplicate entry `{component_id}` for target `{target}`")]
83    DuplicateLockEntry { component_id: String, target: String },
84    #[error("component lock schema version {0} is not supported")]
85    UnsupportedLockSchema(u32),
86    #[error("component lock public key is not a valid Ed25519 public key")]
87    InvalidPublicKey,
88    #[error("component contract table is too small or incorrectly aligned")]
89    InvalidContractTable,
90    #[error("component descriptor does not provide an instance factory")]
91    MissingInstanceFactory,
92    #[error("component descriptor does not provide an instance destructor")]
93    MissingInstanceDestructor,
94    #[error("component instance creation failed with status {status}: {message}")]
95    InstanceCreation { status: i32, message: String },
96    #[error("component instance factory returned a null handle")]
97    NullInstance,
98    #[error("component string is not valid UTF-8")]
99    InvalidUtf8,
100    #[error("component string exceeds the maximum supported length")]
101    StringTooLong,
102    #[error("JSON error: {0}")]
103    Json(#[from] serde_json::Error),
104    #[error("I/O error: {0}")]
105    Io(#[from] std::io::Error),
106}
107
108impl ComponentError {
109    /// A stable, language-agnostic identifier for this error's kind, independent of its
110    /// human-readable message and never changing across releases for the same variant.
111    /// Generated bindings prefix the message with this (see
112    /// `alef::backends::native_components`) so callers in any host language can distinguish,
113    /// for example, an offline failure from an invalid signature from an unsupported host
114    /// without parsing free-form text.
115    #[must_use]
116    pub fn code(&self) -> &'static str {
117        match self {
118            Self::ArtifactNotFound { .. } => "artifact_not_found",
119            Self::ComponentsNotLocked { .. } => "components_not_locked",
120            Self::BundledComponentNotLoadable { .. } => "bundled_component_not_loadable",
121            Self::ContractNotProvided { .. } => "contract_not_provided",
122            Self::InvalidDigest(_) => "invalid_digest",
123            Self::DigestMismatch { .. } => "digest_mismatch",
124            Self::SizeMismatch { .. } => "size_mismatch",
125            Self::SignatureRequired => "signature_required",
126            Self::InvalidSignatureEncoding => "invalid_signature_encoding",
127            Self::SignatureVerification => "signature_verification_failed",
128            Self::NonCanonicalManifest => "non_canonical_manifest",
129            Self::ManifestDigestMismatch => "manifest_digest_mismatch",
130            Self::ManifestIdentityMismatch => "manifest_identity_mismatch",
131            Self::UnsupportedManifest => "unsupported_manifest",
132            Self::UnsupportedSignatureAlgorithm(_) => "unsupported_signature_algorithm",
133            Self::UnknownSignatureKey(_) => "unknown_signature_key",
134            Self::SignatureKeyMismatch => "signature_key_mismatch",
135            Self::UnsafeArchiveEntry(_) => "unsafe_archive_entry",
136            Self::TooManyArchiveEntries { .. } => "too_many_archive_entries",
137            Self::ExtractedSizeExceeded { .. } => "extracted_size_exceeded",
138            Self::UnsafeLibraryPath(_) => "unsafe_library_path",
139            Self::MissingLibrary(_) => "missing_library",
140            Self::Download { .. } => "download_failed",
141            Self::Offline { .. } => "offline",
142            Self::Cancelled => "cancelled",
143            Self::LibraryLoad { .. } => "library_load_failed",
144            Self::MissingEntrypoint(_) => "missing_entrypoint",
145            Self::EntrypointFailed(_) => "entrypoint_failed",
146            Self::InvalidDescriptor(_) => "invalid_descriptor",
147            Self::IncompatibleAbi { .. } => "incompatible_abi",
148            Self::IdentityMismatch { .. } => "identity_mismatch",
149            Self::ContractHashMismatch => "contract_hash_mismatch",
150            Self::FeatureSetHashMismatch => "feature_set_hash_mismatch",
151            Self::DuplicateLockEntry { .. } => "duplicate_lock_entry",
152            Self::UnsupportedLockSchema(_) => "unsupported_lock_schema",
153            Self::InvalidPublicKey => "invalid_public_key",
154            Self::InvalidContractTable => "invalid_contract_table",
155            Self::MissingInstanceFactory => "missing_instance_factory",
156            Self::MissingInstanceDestructor => "missing_instance_destructor",
157            Self::InstanceCreation { .. } => "instance_creation_failed",
158            Self::NullInstance => "null_instance",
159            Self::InvalidUtf8 => "invalid_utf8",
160            Self::StringTooLong => "string_too_long",
161            Self::Json(_) => "json_error",
162            Self::Io(_) => "io_error",
163        }
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn code_is_stable_and_distinct_for_representative_variants() {
173        assert_eq!(
174            ComponentError::Offline {
175                component: "demo".into(),
176                url: "https://example.invalid".into(),
177            }
178            .code(),
179            "offline"
180        );
181        assert_eq!(
182            ComponentError::SignatureVerification.code(),
183            "signature_verification_failed"
184        );
185        assert_eq!(
186            ComponentError::BundledComponentNotLoadable {
187                component: "demo".into()
188            }
189            .code(),
190            "bundled_component_not_loadable"
191        );
192    }
193
194    #[test]
195    fn code_never_appears_inside_its_own_display_message_by_accident() {
196        // Not a hard requirement, just documents that `code()` and `Display` are independent
197        // surfaces: generated bindings prefix the message with the code themselves rather
198        // than relying on it already being embedded.
199        let error = ComponentError::SignatureVerification;
200        assert!(!error.to_string().contains(error.code()));
201    }
202}