Wasmex.Components.ComponentServer (wasmex v0.10.0)
A GenServer wrapper for WebAssembly components. This module provides a macro to easily create GenServer-based components with wrapper functions for the exports in the WIT definition.
Usage
To use this module, you need to:
- Create a WIT file defining your component's interface
- Create a module that uses ComponentServer with the path to your WIT file
- Use the generated functions to interact with your WebAssembly component
Basic Example
Given a WIT file greeter.wit
with the following content:
package example:greeter
world greeter {
export greet: func(who: string) -> string;
export multi-greet: func(who: string, times: u16) -> list<string>;
}
You can create a GenServer wrapper like this:
defmodule MyApp.Greeter do
use Wasmex.Components.ComponentServer,
wit: "path/to/greeter.wit"
end
This will automatically generate the following functions:
# Start the component server
iex> {:ok, pid} = MyApp.Greeter.start_link(path: "path/to/greeter.wasm")
# Generated function wrappers:
iex> MyApp.Greeter.greet(pid, "World") # Returns: "Hello, World!"
iex> MyApp.Greeter.multi_greet(pid, "World", 2) # Returns: ["Hello, World!", "Hello, World!"]
Imports Example
When your WebAssembly component imports functions, you can provide them using the :imports
option.
For example, given a WIT file logger.wit
:
package example:logger
world logger {
import log: func(message: string)
import get-timestamp: func() -> u64
export log-with-timestamp: func(message: string)
}
You can implement the imported functions like this:
defmodule MyApp.Logger do
use Wasmex.Components.ComponentServer,
wit: "path/to/logger.wit",
imports: %{
"log" => fn message ->
IO.puts(message)
:ok
end,
"get-timestamp" => fn ->
System.system_time(:second)
end
}
end
Usage:
iex> {:ok, pid} = MyApp.Logger.start_link(wasm: "path/to/logger.wasm")
iex> MyApp.Logger.log_with_timestamp(pid, "Hello from Wasm!")
The import functions should return the correct types as defined in the WIT file. Incorrect types will likely cause a crash, or possibly a NIF panic.
Options
:wit
- Path to the WIT file defining the component's interface:imports
- A map of import function implementations that the component requires, where each key is the function name as defined in the WIT file and the value is the implementing function