Skip to main content

omnia/
traits.rs

1//! # Traits for WASI Components
2//!
3//! This module contains traits implemented by concrete WASI services.
4//!
5//! Each service is a module that provides a concrete implementation in support
6//! of a specific set of WASI interfaces.
7
8use std::fmt::Debug;
9use std::future::Future;
10
11use anyhow::Result;
12use futures::future::BoxFuture;
13use wasmtime::component::{InstancePre, Linker};
14
15/// Result type for asynchronous operations.
16pub type FutureResult<T> = BoxFuture<'static, Result<T>>;
17
18/// State trait for WASI components.
19pub trait State: Clone + Send + Sync + 'static {
20    /// The store context type.
21    type StoreCtx: Send;
22
23    /// Returns the store context.
24    #[must_use]
25    fn store(&self) -> Self::StoreCtx;
26
27    /// Returns the pre-instantiated component.
28    fn instance_pre(&self) -> &InstancePre<Self::StoreCtx>;
29}
30
31/// Implemented by all WASI hosts in order to allow the runtime to link their
32/// dependencies.
33pub trait Host<T>: Debug + Sync + Send {
34    /// Link the host's dependencies prior to component instantiation.
35    ///
36    /// # Errors
37    ///
38    /// Returns an linking error(s) from the service's generated bindings.
39    fn add_to_linker(linker: &mut Linker<T>) -> Result<()>;
40}
41
42/// Implemented by WASI hosts that are servers in order to allow the runtime to
43/// start them.
44pub trait Server<S: State>: Debug + Sync + Send {
45    /// Start the service.
46    ///
47    /// This is typically implemented by services that instantiate (or run)
48    /// wasm components.
49    #[allow(unused_variables)]
50    fn run(&self, state: &S) -> impl Future<Output = Result<()>> {
51        async { Ok(()) }
52    }
53}
54
55/// Implemented by backend resources to allow the backend to be connected to a
56/// WASI component.
57pub trait Backend: Sized + Sync + Send {
58    /// The options used to connect to the backend.
59    type ConnectOptions: FromEnv;
60
61    /// Connect to the resource.
62    #[must_use]
63    fn connect() -> impl Future<Output = Result<Self>> {
64        async { Self::connect_with(Self::ConnectOptions::from_env()?).await }
65    }
66
67    /// Connect to the resource with the specified options.
68    fn connect_with(options: Self::ConnectOptions) -> impl Future<Output = Result<Self>>;
69}
70
71/// Trait for creating connection options from environment variables.
72pub trait FromEnv: Sized {
73    /// Create connection options from environment variables.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error if required environment variables are missing or invalid.
78    fn from_env() -> Result<Self>;
79}