Key-Value Component Demo
This repo serves as an example of how to use the latest wasm runtime wasmtime and its component-model feature to build and execute a wasm component. The wasm component uses the key-value interface to interface with a in-memory key-value store provided by the host runtime. The interface is written in WIT file. The binding to the wasm component types is generated by the wit-bindgen tool.
Run
The following command will run the wasm component in the host:
cargo run
If everything goes well, you will see the following output:
Running `target/debug/host`
Level::Info I/O: res from guest: world
res from host: "world"
Build
To build the wasm component, run the following command:
cd ./guest
cargo build --release --target wasm32-wasi
After running the above command, the guest wasm module will be generated at ./guest/target/wasm32-wasi/release/guest.wasm
. This is not a wasm component yet. We can use a tool called wasm-tools to convert the wasm module to a wasm component.
wasm-tools component new /
./guest/target/wasm32-wasi/release/guest.wasm -o ./target/guest.component.wasm
The above command will generate a wasm component at ./target/guest.component.wasm
.
Note: As of now, the component-model feature in wasmtime does not support
wasi_snapshot_preview1
yet. This means that the wasm component cannot be executed by the host that embeds wasmtime because the component's WASI imports are not provided by the host.
Workaround
Download "wasi_snapshot_preview1.wasm" from "https://github.com/bytecodealliance/preview2-prototyping/releases/download/latest/wasi_snapshot_preview1.wasm", where contains a wasi module that bridges the preview1 ABI to preview2 ABI of the component model.
The repo also contains a host implementation of the preview2 ABI. The host can be used as a library to build a new host. See these two imports in src/main.rs
use host::{add_to_linker, Wasi, WasiCtx};
use wasi_cap_std_sync::WasiCtxBuilder;
After downloading the wasi module, we can use the adapter feature of wasm-tools component
to convert the wasm module to a wasm component that implements the required WASI ABI:
wasm-tools component new /
./guest/target/wasm32-wasi/release/guest.wasm -o ./target/guest.component.wasm /
--adapter ./wasi_snapshot_preview1.wasm
Now, the ./target/guest.component.wasm
is the desired wasm component that ready to be executed by the host.