1use crate::host_services::ServicesHandle;
2use crate::identity::{FileIdentity, VerifiedFile};
3use crate::stdio::SidecarProcess;
4use crate::{COMPONENT_ABI_VERSION, COMPONENT_MANIFEST_SCHEMA, ComponentError, ComponentManifest, HostServices};
5use alef_component_abi::{
6 ABI_MAJOR_V1, ABI_MINOR_V1, AlefComponentEntryV1, AlefComponentV1, AlefContract, AlefHostApiV1, AlefOwnedBuffer,
7};
8use libloading::Library;
9use std::collections::HashMap;
10use std::ffi::c_void;
11use std::marker::PhantomData;
12use std::ptr::NonNull;
13use std::sync::{Arc, Mutex, OnceLock};
14
15const MAX_DESCRIPTOR_STRING: usize = 16 * 1024;
16
17#[derive(Clone, Debug)]
26pub struct ComponentRequirements {
27 pub component_id: String,
28 pub contract_name: String,
29 pub contract_hash: [u8; 32],
30 pub feature_set_hash: Option<[u8; 32]>,
31}
32
33pub struct LoadedComponent {
34 library: Option<Arc<Library>>,
35 sidecar: Option<(Arc<SidecarProcess>, String)>,
36 _sidecar_descriptor: Option<Box<AlefComponentV1>>,
37 descriptor: NonNull<AlefComponentV1>,
38 host: Box<AlefHostApiV1>,
39 _services: Option<ServicesHandle>,
41 component_id: String,
42 component_version: String,
43}
44
45pub struct ComponentInstance<T: AlefContract> {
50 component: Arc<LoadedComponent>,
51 handle: NonNull<c_void>,
52 _contract: PhantomData<T>,
53}
54
55unsafe impl Send for LoadedComponent {}
59unsafe impl Sync for LoadedComponent {}
62
63unsafe impl<T: AlefContract> Send for ComponentInstance<T> {}
71unsafe impl<T: AlefContract> Sync for ComponentInstance<T> {}
74
75impl LoadedComponent {
76 pub(crate) fn load_with_services(
93 verified: &VerifiedFile,
94 entry_symbol: &[u8],
95 requirements: &ComponentRequirements,
96 mut host: AlefHostApiV1,
97 services: Option<Arc<dyn HostServices>>,
98 ) -> Result<Self, ComponentError> {
99 host.struct_size = core::mem::size_of::<AlefHostApiV1>();
100 host.abi_major = ABI_MAJOR_V1;
101 host.abi_minor = ABI_MINOR_V1;
102 let services = services.map(ServicesHandle::new);
103 if let Some(handle) = &services {
104 handle.install(&mut host);
105 }
106 let host = Box::new(host);
107
108 let load_path = verified.library_load_path()?;
110 let library = Arc::new(
111 unsafe { Library::new(&load_path) }.map_err(|error| ComponentError::LibraryLoad {
115 path: verified.path().to_owned(),
116 message: error.to_string(),
117 })?,
118 );
119 let descriptor = unsafe {
124 let entry: libloading::Symbol<'_, AlefComponentEntryV1> = library
125 .get(entry_symbol)
126 .map_err(|error| ComponentError::MissingEntrypoint(error.to_string()))?;
127 let mut raw = core::ptr::null();
128 let status = entry(ABI_MAJOR_V1, host.as_ref(), &mut raw);
129 if !status.is_ok() {
130 return Err(ComponentError::EntrypointFailed(status.0));
131 }
132 NonNull::new(raw.cast_mut()).ok_or(ComponentError::InvalidDescriptor("null descriptor"))?
133 };
134
135 unsafe { reject_undersized_descriptor(descriptor)? };
142 let validated = unsafe { validate_descriptor(descriptor.as_ref(), requirements)? };
146 pin_for_process(verified.identity(), Arc::clone(&library));
147 Ok(Self {
148 library: Some(library),
149 sidecar: None,
150 _sidecar_descriptor: None,
151 descriptor,
152 host,
153 _services: services,
154 component_id: validated.0,
155 component_version: validated.1,
156 })
157 }
158
159 pub(crate) fn from_sidecar(
160 process: Arc<SidecarProcess>,
161 manifest: &ComponentManifest,
162 requirements: &ComponentRequirements,
163 host: AlefHostApiV1,
164 ) -> Result<Self, ComponentError> {
165 let component_id = manifest.identity.component.clone();
166 let component_version = manifest.identity.version.clone();
167 let mut descriptor = Box::new(AlefComponentV1 {
168 struct_size: core::mem::size_of::<AlefComponentV1>(),
169 abi_major: ABI_MAJOR_V1,
170 abi_minor: ABI_MINOR_V1,
171 component_id: alef_component_abi::AlefStr {
172 ptr: component_id.as_ptr().cast(),
173 len: component_id.len(),
174 },
175 component_version: alef_component_abi::AlefStr {
176 ptr: component_version.as_ptr().cast(),
177 len: component_version.len(),
178 },
179 contract_hash: requirements.contract_hash,
180 feature_set_hash: decode_hash(&manifest.identity.feature_hash)?,
181 contract: core::ptr::null(),
182 contract_size: 0,
183 create: None,
184 destroy: None,
185 });
186 Ok(Self {
187 library: None,
188 sidecar: Some((process, requirements.contract_name.clone())),
189 descriptor: NonNull::from(descriptor.as_mut()),
190 _sidecar_descriptor: Some(descriptor),
191 host: Box::new(host),
192 _services: None,
193 component_id,
194 component_version,
195 })
196 }
197
198 pub(crate) fn ensure_active(&self) -> Result<(), ComponentError> {
199 if let Some((process, _)) = &self.sidecar {
200 process.ensure_running()?;
201 }
202 Ok(())
203 }
204
205 pub(crate) fn is_active(&self) -> bool {
209 match &self.sidecar {
210 Some((process, _)) => process.is_running(),
211 None => true,
212 }
213 }
214
215 pub fn invoke_bytes(&self, method: &str, payload: &[u8]) -> Result<Vec<u8>, ComponentError> {
220 let (process, contract) = self.sidecar.as_ref().ok_or(ComponentError::UnsupportedTransport(
221 "bytes invocation requires a stdio component",
222 ))?;
223 process.invoke(contract, method, payload)
224 }
225
226 #[must_use]
227 pub fn component_id(&self) -> &str {
228 &self.component_id
229 }
230
231 #[must_use]
232 pub fn component_version(&self) -> &str {
233 &self.component_version
234 }
235
236 #[must_use]
237 pub fn descriptor(&self) -> &AlefComponentV1 {
238 unsafe { self.descriptor.as_ref() }
241 }
242
243 #[must_use]
244 pub fn contract(&self) -> *const c_void {
245 self.descriptor().contract
246 }
247
248 #[must_use]
249 pub fn contract_size(&self) -> usize {
250 self.descriptor().contract_size
251 }
252
253 pub fn contract_table<T: AlefContract>(&self) -> Result<&T, ComponentError> {
254 if self.sidecar.is_some() {
255 return Err(ComponentError::UnsupportedTransport(
256 "stdio components support bytes invocation, not typed C function tables",
257 ));
258 }
259 contract_table_from_descriptor(self.descriptor())
260 }
261
262 pub fn instantiate<T: AlefContract>(self: &Arc<Self>) -> Result<ComponentInstance<T>, ComponentError> {
264 self.contract_table::<T>()?;
265 let create = self.descriptor().create.ok_or(ComponentError::MissingInstanceFactory)?;
266 self.descriptor()
267 .destroy
268 .ok_or(ComponentError::MissingInstanceDestructor)?;
269 let mut raw = core::ptr::null_mut();
270 let mut error = AlefOwnedBuffer::EMPTY;
271 let status = unsafe { create(self.host_api(), &mut raw, &mut error) };
274 if !status.is_ok() {
275 return Err(ComponentError::InstanceCreation {
276 status: status.0,
277 message: unsafe { take_owned_buffer(error) },
280 });
281 }
282 let handle = NonNull::new(raw).ok_or(ComponentError::NullInstance)?;
283 Ok(ComponentInstance {
284 component: Arc::clone(self),
285 handle,
286 _contract: PhantomData,
287 })
288 }
289
290 #[must_use]
291 pub fn host_api(&self) -> &AlefHostApiV1 {
292 &self.host
293 }
294
295 #[must_use]
296 pub fn strong_library_references(&self) -> usize {
297 self.library.as_ref().map_or(0, Arc::strong_count)
298 }
299}
300
301impl<T: AlefContract> ComponentInstance<T> {
302 #[must_use]
303 pub fn table(&self) -> &T {
304 self.component
306 .contract_table::<T>()
307 .expect("validated component contract table changed")
308 }
309
310 #[must_use]
311 pub fn handle(&self) -> *mut c_void {
312 self.handle.as_ptr()
313 }
314
315 #[must_use]
316 pub fn component(&self) -> &Arc<LoadedComponent> {
317 &self.component
318 }
319}
320
321impl<T: AlefContract> Drop for ComponentInstance<T> {
322 fn drop(&mut self) {
323 if let Some(destroy) = self.component.descriptor().destroy {
324 unsafe { destroy(self.handle.as_ptr()) };
327 }
328 }
329}
330
331pub use alef_component_abi::take_owned_bytes;
338
339#[must_use]
350pub unsafe fn take_owned_text(buffer: AlefOwnedBuffer) -> String {
351 String::from_utf8_lossy(&unsafe { take_owned_bytes(buffer) }).into_owned()
353}
354
355unsafe fn take_owned_buffer(buffer: AlefOwnedBuffer) -> String {
363 let message = if buffer.ptr.is_null() {
364 if buffer.len == 0 {
365 String::new()
366 } else {
367 "component returned an invalid error buffer".to_string()
368 }
369 } else {
370 String::from_utf8_lossy(unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }).into_owned()
372 };
373 if let Some(free) = buffer.free {
374 unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
376 }
377 message
378}
379
380fn contract_table_from_descriptor<T: AlefContract>(descriptor: &AlefComponentV1) -> Result<&T, ComponentError> {
381 if descriptor.contract_hash != T::CONTRACT_HASH
382 || descriptor.contract_size < core::mem::size_of::<T>()
383 || descriptor.contract.is_null()
384 || !(descriptor.contract as usize).is_multiple_of(core::mem::align_of::<T>())
385 {
386 return Err(ComponentError::InvalidContractTable);
387 }
388 Ok(unsafe { &*descriptor.contract.cast::<T>() })
392}
393
394fn process_pins() -> &'static Mutex<HashMap<FileIdentity, Arc<Library>>> {
397 static PINS: OnceLock<Mutex<HashMap<FileIdentity, Arc<Library>>>> = OnceLock::new();
398 PINS.get_or_init(|| Mutex::new(HashMap::new()))
399}
400
401fn pin_for_process(identity: FileIdentity, library: Arc<Library>) {
402 pin_into(
403 &mut process_pins().lock().unwrap_or_else(|poisoned| poisoned.into_inner()),
404 identity,
405 library,
406 );
407}
408
409fn pin_into(pins: &mut HashMap<FileIdentity, Arc<Library>>, identity: FileIdentity, library: Arc<Library>) -> bool {
413 match pins.entry(identity) {
414 std::collections::hash_map::Entry::Occupied(_) => false,
415 std::collections::hash_map::Entry::Vacant(slot) => {
416 slot.insert(library);
417 true
418 }
419 }
420}
421
422pub(crate) fn validate_manifest(
423 manifest: &ComponentManifest,
424 requirements: &ComponentRequirements,
425) -> Result<(), ComponentError> {
426 if manifest.schema_version != COMPONENT_MANIFEST_SCHEMA || manifest.abi_version != COMPONENT_ABI_VERSION {
427 return Err(ComponentError::UnsupportedManifest);
428 }
429 if manifest.identity.component != requirements.component_id {
430 return Err(ComponentError::IdentityMismatch {
431 expected: requirements.component_id.clone(),
432 actual: manifest.identity.component.clone(),
433 });
434 }
435 let provided = manifest
436 .provides
437 .iter()
438 .find(|provided| provided.contract == requirements.contract_name)
439 .ok_or_else(|| ComponentError::ContractNotProvided {
440 component_id: requirements.component_id.clone(),
441 contract: requirements.contract_name.clone(),
442 })?;
443 if decode_hash(&provided.contract_hash)? != requirements.contract_hash {
444 return Err(ComponentError::ContractHashMismatch);
445 }
446 if let Some(expected) = requirements.feature_set_hash
447 && decode_hash(&manifest.identity.feature_hash)? != expected
448 {
449 return Err(ComponentError::FeatureSetHashMismatch);
450 }
451 Ok(())
452}
453
454const _: () = assert!(core::mem::offset_of!(AlefComponentV1, struct_size) == 0);
459
460unsafe fn reject_undersized_descriptor(descriptor: NonNull<AlefComponentV1>) -> Result<(), ComponentError> {
470 let struct_size = unsafe { descriptor.as_ptr().cast::<usize>().read_unaligned() };
474 if struct_size < core::mem::size_of::<AlefComponentV1>() {
475 return Err(ComponentError::InvalidDescriptor("descriptor is smaller than ABI v1"));
476 }
477 Ok(())
478}
479
480unsafe fn validate_descriptor(
489 descriptor: &AlefComponentV1,
490 requirements: &ComponentRequirements,
491) -> Result<(String, String), ComponentError> {
492 if descriptor.struct_size < core::mem::size_of::<AlefComponentV1>() {
493 return Err(ComponentError::InvalidDescriptor("descriptor is smaller than ABI v1"));
494 }
495 if descriptor.abi_major != ABI_MAJOR_V1 || descriptor.abi_minor > ABI_MINOR_V1 {
496 return Err(ComponentError::IncompatibleAbi {
497 expected_major: ABI_MAJOR_V1,
498 expected_minor: ABI_MINOR_V1,
499 actual_major: descriptor.abi_major,
500 actual_minor: descriptor.abi_minor,
501 });
502 }
503 let component_id = unsafe { copy_abi_str(descriptor.component_id)? };
505 let component_version = unsafe { copy_abi_str(descriptor.component_version)? };
507 if component_id != requirements.component_id {
508 return Err(ComponentError::IdentityMismatch {
509 expected: requirements.component_id.clone(),
510 actual: component_id,
511 });
512 }
513 if descriptor.contract_hash != requirements.contract_hash {
514 return Err(ComponentError::ContractHashMismatch);
515 }
516 if requirements
517 .feature_set_hash
518 .is_some_and(|expected| descriptor.feature_set_hash != expected)
519 {
520 return Err(ComponentError::FeatureSetHashMismatch);
521 }
522 if descriptor.contract_size > 0 && descriptor.contract.is_null() {
523 return Err(ComponentError::InvalidDescriptor(
524 "non-empty contract has a null pointer",
525 ));
526 }
527 Ok((component_id, component_version))
528}
529
530unsafe fn copy_abi_str(value: alef_component_abi::AlefStr) -> Result<String, ComponentError> {
539 if value.len > MAX_DESCRIPTOR_STRING {
540 return Err(ComponentError::StringTooLong);
541 }
542 if value.len == 0 {
543 return Ok(String::new());
544 }
545 if value.ptr.is_null() {
546 return Err(ComponentError::InvalidDescriptor("non-empty string has a null pointer"));
547 }
548 let bytes = unsafe { core::slice::from_raw_parts(value.ptr.cast::<u8>(), value.len) };
550 let text = core::str::from_utf8(bytes).map_err(|_| ComponentError::InvalidUtf8)?;
551 Ok(text.to_owned())
552}
553
554pub(crate) fn decode_hash(value: &str) -> Result<[u8; 32], ComponentError> {
555 let bytes = hex::decode(value).map_err(|_| ComponentError::InvalidDigest(value.to_owned()))?;
556 bytes
557 .try_into()
558 .map_err(|_| ComponentError::InvalidDigest(value.to_owned()))
559}
560
561#[cfg(test)]
562mod tests;