Skip to main content

Grove/WASM/
HostBridge.rs

1//! Host Bridge
2//!
3//! Provides bidirectional communication between the host (Grove) and WASM
4//! modules. Handles function calls, data transfer, and marshalling between the
5//! two environments.
6
7use 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/// Host bridge error types
18#[derive(Debug, thiserror::Error)]
19pub enum BridgeError {
20	/// Function not found error
21	#[error("Function not found: {0}")]
22	FunctionNotFound(String),
23
24	/// Invalid function signature error
25	#[error("Invalid function signature: {0}")]
26	InvalidSignature(String),
27
28	/// Serialization failed error
29	#[error("Serialization failed: {0}")]
30	SerializationError(String),
31
32	/// Deserialization failed error
33	#[error("Deserialization failed: {0}")]
34	DeserializationError(String),
35
36	/// Host function error
37	#[error("Host function error: {0}")]
38	HostFunctionError(String),
39
40	/// Communication timeout error
41	#[error("Communication timeout")]
42	Timeout,
43
44	/// Bridge closed error
45	#[error("Bridge closed")]
46	BridgeClosed,
47}
48
49/// Type-safe result for operations
50pub type BridgeResult<T> = Result<T, BridgeError>;
51
52/// Function signature information
53#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
54pub struct FunctionSignature {
55	/// Function name
56	pub name:String,
57	/// Parameter types
58	pub param_types:Vec<ParamType>,
59	/// Return type
60	pub return_type:Option<ReturnType>,
61	/// Whether this is an async function
62	pub is_async:bool,
63}
64
65/// Parameter types for WASM functions
66#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
67pub enum ParamType {
68	/// 32-bit signed integer parameter
69	I32,
70	/// 64-bit signed integer parameter
71	I64,
72	/// 32-bit floating point parameter
73	F32,
74	/// 64-bit floating point parameter
75	F64,
76	/// Pointer to memory
77	Ptr,
78	/// Length parameter following a pointer
79	Len,
80}
81
82/// Return types for WASM functions
83#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
84pub enum ReturnType {
85	/// 32-bit signed integer return type
86	I32,
87	/// 64-bit signed integer return type
88	I64,
89	/// 32-bit floating point return type
90	F32,
91	/// 64-bit floating point return type
92	F64,
93	/// No return value (void)
94	Void,
95}
96
97/// Message sent from WASM to host
98#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
99pub struct HostMessage {
100	/// Message ID for correlation
101	pub message_id:String,
102	/// Function name to call
103	pub function:String,
104	/// Serialized arguments
105	pub args:Vec<Bytes>,
106	/// Callback token for async responses
107	pub callback_token:Option<u64>,
108}
109
110/// Response sent from host to WASM
111#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
112pub struct HostResponse {
113	/// Correlating message ID
114	pub message_id:String,
115	/// Success flag
116	pub success:bool,
117	/// Response data
118	pub data:Option<Bytes>,
119	/// Error message if failed
120	pub error:Option<String>,
121}
122
123/// Callback for async function responses
124#[derive(Clone)]
125pub struct AsyncCallback {
126	/// Sender for transmitting the response
127	sender:Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<HostResponse>>>>,
128	/// Message ID for correlation
129	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	/// Send response through the callback
140	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/// Message from host to WASM
152#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
153pub struct WASMMessage {
154	/// Target function in WASM
155	pub function:String,
156	/// Arguments
157	pub args:Vec<Bytes>,
158}
159
160/// Host function callback type
161pub type HostFunctionCallback = fn(Vec<Bytes>) -> Result<Bytes>;
162
163/// Async host function callback type
164pub type AsyncHostFunctionCallback =
165	fn(Vec<Bytes>) -> Box<dyn std::future::Future<Output = Result<Bytes>> + Send + Unpin>;
166
167/// Host function definition
168#[derive(Debug)]
169pub struct HostFunction {
170	/// Function name
171	pub name:String,
172	/// Function signature
173	pub signature:FunctionSignature,
174	/// Synchronous callback - not serializable (skip serde derive)
175	#[allow(dead_code)]
176	pub callback:Option<HostFunctionCallback>,
177	/// Async callback - not serializable (skip serde derive)
178	#[allow(dead_code)]
179	pub async_callback:Option<AsyncHostFunctionCallback>,
180}
181
182/// Host Bridge for WASM communication
183#[derive(Debug)]
184pub struct HostBridgeImpl {
185	/// Registry of host functions exported to WASM
186	host_functions:Arc<RwLock<HashMap<String, HostFunction>>>,
187	/// Channel for receiving messages from WASM
188	wasm_to_host_rx:mpsc::UnboundedReceiver<WASMMessage>,
189	/// Channel for sending messages to WASM
190	host_to_wasm_tx:mpsc::UnboundedSender<WASMMessage>,
191	/// Active async callbacks
192	async_callbacks:Arc<RwLock<HashMap<u64, AsyncCallback>>>,
193	/// Next callback token
194	next_callback_token:Arc<std::sync::atomic::AtomicU64>,
195}
196
197impl HostBridgeImpl {
198	/// Create a new host bridge
199	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		// In a real implementation, we'd need to wire these up properly
204		// For now, we drop the receiver to avoid unused warnings
205		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	/// Register a host function to be exported to WASM
217	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	/// Register an async host function
241	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	/// Call a host function from WASM
261	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			// Synchronous call
271			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			// Async call
277			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	/// Send a message to WASM
292	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	/// Receive a message from WASM (blocking)
300	pub async fn receive_from_wasm(&mut self) -> Option<WASMMessage> { self.wasm_to_host_rx.recv().await }
301
302	/// Create async callback
303	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		// Create callback with Arc-wrapped sender
308		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	/// Get callback by token
319	pub async fn get_callback(&self, token:u64) -> Option<AsyncCallback> {
320		self.async_callbacks.write().await.remove(&token)
321	}
322
323	/// Get all registered host functions
324	pub async fn get_host_functions(&self) -> Vec<String> { self.host_functions.read().await.keys().cloned().collect() }
325
326	/// Unregister a host function
327	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	/// Clear all registered functions
337	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
348/// Utility function to serialize data to Bytes
349pub 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
355/// Utility function to deserialize Bytes to data
356pub 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
360/// Marshal arguments for WASM function call
361pub 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
381/// Unmarshal return values from WASM function call
382pub 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		// Test that marshaling works (we don't assert on exact type conversion)
459		let marshaled = marshal_args(args);
460		assert!(marshaled.is_ok());
461	}
462}