Skip to main content

alef_component_runtime/
proxy_support.rs

1//! Support for the contract proxies `alef` generates over native components.
2//!
3//! A contract method that cannot fail in Rust (its trait signature returns a plain value) still
4//! crosses a C ABI that returns a status. When a component reports a failure there, the generated
5//! proxy cannot return an error, and panicking would take the host down for one misbehaving
6//! component. It reports the failure through [`report_infallible_failure`] and returns the
7//! result type's `Default` value instead (empty string, empty bytes, zero, `false`, `()`).
8//!
9//! Hosts observe or escalate these failures with [`set_infallible_failure_hook`]; without a hook
10//! each one is written to stderr. ADR-0029 records the decision.
11
12use std::sync::{Arc, PoisonError, RwLock};
13
14/// A native component reported a failure from a contract method whose Rust signature cannot
15/// return an error.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct InfallibleCallFailure<'a> {
19    /// The component id from its descriptor.
20    pub component: &'a str,
21    /// The contract method, in the trait's snake_case spelling.
22    pub method: &'a str,
23    /// The non-OK `AlefStatus` code the component returned.
24    pub status: i32,
25    /// The component's error message, lossily decoded as UTF-8.
26    pub message: &'a str,
27}
28
29impl<'a> InfallibleCallFailure<'a> {
30    /// Describe one failure; generated proxies call this.
31    #[must_use]
32    pub fn new(component: &'a str, method: &'a str, status: i32, message: &'a str) -> Self {
33        Self {
34            component,
35            method,
36            status,
37            message,
38        }
39    }
40}
41
42type Hook = Arc<dyn Fn(&InfallibleCallFailure<'_>) + Send + Sync>;
43
44static HOOK: RwLock<Option<Hook>> = RwLock::new(None);
45
46/// Replace the process-wide handler for [`InfallibleCallFailure`]s. The handler runs on the
47/// calling thread, before the proxy returns the default value; it may log, count, or panic if the
48/// host prefers to abort. It must not call back into the failing proxy.
49pub fn set_infallible_failure_hook(hook: impl Fn(&InfallibleCallFailure<'_>) + Send + Sync + 'static) {
50    *HOOK.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(hook));
51}
52
53/// Report a failure of an infallible contract method: to the hook set with
54/// [`set_infallible_failure_hook`], or to stderr when none is set. Generated proxies call this and
55/// then return the method's default value.
56pub fn report_infallible_failure(failure: &InfallibleCallFailure<'_>) {
57    let hook = HOOK.read().unwrap_or_else(PoisonError::into_inner).clone();
58    match hook {
59        Some(hook) => hook(failure),
60        None => eprintln!(
61            "alef component `{}`: method `{}` failed with status {}: {}; returning its default value",
62            failure.component, failure.method, failure.status, failure.message
63        ),
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70    use std::sync::Mutex;
71
72    #[test]
73    fn the_hook_receives_each_failure() {
74        let seen = Arc::new(Mutex::new(Vec::new()));
75        {
76            let seen = Arc::clone(&seen);
77            set_infallible_failure_hook(move |failure| {
78                seen.lock().unwrap().push((
79                    failure.component.to_owned(),
80                    failure.method.to_owned(),
81                    failure.status,
82                    failure.message.to_owned(),
83                ));
84            });
85        }
86        report_infallible_failure(&InfallibleCallFailure::new("demo", "name", 5, "broken"));
87        assert!(
88            seen.lock()
89                .unwrap()
90                .contains(&("demo".to_owned(), "name".to_owned(), 5, "broken".to_owned()))
91        );
92    }
93}