1use 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
10pub trait HostServices: Send + Sync {
17 fn call(&self, service: &str, request: &[u8]) -> Result<Vec<u8>, String>;
20
21 fn notify(&self, service: &str, payload: &[u8]);
23}
24
25pub(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 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
46unsafe 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 std::str::from_utf8(unsafe { core::slice::from_raw_parts(value.ptr.cast::<u8>(), value.len) }).ok()
58}
59
60unsafe 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 Some(unsafe { core::slice::from_raw_parts(value.ptr, value.len) })
72}
73
74unsafe 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 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 unsafe { out.write(owned_buffer(bytes)) };
109 status
110}
111
112unsafe 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 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 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 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 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 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}