1use std::{collections::HashMap, sync::Arc};
8
9use anyhow::Result;
10use bytes::Bytes;
11use serde::{Serialize, de::DeserializeOwned};
12use tokio::sync::{RwLock, mpsc, oneshot};
13use crate::dev_log;
14#[allow(unused_imports)]
15use wasmtime::{Caller, Extern, Func, Linker, Store};
16
17#[derive(Debug, thiserror::Error)]
19pub enum BridgeError {
20 #[error("Function not found: {0}")]
22 FunctionNotFound(String),
23
24 #[error("Invalid function signature: {0}")]
26 InvalidSignature(String),
27
28 #[error("Serialization failed: {0}")]
30 SerializationError(String),
31
32 #[error("Deserialization failed: {0}")]
34 DeserializationError(String),
35
36 #[error("Host function error: {0}")]
38 HostFunctionError(String),
39
40 #[error("Communication timeout")]
42 Timeout,
43
44 #[error("Bridge closed")]
46 BridgeClosed,
47}
48
49pub type BridgeResult<T> = Result<T, BridgeError>;
51
52#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
54pub struct FunctionSignature {
55 pub name:String,
57 pub param_types:Vec<ParamType>,
59 pub return_type:Option<ReturnType>,
61 pub is_async:bool,
63}
64
65#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
67pub enum ParamType {
68 I32,
70 I64,
72 F32,
74 F64,
76 Ptr,
78 Len,
80}
81
82#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
84pub enum ReturnType {
85 I32,
87 I64,
89 F32,
91 F64,
93 Void,
95}
96
97#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
99pub struct HostMessage {
100 pub message_id:String,
102 pub function:String,
104 pub args:Vec<Bytes>,
106 pub callback_token:Option<u64>,
108}
109
110#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
112pub struct HostResponse {
113 pub message_id:String,
115 pub success:bool,
117 pub data:Option<Bytes>,
119 pub error:Option<String>,
121}
122
123#[derive(Clone)]
125pub struct AsyncCallback {
126 sender:Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<HostResponse>>>>,
128 message_id:String,
130}
131
132impl std::fmt::Debug for AsyncCallback {
133 fn fmt(&self, f:&mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 f.debug_struct("AsyncCallback").field("message_id", &self.message_id).finish()
135 }
136}
137
138impl AsyncCallback {
139 pub async fn send(self, response:HostResponse) -> Result<()> {
141 let mut sender_opt = self.sender.lock().await;
142 if let Some(sender) = sender_opt.take() {
143 sender.send(response).map_err(|_| BridgeError::BridgeClosed)?;
144 Ok(())
145 } else {
146 Err(BridgeError::BridgeClosed.into())
147 }
148 }
149}
150
151#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
153pub struct WASMMessage {
154 pub function:String,
156 pub args:Vec<Bytes>,
158}
159
160pub type HostFunctionCallback = fn(Vec<Bytes>) -> Result<Bytes>;
162
163pub type AsyncHostFunctionCallback =
165 fn(Vec<Bytes>) -> Box<dyn std::future::Future<Output = Result<Bytes>> + Send + Unpin>;
166
167#[derive(Debug)]
169pub struct HostFunction {
170 pub name:String,
172 pub signature:FunctionSignature,
174 #[allow(dead_code)]
176 pub callback:Option<HostFunctionCallback>,
177 #[allow(dead_code)]
179 pub async_callback:Option<AsyncHostFunctionCallback>,
180}
181
182#[derive(Debug)]
184pub struct HostBridgeImpl {
185 host_functions:Arc<RwLock<HashMap<String, HostFunction>>>,
187 wasm_to_host_rx:mpsc::UnboundedReceiver<WASMMessage>,
189 host_to_wasm_tx:mpsc::UnboundedSender<WASMMessage>,
191 async_callbacks:Arc<RwLock<HashMap<u64, AsyncCallback>>>,
193 next_callback_token:Arc<std::sync::atomic::AtomicU64>,
195}
196
197impl HostBridgeImpl {
198 pub fn new() -> Self {
200 let (_wasm_to_host_tx, wasm_to_host_rx) = mpsc::unbounded_channel();
201 let (host_to_wasm_tx, host_to_wasm_rx) = mpsc::unbounded_channel();
202
203 drop(host_to_wasm_rx);
206
207 Self {
208 host_functions:Arc::new(RwLock::new(HashMap::new())),
209 wasm_to_host_rx,
210 host_to_wasm_tx,
211 async_callbacks:Arc::new(RwLock::new(HashMap::new())),
212 next_callback_token:Arc::new(std::sync::atomic::AtomicU64::new(0)),
213 }
214 }
215
216 pub async fn register_host_function(
218 &self,
219 name:&str,
220 signature:FunctionSignature,
221 callback:HostFunctionCallback,
222 ) -> BridgeResult<()> {
223 dev_log!("wasm", "Registering host function: {}", name);
224
225 let mut functions = self.host_functions.write().await;
226
227 if functions.contains_key(name) {
228 dev_log!("wasm", "warn: host function already registered: {}", name);
229 }
230
231 functions.insert(
232 name.to_string(),
233 HostFunction { name:name.to_string(), signature, callback:Some(callback), async_callback:None },
234 );
235
236 dev_log!("wasm", "Host function registered successfully: {}", name);
237 Ok(())
238 }
239
240 pub async fn register_async_host_function(
242 &self,
243 name:&str,
244 signature:FunctionSignature,
245 callback:AsyncHostFunctionCallback,
246 ) -> BridgeResult<()> {
247 dev_log!("wasm", "Registering async host function: {}", name);
248
249 let mut functions = self.host_functions.write().await;
250
251 functions.insert(
252 name.to_string(),
253 HostFunction { name:name.to_string(), signature, callback:None, async_callback:Some(callback) },
254 );
255
256 dev_log!("wasm", "Async host function registered successfully: {}", name);
257 Ok(())
258 }
259
260 pub async fn call_host_function(&self, function_name:&str, args:Vec<Bytes>) -> BridgeResult<Bytes> {
262 dev_log!("wasm", "Calling host function: {}", function_name);
263
264 let functions = self.host_functions.read().await;
265 let func = functions
266 .get(function_name)
267 .ok_or_else(|| BridgeError::FunctionNotFound(function_name.to_string()))?;
268
269 if let Some(callback) = func.callback {
270 let result =
272 callback(args).map_err(|e| BridgeError::HostFunctionError(format!("{}: {}", function_name, e)))?;
273 dev_log!("wasm", "Host function call completed: {}", function_name);
274 Ok(result)
275 } else if let Some(async_callback) = func.async_callback {
276 let future = async_callback(args);
278 let result = future
279 .await
280 .map_err(|e| BridgeError::HostFunctionError(format!("{}: {}", function_name, e)))?;
281 dev_log!("wasm", "Async host function call completed: {}", function_name);
282 Ok(result)
283 } else {
284 Err(BridgeError::FunctionNotFound(format!(
285 "No callback for function: {}",
286 function_name
287 )))
288 }
289 }
290
291 pub async fn send_to_wasm(&self, message:WASMMessage) -> BridgeResult<()> {
293 let function_name = message.function.clone();
294 self.host_to_wasm_tx.send(message).map_err(|_| BridgeError::BridgeClosed)?;
295 dev_log!("wasm", "Message sent to WASM: {}", function_name);
296 Ok(())
297 }
298
299 pub async fn receive_from_wasm(&mut self) -> Option<WASMMessage> { self.wasm_to_host_rx.recv().await }
301
302 pub async fn create_async_callback(&self, message_id:String) -> (AsyncCallback, u64) {
304 let token = self.next_callback_token.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
305 let (tx, _rx) = oneshot::channel();
306
307 let callback = AsyncCallback {
309 sender:Arc::new(tokio::sync::Mutex::new(Some(tx))),
310 message_id:message_id.clone(),
311 };
312
313 self.async_callbacks.write().await.insert(token, callback.clone());
314
315 (callback, token)
316 }
317
318 pub async fn get_callback(&self, token:u64) -> Option<AsyncCallback> {
320 self.async_callbacks.write().await.remove(&token)
321 }
322
323 pub async fn get_host_functions(&self) -> Vec<String> { self.host_functions.read().await.keys().cloned().collect() }
325
326 pub async fn unregister_host_function(&self, name:&str) -> bool {
328 let mut functions = self.host_functions.write().await;
329 let removed = functions.remove(name).is_some();
330 if removed {
331 dev_log!("wasm", "Host function unregistered: {}", name);
332 }
333 removed
334 }
335
336 pub async fn clear(&self) {
338 dev_log!("wasm", "Clearing all registered host functions");
339 self.host_functions.write().await.clear();
340 self.async_callbacks.write().await.clear();
341 }
342}
343
344impl Default for HostBridgeImpl {
345 fn default() -> Self { Self::new() }
346}
347
348pub fn serialize_to_bytes<T:Serialize>(data:&T) -> Result<Bytes> {
350 serde_json::to_vec(data)
351 .map(Bytes::from)
352 .map_err(|e| anyhow::anyhow!("Serialization error: {}", e))
353}
354
355pub fn deserialize_from_bytes<T:DeserializeOwned>(bytes:&Bytes) -> Result<T> {
357 serde_json::from_slice(bytes).map_err(|e| anyhow::anyhow!("Deserialization error: {}", e))
358}
359
360pub fn marshal_args(args:Vec<Bytes>) -> Result<Vec<wasmtime::Val>> {
362 args.iter()
363 .map(|bytes| {
364 let value:serde_json::Value = serde_json::from_slice(bytes)?;
365 match value {
366 serde_json::Value::Number(n) => {
367 if let Some(i) = n.as_i64() {
368 Ok(wasmtime::Val::I32(i as i32))
369 } else if let Some(f) = n.as_f64() {
370 Ok(wasmtime::Val::F64(f.to_bits()))
371 } else {
372 Err(anyhow::anyhow!("Invalid number value"))
373 }
374 },
375 _ => Err(anyhow::anyhow!("Unsupported argument type")),
376 }
377 })
378 .collect()
379}
380
381pub fn unmarshal_return(val:wasmtime::Val) -> Result<Bytes> {
383 match val {
384 wasmtime::Val::I32(i) => {
385 let json = serde_json::to_string(&i)?;
386 Ok(Bytes::from(json))
387 },
388 wasmtime::Val::I64(i) => {
389 let json = serde_json::to_string(&i)?;
390 Ok(Bytes::from(json))
391 },
392 wasmtime::Val::F32(f) => {
393 let json = serde_json::to_string(&f)?;
394 Ok(Bytes::from(json))
395 },
396 wasmtime::Val::F64(f) => {
397 let json = serde_json::to_string(&f)?;
398 Ok(Bytes::from(json))
399 },
400 _ => Err(anyhow::anyhow!("Unsupported return type")),
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 #[test]
409 fn test_function_signature_creation() {
410 let signature = FunctionSignature {
411 name:"test_func".to_string(),
412 param_types:vec![ParamType::I32, ParamType::Ptr],
413 return_type:Some(ReturnType::I32),
414 is_async:false,
415 };
416
417 assert_eq!(signature.name, "test_func");
418 assert_eq!(signature.param_types.len(), 2);
419 }
420
421 #[tokio::test]
422 async fn test_host_bridge_creation() {
423 let bridge = HostBridgeImpl::new();
424 assert_eq!(bridge.get_host_functions().await.len(), 0);
425 }
426
427 #[tokio::test]
428 async fn test_register_host_function() {
429 let bridge = HostBridgeImpl::new();
430
431 let signature = FunctionSignature {
432 name:"echo".to_string(),
433 param_types:vec![ParamType::I32],
434 return_type:Some(ReturnType::I32),
435 is_async:false,
436 };
437
438 let result = bridge
439 .register_host_function("echo", signature, |args| Ok(args[0].clone()))
440 .await;
441
442 assert!(result.is_ok());
443 assert_eq!(bridge.get_host_functions().await.len(), 1);
444 }
445
446 #[test]
447 fn test_serialize_deserialize() {
448 let data = vec![1, 2, 3, 4, 5];
449 let bytes = serialize_to_bytes(&data).unwrap();
450 let recovered:Vec<i32> = deserialize_from_bytes(&bytes).unwrap();
451 assert_eq!(data, recovered);
452 }
453
454 #[test]
455 fn test_marshal_unmarshal() {
456 let args = vec![serialize_to_bytes(&42i32).unwrap(), serialize_to_bytes(&3.14f64).unwrap()];
457
458 let marshaled = marshal_args(args);
460 assert!(marshaled.is_ok());
461 }
462}