wasmrs_host/
context.rs

1use std::sync::Arc;
2
3use bytes::Bytes;
4use wasmrs::{Frame, OperationList, WasmSocket};
5
6use crate::host::HostServer;
7
8type Result<T> = std::result::Result<T, crate::errors::Error>;
9
10#[derive(Clone)]
11#[allow(missing_debug_implementations)]
12#[allow(missing_docs)]
13pub struct SharedContext(Arc<dyn ProviderCallContext + Send + Sync + 'static>);
14
15impl SharedContext {
16  /// Create a new shared context with the passed [ProviderCallContext]
17  pub fn new(context: impl ProviderCallContext + Send + Sync + 'static) -> Self {
18    Self(Arc::new(context))
19  }
20
21  pub(crate) async fn init(&self, host_buffer_size: u32, guest_buffer_size: u32) -> Result<()> {
22    self.0.init(host_buffer_size, guest_buffer_size).await
23  }
24
25  pub(crate) async fn write_frame(&self, frame: Frame) -> Result<()> {
26    let id = frame.stream_id();
27    let result = self.0.write_frame(frame).await;
28
29    if let Err(e) = &result {
30      error!("failed to write frame for stream ID {}: {}", id, e);
31      self.0.on_error(id).await?;
32    }
33
34    Ok(result?)
35  }
36
37  pub(crate) fn get_import(&self, namespace: &str, operation: &str) -> Option<u32> {
38    self.0.get_import(namespace, operation)
39  }
40
41  pub(crate) fn get_export(&self, namespace: &str, operation: &str) -> Option<u32> {
42    self.0.get_export(namespace, operation)
43  }
44
45  pub(crate) fn get_operation_list(&self) -> OperationList {
46    self.0.get_operation_list()
47  }
48}
49
50/// All engine providers must implement the [EngineProvider] trait.
51#[async_trait::async_trait]
52pub trait EngineProvider {
53  /// Called to create a new [SharedContext].
54  async fn new_context(&self, state: Arc<WasmSocket<HostServer>>) -> Result<SharedContext>;
55}
56
57/// The trait implemented by a context for a call or set of calls.
58#[async_trait::async_trait]
59pub trait ProviderCallContext: wasmrs::ModuleHost {
60  /// Initialize the call context.
61  async fn init(&self, host_buffer_size: u32, guest_buffer_size: u32) -> Result<()>;
62}
63
64/// The trait that a host needs to implement to satisfy wasmrs protocol imports and to query data about the loaded module.
65pub trait CallbackProvider {
66  /// The callback for `__wasmrs_send`
67  fn do_host_send(&self, frame_bytes: Bytes) -> Result<()>;
68  #[allow(missing_docs)]
69  fn do_console_log(&self, msg: &str);
70  /// Query the operation list for the module.
71  fn do_op_list(&mut self, bytes: Bytes) -> Result<()>;
72  /// The callback for `__wasmrs_init`
73  fn do_host_init(&self, guest_buff_ptr: u32, host_buff_ptr: u32) -> Result<()>;
74}