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