Files
wazero/examples/wasi_test.go
Crypt Keeper 2664b1eb62 Simplifies API per feedback (#427)
During #425, @neilalexander gave constructive feedback that the API is
both moving fast, and not good enough yet. This attempts to reduce the
incidental complexity at the cost of a little conflation.

### odd presence of `wasm` and `wasi` packages -> `api` package

We had public API packages in wasm and wasi, which helped us avoid
leaking too many internals as public. That these had names that look
like there should be implementations in them cause unnecessary
confusion. This squashes both into one package "api" which has no
package collission with anything.

We've long struggled with the poorly specified and non-uniformly
implemented WASI specification. Trying to bring visibility to its
constraints knowing they are routinely invalid taints our API for no
good reason. This removes all `WASI` commands for a default to invoke
the function `_start` if it exists. In doing so, there's only one path
to start a module.

Moreover, this puts all wasi code in a top-level package "wasi" as it
isn't re-imported by any internal types.

### Reuse of Module for pre and post instantiation to `Binary` -> `Module`

Module is defined by WebAssembly in many phases, from decoded to
instantiated. However, using the same noun in multiple packages is very
confusing. We at one point tried a name "DecodedModule" or
"InstantiatedModule", but this is a fools errand. By deviating slightly
from the spec we can make it unambiguous what a module is.

This make a result of compilation a `Binary`, retaining `Module` for an
instantiated one. In doing so, there's no longer any name conflicts
whatsoever.

### Confusion about config -> `ModuleConfig`

Also caused by splitting wasm into wasm+wasi is configuration. This
conflates both into the same type `ModuleConfig` as it is simpler than
trying to explain a "will never be finished" api of wasi snapshot-01 in
routine use of WebAssembly. In other words, this further moves WASI out
of the foreground as it has been nothing but burden.

```diff
--- a/README.md
+++ b/README.md
@@ -49,8 +49,8 @@ For example, here's how you can allow WebAssembly modules to read
-wm, err := r.InstantiateModule(wazero.WASISnapshotPreview1())
-defer wm.Close()
+wm, err := wasi.InstantiateSnapshotPreview1(r)
+defer wm.Close()

-sysConfig := wazero.NewSysConfig().WithFS(os.DirFS("/work/home"))
-module, err := wazero.StartWASICommandWithConfig(r, compiled, sysConfig)
+config := wazero.ModuleConfig().WithFS(os.DirFS("/work/home"))
+module, err := r.InstantiateModule(binary, config)
 defer module.Close()
 ...
```
2022-04-02 06:42:36 +08:00

68 lines
2.0 KiB
Go

package examples
import (
"bytes"
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/wasi"
)
func Test_WASI(t *testing.T) {
// built-in WASI function to write a random value to memory
randomGet := func(ctx api.Module, buf, bufLen uint32) wasi.Errno {
panic("unimplemented")
}
stdout := new(bytes.Buffer)
random := func(ctx api.Module) {
// Write 8 random bytes to memory using WASI.
errno := randomGet(ctx, 0, 8)
require.Equal(t, wasi.ErrnoSuccess, errno)
// Read them back and print it in hex!
random, ok := ctx.Memory().ReadUint64Le(0)
require.True(t, ok)
_, _ = fmt.Fprintf(stdout, "random: %x\n", random)
}
r := wazero.NewRuntime()
// Host functions can be exported as any module name, including the empty string.
host, err := r.NewModuleBuilder("").ExportFunction("random", random).Instantiate()
require.NoError(t, err)
defer host.Close()
// Configure WASI and implement the function to use it
wm, err := wasi.InstantiateSnapshotPreview1(r)
require.NoError(t, err)
defer wm.Close()
randomGetFn := wm.ExportedFunction("random_get")
// Implement the function pointer. This mainly shows how you can decouple a host function dependency.
randomGet = func(ctx api.Module, buf, bufLen uint32) wasi.Errno {
res, err := randomGetFn.Call(ctx, uint64(buf), uint64(bufLen))
require.NoError(t, err)
return wasi.Errno(res[0])
}
// The "random" function was imported as $random in Wasm. Since it was marked as the start
// function, it is invoked on instantiation. Ensure that worked: "random" was called!
mod, err := r.InstantiateModuleFromCode([]byte(`(module $wasi
(import "wasi_snapshot_preview1" "random_get"
(func $wasi.random_get (param $buf i32) (param $buf_len i32) (result (;errno;) i32)))
(import "" "random" (func $random))
(memory 1)
(start $random)
)`))
require.NoError(t, err)
defer mod.Close()
require.Contains(t, stdout.String(), "random: ")
}