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("cached component object `{component}` failed verification: {source}")]
58 CachedObjectInvalid {
59 component: String,
60 source: Box<ComponentError>,
61 },
62 #[error("component download was cancelled")]
63 Cancelled,
64 #[error("failed to load component library `{path}`: {message}")]
65 LibraryLoad { path: PathBuf, message: String },
66 #[error("component library does not export the requested entry point: {0}")]
67 MissingEntrypoint(String),
68 #[error("component entrypoint failed with status {0}")]
69 EntrypointFailed(i32),
70 #[error("component returned an invalid descriptor: {0}")]
71 InvalidDescriptor(&'static str),
72 #[error(
73 "component ABI {actual_major}.{actual_minor} is incompatible with host ABI {expected_major}.{expected_minor}"
74 )]
75 IncompatibleAbi {
76 expected_major: u32,
77 expected_minor: u32,
78 actual_major: u32,
79 actual_minor: u32,
80 },
81 #[error("component identity mismatch: expected `{expected}`, got `{actual}`")]
82 IdentityMismatch { expected: String, actual: String },
83 #[error("component contract hash does not match the requested contract")]
84 ContractHashMismatch,
85 #[error("component feature-set hash does not match the requested feature set")]
86 FeatureSetHashMismatch,
87 #[error("component lock contains duplicate entry `{component_id}` for target `{target}`")]
88 DuplicateLockEntry { component_id: String, target: String },
89 #[error("component lock schema version {0} is not supported")]
90 UnsupportedLockSchema(u32),
91 #[error("component lock public key is not a valid Ed25519 public key")]
92 InvalidPublicKey,
93 #[error("component contract table is too small or incorrectly aligned")]
94 InvalidContractTable,
95 #[error("component descriptor does not provide an instance factory")]
96 MissingInstanceFactory,
97 #[error("component descriptor does not provide an instance destructor")]
98 MissingInstanceDestructor,
99 #[error("component instance creation failed with status {status}: {message}")]
100 InstanceCreation { status: i32, message: String },
101 #[error("component instance factory returned a null handle")]
102 NullInstance,
103 #[error("component string is not valid UTF-8")]
104 InvalidUtf8,
105 #[error("component string exceeds the maximum supported length")]
106 StringTooLong,
107 #[error("unsupported component transport operation: {0}")]
108 UnsupportedTransport(&'static str),
109 #[error("stdio component protocol error: {0}")]
110 SidecarProtocol(String),
111 #[error("stdio component response timed out")]
112 SidecarTimeout,
113 #[error("stdio component connection is stopped")]
114 SidecarStopped,
115 #[error("stdio component call failed with status {status}: {message}")]
116 SidecarCall { status: i32, message: String },
117 #[error("JSON error: {0}")]
118 Json(#[from] serde_json::Error),
119 #[error("I/O error: {0}")]
120 Io(#[from] std::io::Error),
121}
122
123impl ComponentError {
124 #[must_use]
131 pub fn code(&self) -> &'static str {
132 match self {
133 Self::ArtifactNotFound { .. } => "artifact_not_found",
134 Self::ComponentsNotLocked { .. } => "components_not_locked",
135 Self::BundledComponentNotLoadable { .. } => "bundled_component_not_loadable",
136 Self::ContractNotProvided { .. } => "contract_not_provided",
137 Self::InvalidDigest(_) => "invalid_digest",
138 Self::DigestMismatch { .. } => "digest_mismatch",
139 Self::SizeMismatch { .. } => "size_mismatch",
140 Self::SignatureRequired => "signature_required",
141 Self::InvalidSignatureEncoding => "invalid_signature_encoding",
142 Self::SignatureVerification => "signature_verification_failed",
143 Self::NonCanonicalManifest => "non_canonical_manifest",
144 Self::ManifestDigestMismatch => "manifest_digest_mismatch",
145 Self::ManifestIdentityMismatch => "manifest_identity_mismatch",
146 Self::UnsupportedManifest => "unsupported_manifest",
147 Self::UnsupportedSignatureAlgorithm(_) => "unsupported_signature_algorithm",
148 Self::UnknownSignatureKey(_) => "unknown_signature_key",
149 Self::SignatureKeyMismatch => "signature_key_mismatch",
150 Self::UnsafeArchiveEntry(_) => "unsafe_archive_entry",
151 Self::TooManyArchiveEntries { .. } => "too_many_archive_entries",
152 Self::ExtractedSizeExceeded { .. } => "extracted_size_exceeded",
153 Self::UnsafeLibraryPath(_) => "unsafe_library_path",
154 Self::MissingLibrary(_) => "missing_library",
155 Self::Download { .. } => "download_failed",
156 Self::Offline { .. } => "offline",
157 Self::CachedObjectInvalid { .. } => "cached_object_invalid",
158 Self::Cancelled => "cancelled",
159 Self::LibraryLoad { .. } => "library_load_failed",
160 Self::MissingEntrypoint(_) => "missing_entrypoint",
161 Self::EntrypointFailed(_) => "entrypoint_failed",
162 Self::InvalidDescriptor(_) => "invalid_descriptor",
163 Self::IncompatibleAbi { .. } => "incompatible_abi",
164 Self::IdentityMismatch { .. } => "identity_mismatch",
165 Self::ContractHashMismatch => "contract_hash_mismatch",
166 Self::FeatureSetHashMismatch => "feature_set_hash_mismatch",
167 Self::DuplicateLockEntry { .. } => "duplicate_lock_entry",
168 Self::UnsupportedLockSchema(_) => "unsupported_lock_schema",
169 Self::InvalidPublicKey => "invalid_public_key",
170 Self::InvalidContractTable => "invalid_contract_table",
171 Self::MissingInstanceFactory => "missing_instance_factory",
172 Self::MissingInstanceDestructor => "missing_instance_destructor",
173 Self::InstanceCreation { .. } => "instance_creation_failed",
174 Self::NullInstance => "null_instance",
175 Self::InvalidUtf8 => "invalid_utf8",
176 Self::StringTooLong => "string_too_long",
177 Self::UnsupportedTransport(_) => "unsupported_transport",
178 Self::SidecarProtocol(_) => "sidecar_protocol",
179 Self::SidecarTimeout => "sidecar_timeout",
180 Self::SidecarStopped => "sidecar_stopped",
181 Self::SidecarCall { .. } => "sidecar_call_failed",
182 Self::Json(_) => "json_error",
183 Self::Io(_) => "io_error",
184 }
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn code_is_stable_and_distinct_for_representative_variants() {
194 assert_eq!(
195 ComponentError::Offline {
196 component: "demo".into(),
197 url: "https://example.invalid".into(),
198 }
199 .code(),
200 "offline"
201 );
202 assert_eq!(
203 ComponentError::SignatureVerification.code(),
204 "signature_verification_failed"
205 );
206 assert_eq!(
207 ComponentError::BundledComponentNotLoadable {
208 component: "demo".into()
209 }
210 .code(),
211 "bundled_component_not_loadable"
212 );
213 assert_eq!(
214 ComponentError::CachedObjectInvalid {
215 component: "demo".into(),
216 source: Box::new(ComponentError::DigestMismatch {
217 expected: "a".into(),
218 actual: "b".into(),
219 }),
220 }
221 .code(),
222 "cached_object_invalid"
223 );
224 }
225
226 #[test]
227 fn cached_object_invalid_preserves_its_source_chain() {
228 use std::error::Error as _;
229
230 let error = ComponentError::CachedObjectInvalid {
231 component: "demo".into(),
232 source: Box::new(ComponentError::DigestMismatch {
233 expected: "a".into(),
234 actual: "b".into(),
235 }),
236 };
237 let source = error
238 .source()
239 .and_then(|source| source.downcast_ref::<Box<ComponentError>>())
243 .map(|source| source.code());
244 assert_eq!(source, Some("digest_mismatch"));
245 }
246
247 #[test]
248 fn code_never_appears_inside_its_own_display_message_by_accident() {
249 let error = ComponentError::SignatureVerification;
253 assert!(!error.to_string().contains(error.code()));
254 }
255}