1use alef_component_abi::{AlefHostApiV1, AlefOwnedBuffer, AlefSlice, AlefStatus, AlefStr};
6use std::ffi::c_void;
7use std::mem::ManuallyDrop;
8use std::panic::{AssertUnwindSafe, catch_unwind};
9use std::sync::Arc;
10
11pub trait HostServices: Send + Sync {
18 fn call(&self, service: &str, request: &[u8]) -> Result<Vec<u8>, String>;
21
22 fn notify(&self, service: &str, payload: &[u8]);
24}
25
26pub(crate) struct ServicesHandle {
29 services: Box<Arc<dyn HostServices>>,
30}
31
32impl ServicesHandle {
33 pub(crate) fn new(services: Arc<dyn HostServices>) -> Self {
34 Self {
35 services: Box::new(services),
36 }
37 }
38
39 pub(crate) fn install(&self, host: &mut AlefHostApiV1) {
41 host.services_context = core::ptr::from_ref(&*self.services).cast_mut().cast();
42 host.service_call = Some(service_call);
43 host.service_notify = Some(service_notify);
44 }
45}
46
47unsafe extern "C" fn free_vec(_context: *mut c_void, ptr: *mut u8, len: usize, capacity: usize) {
48 drop(unsafe { Vec::from_raw_parts(ptr, len, capacity) });
50}
51
52fn owned_buffer(bytes: Vec<u8>) -> AlefOwnedBuffer {
53 let mut bytes = ManuallyDrop::new(bytes);
54 AlefOwnedBuffer {
55 ptr: bytes.as_mut_ptr(),
56 len: bytes.len(),
57 capacity: bytes.capacity(),
58 context: core::ptr::null_mut(),
59 free: Some(free_vec),
60 }
61}
62
63unsafe fn str_arg<'a>(value: AlefStr) -> Option<&'a str> {
67 if value.len == 0 {
68 return Some("");
69 }
70 if value.ptr.is_null() {
71 return None;
72 }
73 std::str::from_utf8(unsafe { core::slice::from_raw_parts(value.ptr.cast::<u8>(), value.len) }).ok()
75}
76
77unsafe fn slice_arg<'a>(value: AlefSlice) -> Option<&'a [u8]> {
81 if value.len == 0 {
82 return Some(&[]);
83 }
84 if value.ptr.is_null() {
85 return None;
86 }
87 Some(unsafe { core::slice::from_raw_parts(value.ptr, value.len) })
89}
90
91unsafe extern "C" fn service_call(
92 context: *mut c_void,
93 service: AlefStr,
94 request: AlefSlice,
95 out: *mut AlefOwnedBuffer,
96) -> AlefStatus {
97 if context.is_null() || out.is_null() {
98 return AlefStatus::INVALID_ARGUMENT;
99 }
100 let (services, service, request) = unsafe {
103 (
104 &*context.cast::<Arc<dyn HostServices>>(),
105 str_arg(service),
106 slice_arg(request),
107 )
108 };
109 let (Some(service), Some(request)) = (service, request) else {
110 return AlefStatus::INVALID_ARGUMENT;
111 };
112 let (status, bytes) = match catch_unwind(AssertUnwindSafe(|| services.call(service, request))) {
113 Ok(Ok(bytes)) => (AlefStatus::OK, bytes),
114 Ok(Err(message)) => (AlefStatus::INTERNAL_ERROR, message.into_bytes()),
115 Err(_) => (AlefStatus::INTERNAL_ERROR, b"host service panicked".to_vec()),
116 };
117 unsafe { out.write(owned_buffer(bytes)) };
119 status
120}
121
122unsafe extern "C" fn service_notify(context: *mut c_void, service: AlefStr, payload: AlefSlice) -> AlefStatus {
123 if context.is_null() {
124 return AlefStatus::INVALID_ARGUMENT;
125 }
126 let (services, service, payload) = unsafe {
128 (
129 &*context.cast::<Arc<dyn HostServices>>(),
130 str_arg(service),
131 slice_arg(payload),
132 )
133 };
134 let (Some(service), Some(payload)) = (service, payload) else {
135 return AlefStatus::INVALID_ARGUMENT;
136 };
137 match catch_unwind(AssertUnwindSafe(|| services.notify(service, payload))) {
138 Ok(()) => AlefStatus::OK,
139 Err(_) => AlefStatus::INTERNAL_ERROR,
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146 use alef_component_abi::HostApi;
147 use alef_component_abi::HostServiceError;
148 use std::sync::Mutex;
149
150 #[derive(Default)]
151 struct Recorder {
152 notes: Mutex<Vec<(String, Vec<u8>)>>,
153 }
154
155 impl HostServices for Recorder {
156 fn call(&self, service: &str, request: &[u8]) -> Result<Vec<u8>, String> {
157 match service {
158 "echo" => Ok(request.to_vec()),
159 "fail" => Err("nope".to_owned()),
160 _ => panic!("unexpected service {service}"),
161 }
162 }
163
164 fn notify(&self, service: &str, payload: &[u8]) {
165 if service == "panic" {
166 panic!("notify panic");
167 }
168 self.notes.lock().unwrap().push((service.to_owned(), payload.to_vec()));
169 }
170 }
171
172 fn host_for(recorder: &Arc<Recorder>) -> (ServicesHandle, AlefHostApiV1) {
173 let handle = ServicesHandle::new(Arc::clone(recorder) as Arc<dyn HostServices>);
174 let mut raw = AlefHostApiV1::EMPTY;
175 handle.install(&mut raw);
176 (handle, raw)
177 }
178
179 #[test]
180 fn trampolines_route_calls_and_notifications_to_the_registered_services() {
181 let recorder = Arc::new(Recorder::default());
182 let (_handle, raw) = host_for(&recorder);
183 let api = unsafe { HostApi::from_raw(&raw) };
185 assert_eq!(api.call_service("echo", b"hello").unwrap(), b"hello");
186 assert_eq!(api.call_service("echo", b"").unwrap(), b"");
187 api.notify("progress", b"1/2").unwrap();
188 assert_eq!(
189 *recorder.notes.lock().unwrap(),
190 [("progress".to_owned(), b"1/2".to_vec())]
191 );
192 }
193
194 #[test]
195 fn host_errors_reach_the_component_as_internal_error_with_the_message() {
196 let recorder = Arc::new(Recorder::default());
197 let (_handle, raw) = host_for(&recorder);
198 let api = unsafe { HostApi::from_raw(&raw) };
200 assert_eq!(
201 api.call_service("fail", b"").unwrap_err(),
202 HostServiceError::Failed {
203 status: AlefStatus::INTERNAL_ERROR,
204 message: "nope".to_owned(),
205 }
206 );
207 }
208
209 #[test]
210 fn panics_in_host_callbacks_become_error_statuses() {
211 let recorder = Arc::new(Recorder::default());
212 let (_handle, raw) = host_for(&recorder);
213 let api = unsafe { HostApi::from_raw(&raw) };
215 assert_eq!(
216 api.call_service("boom", b"").unwrap_err(),
217 HostServiceError::Failed {
218 status: AlefStatus::INTERNAL_ERROR,
219 message: "host service panicked".to_owned(),
220 }
221 );
222 assert!(matches!(
223 api.notify("panic", b""),
224 Err(HostServiceError::Failed {
225 status: AlefStatus::INTERNAL_ERROR,
226 ..
227 })
228 ));
229 }
230
231 #[test]
232 fn invalid_utf8_service_names_are_rejected() {
233 let recorder = Arc::new(Recorder::default());
234 let (_handle, raw) = host_for(&recorder);
235 let bad = [0xff_u8, 0xfe];
236 let name = AlefStr {
237 ptr: bad.as_ptr().cast(),
238 len: bad.len(),
239 };
240 let mut out = AlefOwnedBuffer::EMPTY;
241 let call = raw.service_call.unwrap();
242 let status = unsafe { call(raw.services_context, name, AlefSlice::EMPTY, &mut out) };
244 assert_eq!(status, AlefStatus::INVALID_ARGUMENT);
245 assert!(out.ptr.is_null());
246 }
247}