Skip to main content

alef_component_runtime/
host_services.rs

1//! Host side of the component-to-host service table (`AlefHostApiV1::service_call` /
2//! `service_notify`): a [`HostServices`] trait hosts implement, and the `extern "C"`
3//! trampolines that route a component's calls to it.
4
5use alef_component_abi::{AlefHostApiV1, AlefOwnedBuffer, AlefSlice, AlefStatus, AlefStr, owned_buffer};
6use std::ffi::c_void;
7use std::panic::{AssertUnwindSafe, catch_unwind};
8use std::sync::Arc;
9
10/// Services a host exposes to the components it loads.
11///
12/// The host owns the meaning of `service` names and payload bytes; the ABI only moves bytes.
13/// Components may call from any thread, so implementations must be thread-safe. A panic in an
14/// implementation is caught at the FFI boundary and reported to the component as an error
15/// status, never unwound across it.
16pub trait HostServices: Send + Sync {
17    /// Handle a request/response call. An `Err` message is delivered to the component with an
18    /// `INTERNAL_ERROR` status.
19    fn call(&self, service: &str, request: &[u8]) -> Result<Vec<u8>, String>;
20
21    /// Handle a one-way notification (progress, streaming chunks).
22    fn notify(&self, service: &str, payload: &[u8]);
23}
24
25/// Keeps the `Arc` the table's `services_context` points at alive and at a stable address for
26/// as long as the loaded component exists.
27pub(crate) struct ServicesHandle {
28    services: Box<Arc<dyn HostServices>>,
29}
30
31impl ServicesHandle {
32    pub(crate) fn new(services: Arc<dyn HostServices>) -> Self {
33        Self {
34            services: Box::new(services),
35        }
36    }
37
38    /// Fill the service fields of `host` with this handle's trampolines.
39    pub(crate) fn install(&self, host: &mut AlefHostApiV1) {
40        host.services_context = core::ptr::from_ref(&*self.services).cast_mut().cast();
41        host.service_call = Some(service_call);
42        host.service_notify = Some(service_notify);
43    }
44}
45
46/// # Safety
47///
48/// `value.ptr` must be null or readable for `value.len` bytes.
49unsafe fn str_arg<'a>(value: AlefStr) -> Option<&'a str> {
50    if value.len == 0 {
51        return Some("");
52    }
53    if value.ptr.is_null() {
54        return None;
55    }
56    // SAFETY: upheld by the caller contract.
57    std::str::from_utf8(unsafe { core::slice::from_raw_parts(value.ptr.cast::<u8>(), value.len) }).ok()
58}
59
60/// # Safety
61///
62/// `value.ptr` must be null or readable for `value.len` bytes.
63unsafe fn slice_arg<'a>(value: AlefSlice) -> Option<&'a [u8]> {
64    if value.len == 0 {
65        return Some(&[]);
66    }
67    if value.ptr.is_null() {
68        return None;
69    }
70    // SAFETY: upheld by the caller contract.
71    Some(unsafe { core::slice::from_raw_parts(value.ptr, value.len) })
72}
73
74/// The host table's `service_call` callback.
75///
76/// # Safety
77///
78/// `context` must be null or the `services_context` [`ServicesHandle::install`] published and
79/// still alive; `service` and `request` must be null or readable for their lengths, and `out`
80/// null or writable, as the ABI requires of a component calling it.
81unsafe extern "C" fn service_call(
82    context: *mut c_void,
83    service: AlefStr,
84    request: AlefSlice,
85    out: *mut AlefOwnedBuffer,
86) -> AlefStatus {
87    if context.is_null() || out.is_null() {
88        return AlefStatus::INVALID_ARGUMENT;
89    }
90    // SAFETY: `context` is the `Arc<dyn HostServices>` that `ServicesHandle::install` published,
91    // kept alive by the loaded component; the component's arguments are valid per the ABI.
92    let (services, service, request) = unsafe {
93        (
94            &*context.cast::<Arc<dyn HostServices>>(),
95            str_arg(service),
96            slice_arg(request),
97        )
98    };
99    let (Some(service), Some(request)) = (service, request) else {
100        return AlefStatus::INVALID_ARGUMENT;
101    };
102    let (status, bytes) = match catch_unwind(AssertUnwindSafe(|| services.call(service, request))) {
103        Ok(Ok(bytes)) => (AlefStatus::OK, bytes),
104        Ok(Err(message)) => (AlefStatus::INTERNAL_ERROR, message.into_bytes()),
105        Err(_) => (AlefStatus::INTERNAL_ERROR, b"host service panicked".to_vec()),
106    };
107    // SAFETY: `out` is non-null and writable per the ABI; it holds no live value to drop.
108    unsafe { out.write(owned_buffer(bytes)) };
109    status
110}
111
112/// The host table's `service_notify` callback.
113///
114/// # Safety
115///
116/// As for [`service_call`], without the out-pointer.
117unsafe extern "C" fn service_notify(context: *mut c_void, service: AlefStr, payload: AlefSlice) -> AlefStatus {
118    if context.is_null() {
119        return AlefStatus::INVALID_ARGUMENT;
120    }
121    // SAFETY: see `service_call`.
122    let (services, service, payload) = unsafe {
123        (
124            &*context.cast::<Arc<dyn HostServices>>(),
125            str_arg(service),
126            slice_arg(payload),
127        )
128    };
129    let (Some(service), Some(payload)) = (service, payload) else {
130        return AlefStatus::INVALID_ARGUMENT;
131    };
132    match catch_unwind(AssertUnwindSafe(|| services.notify(service, payload))) {
133        Ok(()) => AlefStatus::OK,
134        Err(_) => AlefStatus::INTERNAL_ERROR,
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use alef_component_abi::HostApi;
142    use alef_component_abi::HostServiceError;
143    use std::sync::Mutex;
144
145    #[derive(Default)]
146    struct Recorder {
147        notes: Mutex<Vec<(String, Vec<u8>)>>,
148    }
149
150    impl HostServices for Recorder {
151        fn call(&self, service: &str, request: &[u8]) -> Result<Vec<u8>, String> {
152            match service {
153                "echo" => Ok(request.to_vec()),
154                "fail" => Err("nope".to_owned()),
155                _ => panic!("unexpected service {service}"),
156            }
157        }
158
159        fn notify(&self, service: &str, payload: &[u8]) {
160            if service == "panic" {
161                panic!("notify panic");
162            }
163            self.notes.lock().unwrap().push((service.to_owned(), payload.to_vec()));
164        }
165    }
166
167    fn host_for(recorder: &Arc<Recorder>) -> (ServicesHandle, AlefHostApiV1) {
168        let handle = ServicesHandle::new(Arc::clone(recorder) as Arc<dyn HostServices>);
169        let mut raw = AlefHostApiV1::EMPTY;
170        handle.install(&mut raw);
171        (handle, raw)
172    }
173
174    #[test]
175    fn trampolines_route_calls_and_notifications_to_the_registered_services() {
176        let recorder = Arc::new(Recorder::default());
177        let (_handle, raw) = host_for(&recorder);
178        // SAFETY: `raw` is a complete, live host table.
179        let api = unsafe { HostApi::from_raw(&raw) };
180        assert_eq!(api.call_service("echo", b"hello").unwrap(), b"hello");
181        assert_eq!(api.call_service("echo", b"").unwrap(), b"");
182        api.notify("progress", b"1/2").unwrap();
183        assert_eq!(
184            *recorder.notes.lock().unwrap(),
185            [("progress".to_owned(), b"1/2".to_vec())]
186        );
187    }
188
189    #[test]
190    fn host_errors_reach_the_component_as_internal_error_with_the_message() {
191        let recorder = Arc::new(Recorder::default());
192        let (_handle, raw) = host_for(&recorder);
193        // SAFETY: as above.
194        let api = unsafe { HostApi::from_raw(&raw) };
195        assert_eq!(
196            api.call_service("fail", b"").unwrap_err(),
197            HostServiceError::Failed {
198                status: AlefStatus::INTERNAL_ERROR,
199                message: "nope".to_owned(),
200            }
201        );
202    }
203
204    #[test]
205    fn panics_in_host_callbacks_become_error_statuses() {
206        let recorder = Arc::new(Recorder::default());
207        let (_handle, raw) = host_for(&recorder);
208        // SAFETY: as above.
209        let api = unsafe { HostApi::from_raw(&raw) };
210        assert_eq!(
211            api.call_service("boom", b"").unwrap_err(),
212            HostServiceError::Failed {
213                status: AlefStatus::INTERNAL_ERROR,
214                message: "host service panicked".to_owned(),
215            }
216        );
217        assert!(matches!(
218            api.notify("panic", b""),
219            Err(HostServiceError::Failed {
220                status: AlefStatus::INTERNAL_ERROR,
221                ..
222            })
223        ));
224    }
225
226    #[test]
227    fn invalid_utf8_service_names_are_rejected() {
228        let recorder = Arc::new(Recorder::default());
229        let (_handle, raw) = host_for(&recorder);
230        let bad = [0xff_u8, 0xfe];
231        let name = AlefStr {
232            ptr: bad.as_ptr().cast(),
233            len: bad.len(),
234        };
235        let mut out = AlefOwnedBuffer::EMPTY;
236        let call = raw.service_call.unwrap();
237        // SAFETY: the table is live and the arguments are valid for the call.
238        let status = unsafe { call(raw.services_context, name, AlefSlice::EMPTY, &mut out) };
239        assert_eq!(status, AlefStatus::INVALID_ARGUMENT);
240        assert!(out.ptr.is_null());
241    }
242}