Skip to main content

alef_component_runtime/
loader.rs

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/// What a loaded component's descriptor must match.
18///
19/// `contract_name` identifies which of a component's `provides` entries this
20/// is for; `contract_hash` is that specific contract's hash, not the
21/// component-wide legacy `ComponentIdentity::contract_hash`. A component that
22/// provides several contracts is loaded once per contract, each through its
23/// own entry point (see [`crate::ComponentManager::ensure_contract`]), so each
24/// load only ever validates one contract's requirements.
25#[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    /// Keeps the context behind the host table's service callbacks alive with the component.
40    _services: Option<ServicesHandle>,
41    component_id: String,
42    component_version: String,
43}
44
45/// A live instance created by a component, paired with its typed C function table.
46///
47/// Dropping the instance invokes the component's own destructor while the
48/// originating dynamic library remains pinned.
49pub struct ComponentInstance<T: AlefContract> {
50    component: Arc<LoadedComponent>,
51    handle: NonNull<c_void>,
52    _contract: PhantomData<T>,
53}
54
55// SAFETY: native metadata is static and pinned; sidecar metadata is owned and immutable,
56// and its process synchronizes concurrent calls internally. Host callback context thread-safety is part of the
57// `AlefHostApiV1` contract supplied by the caller. ~keep
58unsafe impl Send for LoadedComponent {}
59// SAFETY: as for `Send` above; every shared access is a read of immutable metadata or goes
60// through the sidecar process's own synchronization.
61unsafe impl Sync for LoadedComponent {}
62
63// SAFETY: the C ABI requires every contract method to take `&self` (see
64// `component::map_method`) and calls it through a plain function pointer, so the
65// component's own implementation is the only thing that can make concurrent access
66// unsound; the ABI async wrapper already calls back into an instance from a spawned
67// worker thread, so components are contractually required to tolerate this. The
68// instance handle itself is owned exclusively by this `ComponentInstance` for its
69// lifetime, with no interior aliasing on the host side. ~keep
70unsafe impl<T: AlefContract> Send for ComponentInstance<T> {}
71// SAFETY: as for `Send` above; `&self` methods only read the handle and the validated table,
72// and concurrent calls through the table are the component's contractual obligation.
73unsafe impl<T: AlefContract> Sync for ComponentInstance<T> {}
74
75impl LoadedComponent {
76    /// Load one contract's descriptor from a component's shared library.
77    ///
78    /// A component that provides several contracts exports one entry point
79    /// per contract (`alef_component_entry_v1_<contract>`, see
80    /// `alef::codegen::component::entry_point_symbol`); `entry_symbol` is that
81    /// NUL-terminated symbol name, so this loads exactly one contract's
82    /// descriptor per call even when the underlying `.so`/`.dylib`/`.dll` is
83    /// shared across several `LoadedComponent`s.
84    ///
85    /// `services` is published through the host table's `service_call` / `service_notify`
86    /// callbacks. With `None` the service fields of `host` are passed through unchanged (null by
87    /// default, so components see no service table).
88    ///
89    /// Crate-private: loading runs the library's initializers and entry point, so the only
90    /// caller is [`crate::ComponentManager`], which loads nothing it has not verified against
91    /// the lock first.
92    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        // The verified descriptor's path on Linux, else the checked path (see `identity`).
109        let load_path = verified.library_load_path()?;
110        let library = Arc::new(
111            // SAFETY: loading runs the library's initializers. `load_path` names the file the
112            // cache verified against the signed lock (its descriptor on Linux, a re-checked path
113            // elsewhere), which is the trust decision this crate makes for native code.
114            unsafe { Library::new(&load_path) }.map_err(|error| ComponentError::LibraryLoad {
115                path: verified.path().to_owned(),
116                message: error.to_string(),
117            })?,
118        );
119        // SAFETY: `entry_symbol` names an `alef_component_entry_v1*` export, whose signature the
120        // ABI fixes as `AlefComponentEntryV1`; `library` outlives the symbol, and `host` is a live
121        // `AlefHostApiV1` the call only borrows. The returned pointer is checked for null here and
122        // for size and contents below before any reference is formed over it.
123        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        // Reject a too-small descriptor before a `&AlefComponentV1` reference is ever formed
136        // over it: forming that reference asserts the pointee is valid for
137        // `size_of::<AlefComponentV1>()` bytes, which is undefined behavior when the
138        // component actually returned a shorter, older-ABI struct.
139        // SAFETY: the entry point returned this non-null pointer as its descriptor, which the ABI
140        // requires to start with a readable `struct_size`, and no reference to it exists yet.
141        unsafe { reject_undersized_descriptor(descriptor)? };
142        // SAFETY: the descriptor is at least `size_of::<AlefComponentV1>()` bytes (checked above)
143        // and static in the pinned library; its string fields are the component's own static
144        // metadata, as `validate_descriptor` requires.
145        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    /// Passive liveness probe: true when a sidecar connection is currently running, with no
206    /// healing side effect — unlike [`Self::ensure_active`], it never respawns. Status reporting
207    /// observes; only a real call may spend the restart budget.
208    pub(crate) fn is_active(&self) -> bool {
209        match &self.sidecar {
210            Some((process, _)) => process.is_running(),
211            None => true,
212        }
213    }
214
215    /// Invoke a named bytes-only method on this contract's stdio component.
216    ///
217    /// Native typed function tables require their generated bindings and do not implement
218    /// this operation. Stdio components likewise cannot expose typed C function tables.
219    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        // SAFETY: a native descriptor was size-checked at load and lives in a library pinned for
239        // the process; a sidecar descriptor is owned by `self._sidecar_descriptor`.
240        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    /// Create an instance and bind it to a generated contract-table type.
263    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        // SAFETY: `create` comes from the validated descriptor of a pinned library and takes the
272        // host table this component was loaded with plus two valid out-pointers.
273        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                // SAFETY: the component filled `error` (or left it `EMPTY`) as the ABI's owned
278                // error buffer for this failed call.
279                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        // The table was validated before this instance was constructed.
305        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            // SAFETY: `handle` came from this component's `create` and is destroyed exactly once,
325            // here; the library stays loaded through `self.component`.
326            unsafe { destroy(self.handle.as_ptr()) };
327        }
328    }
329}
330
331/// Copy an owned buffer's bytes into a `Vec<u8>` and release the original allocation through its
332/// own `free` callback.
333///
334/// Generated contract proxies use this to convert a component's `AlefOwnedBuffer` results into
335/// owned Rust values. It is [`alef_component_abi::take_owned_bytes`], re-exported so existing
336/// generated code keeps its `alef_component_runtime::take_owned_bytes` path.
337pub use alef_component_abi::take_owned_bytes;
338
339/// Like [`take_owned_bytes`], but lossily decodes the bytes as UTF-8.
340///
341/// Generated proxies use this to turn a component's error buffer into a
342/// `String` for constructing the contract's error type; a component that
343/// returns non-UTF-8 error text gets a replacement-character message instead
344/// of a panic or a dropped allocation.
345///
346/// # Safety
347///
348/// Same obligations as [`take_owned_bytes`].
349#[must_use]
350pub unsafe fn take_owned_text(buffer: AlefOwnedBuffer) -> String {
351    // SAFETY: upheld by this function's caller contract.
352    String::from_utf8_lossy(&unsafe { take_owned_bytes(buffer) }).into_owned()
353}
354
355/// Decode a component's error buffer as text and release it, tolerating a null pointer.
356///
357/// # Safety
358///
359/// When `buffer.ptr` is non-null it must be valid for reads of `buffer.len` bytes, and `free`
360/// (if present) must be safe to call once with this buffer's own `context`, `ptr`, `len` and
361/// `capacity`.
362unsafe 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        // SAFETY: non-null and valid for `len` bytes per this function's contract.
371        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        // SAFETY: called once with the buffer's own fields, per this function's contract.
375        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    // SAFETY: the table is non-null, aligned for `T`, at least `size_of::<T>()` bytes, and carries
389    // `T`'s contract hash, so it is the `repr(C)` table `T` describes; it lives in a pinned
390    // library for as long as `descriptor` is borrowed.
391    Ok(unsafe { &*descriptor.contract.cast::<T>() })
392}
393
394/// Libraries kept loaded for the rest of the process, one per verified file: function pointers
395/// and registered providers may outlive every `LoadedComponent` that handed them out.
396fn 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
409/// Pin `library` unless the same file is already pinned; returns whether it was added. Loading
410/// another contract from an already-loaded library returns the same OS handle, so one pin per file
411/// is enough, and a long-lived host that re-ensures components no longer grows the list per load.
412fn 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
454// `struct_size` must be a descriptor's first field: only that guarantees a raw read of it
455// never touches memory beyond what the component actually allocated, even when the
456// allocation is shorter than `size_of::<AlefComponentV1>()`. If this ever fails, the raw
457// read in `reject_undersized_descriptor` is no longer sound and must be revisited.
458const _: () = assert!(core::mem::offset_of!(AlefComponentV1, struct_size) == 0);
459
460/// Read a just-returned descriptor's `struct_size` and reject it while it is still smaller
461/// than the current ABI, before a `&AlefComponentV1` reference is formed over it.
462///
463/// # Safety
464///
465/// `descriptor` must be non-null and point to memory valid for reads of at least
466/// `size_of::<usize>()` bytes at `AlefComponentV1`'s alignment; no wider reference to it may
467/// have been formed yet. Both are upheld by [`LoadedComponent::load`]'s caller contract: a
468/// component's entry point must return a pointer to at least a valid `struct_size` field.
469unsafe fn reject_undersized_descriptor(descriptor: NonNull<AlefComponentV1>) -> Result<(), ComponentError> {
470    // SAFETY: upheld by this function's caller contract; `struct_size` sits at offset 0
471    // (asserted above), so this read never reaches past the caller-guaranteed
472    // `size_of::<usize>()` bytes regardless of how large the real descriptor is.
473    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
480/// Check a loaded descriptor against `requirements` and copy out its id and version.
481///
482/// # Safety
483///
484/// Unsafe despite taking a reference: `component_id` and `component_version` are raw `AlefStr`s,
485/// and each must be valid for reads of its `len` bytes whenever `len` is non-zero and at most
486/// [`MAX_DESCRIPTOR_STRING`]; a reference to the descriptor says nothing about what they point
487/// to. A component's entry point guarantees this for the descriptor it returns.
488unsafe 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    // SAFETY: both strings satisfy `copy_abi_str`'s contract per this function's own.
504    let component_id = unsafe { copy_abi_str(descriptor.component_id)? };
505    // SAFETY: as above.
506    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
530/// Copy a component-owned string out as a `String`, refusing more than
531/// [`MAX_DESCRIPTOR_STRING`] bytes, a null pointer with a non-zero length, or invalid UTF-8.
532///
533/// # Safety
534///
535/// When `value.len` is non-zero and at most [`MAX_DESCRIPTOR_STRING`] and `value.ptr` is
536/// non-null, `value.ptr` must be valid for reads of `value.len` bytes. Longer or null values are
537/// rejected before the pointer is read.
538unsafe 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    // SAFETY: non-null, bounded and valid for `len` bytes per this function's contract.
549    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;