This is an API breaking change that does a few things:
* Stop encouraging practice that can break context propagation:
* Stops caching `context.Context` in `wazero.RuntimeConfig`
* Stops caching `context.Context` in `api.Module`
* Fixes context propagation in function calls:
* Changes `api.Function`'s arg0 from `api.Module` to `context.Context`
* Adds `context.Context` parameter in instantiation (propagates to
.start)
* Allows context propagation for heavy operations like compile:
* Adds `context.Context` as the initial parameter of `CompileModule`
The design we had earlier was a good start, but this is the only way to
ensure coherence when users start correlating or tracing. While adding a
`context.Context` parameter may seem difficult, wazero is a low-level
library and WebAssembly is notoriously difficult to troubleshoot. In
other words, it will be easier to explain to users to pass (even nil) as
the context parameter vs try to figure out things without coherent
context.
Signed-off-by: Adrian Cole <adrian@tetrate.io>
Import go func example
This example shows how to define, import and call a Go-defined function from a WebAssembly-defined function.
If the current year is 2022, and we give the argument 2000, age-calculator.go should output 22.
$ go run age-calculator.go 2000
println >> 21
log_i32 >> 21
Background
WebAssembly has neither a mechanism to get the current year, nor one to print to the console, so we define these in Go. Similar to Go, WebAssembly functions are namespaced, into modules instead of packages. Just like Go, only exported functions can be imported into another module. What you'll learn in age-calculator.go, is how to export functions using ModuleBuilder and how a WebAssembly module defined in its text format imports it. This only uses the text format for demonstration purposes, to show you what's going on. It is likely, you will use another language to compile a Wasm (WebAssembly Module) binary, such as TinyGo. Regardless of how wasm is produced, the export/import mechanics are the same!
Where next?
The following examples continue the path of learning about importing and exporting functions with wazero:
WebAssembly System Interface (WASI)
This uses an ad-hoc Go-defined function to print to the console. There is an emerging specification to standardize system calls (similar to Go's x/sys) called WebAssembly System Interface (WASI). While this is not yet a W3C standard, wazero includes a wasi package.
Replace Import
You may use WebAssembly modules that have imports that don't match your ideal packaging structure. wazero allows you to replace imports with different module names as needed, on a function granularity using ModuleConfig.WithImport.