component

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 5 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package component runs WebAssembly Component Model components -- and the WASI 0.2 (wasip2) world built on it -- on a wazy Runtime.

Where the core wazy package instantiates core modules, this package instantiates *components*: genuine wasm32-wasip2 binaries produced by rustc, wasm-tools, and friends. It decodes the component, wires its multi-module graph (nested instances, canonical lift/lower of the Canonical ABI, resource lifetimes), and -- with WithWASI -- provides the WASI 0.2 host interfaces (wasi:cli, clocks, filesystem, io, random, sockets, http).

Typical use: build a Runtime, instantiate a component with the WASI surface wired to your stdio/filesystem/args, call an export, then Close.

r := wazy.NewRuntime(ctx)
defer r.Close(ctx)

inst, err := component.Instantiate(ctx, r, componentWasm,
	component.WithWASI(component.WASIConfig{Stdout: os.Stdout})...)
if err != nil {
	return err
}
defer inst.Close(ctx)

// A wasi:cli/command component: run its entry point.
_, err = inst.Call(ctx, "wasi:cli/run@0.2.3#run")

Call arguments and results are Go values (uint32, int64, string, []any for lists/records, and uint32 handles for resources), matching the Canonical ABI's lifting of the component's WIT types.

This API is young and, like the rest of wazy, makes no stability promise yet.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncCall

type AsyncCall = instance.AsyncCall

AsyncCall is the completion handle an AsyncHostFunc receives. Call Resolve with the import's results (or ResolveCancelled). Under CallAsync, Resolve may be called from another goroutine after the AsyncHostFunc returns -- that is how external I/O completions drive a component forward.

type AsyncHostFunc

type AsyncHostFunc = instance.AsyncHostFunc

AsyncHostFunc implements an async-lowered component import. It receives the lifted arguments and an *AsyncCall used to deliver the result -- synchronously (call.Resolve before returning) or later, from any goroutine, once the call was started via Instance.CallAsync. Register it with WithAsyncImport.

type BorrowDesc

type BorrowDesc = binary.BorrowDesc

BorrowDesc is borrow<R> -- a handle lent for the duration of the call.

type CompileCache

type CompileCache = instance.CompileCache

CompileCache amortizes a component's decode and its embedded core modules' compilation across repeated Instantiate calls of the same component bytes. Safe for concurrent use. Pair one with a single Runtime and Close it when done. See WithCompileCache and NewCompileCache.

func NewCompileCache

func NewCompileCache() *CompileCache

NewCompileCache returns an empty CompileCache ready to pass to WithCompileCache. Close it (CompileCache.Close) alongside the Runtime it is paired with.

type EnumDesc

type EnumDesc = binary.EnumDesc

EnumDesc is a set of named cases with no payloads. Its Value is the case index as a uint32.

type FlagsDesc

type FlagsDesc = binary.FlagsDesc

FlagsDesc is a named bitset. Its Value is a uint32 of set bits.

type FuncDesc

type FuncDesc = binary.FuncDesc

FuncDesc, and its parts, describe a whole host func signature. Build one with TypeTable.Func rather than by hand.

type FuncParam

type FuncParam = binary.FuncParam

FuncDesc, and its parts, describe a whole host func signature. Build one with TypeTable.Func rather than by hand.

type FuncResult

type FuncResult = binary.FuncResult

FuncDesc, and its parts, describe a whole host func signature. Build one with TypeTable.Func rather than by hand.

type FuncResults

type FuncResults = binary.FuncResults

FuncDesc, and its parts, describe a whole host func signature. Build one with TypeTable.Func rather than by hand.

type FutureDesc

type FutureDesc = binary.FutureDesc

FutureDesc is future<T>.

type HandleTable

type HandleTable = instance.HandleTable

HandleTable is one instance's resource handle table. Obtain it with WithResourcesHook; use it to mint own<T>/borrow<T> handles that sit nested inside a composite result, which the engine's automatic top-level handle translation does not reach.

type HostFunc

type HostFunc = instance.HostFunc

HostFunc implements a synchronous component import: it receives the lifted arguments and returns the lifted results (or an error, which traps the guest call). Register it with WithImport.

type Instance

type Instance = instance.Instance

Instance is a live component instance. Call its exports with Call / CallExport, and release it with Close. A wasi:http/incoming-handler component also satisfies http.Handler via ServeHTTP.

func Instantiate

func Instantiate(ctx context.Context, r wazy.Runtime, componentBytes []byte, opts ...Option) (*Instance, error)

Instantiate decodes componentBytes as a WebAssembly Component Model component and instantiates it on r, returning a live Instance. Pass WithWASI to give it the WASI 0.2 host surface, and WithCompileCache to reuse compilation work across repeated instantiations. Close the returned Instance when done.

type ListDesc

type ListDesc = binary.ListDesc

ListDesc is an unbounded sequence. Its Value is a []Value -- or, for list<u8> specifically, a []byte, which lowers with a single copy.

type Option

type Option = instance.Option

Option configures Instantiate. WithWASI and WithCompileCache produce Options.

func WithAsyncImport

func WithAsyncImport(iface, name string, fn AsyncHostFunc, params, results []TypeDesc) Option

WithAsyncImport registers fn as the component's async-lowered import iface/name. Pair it with Instance.CallAsync so fn may complete the call later, from another goroutine (real I/O), via AsyncCall.Resolve.

func WithCompileCache

func WithCompileCache(cache *CompileCache) Option

WithCompileCache reuses cache across this and future Instantiate calls of the same component bytes, skipping the repeated decode + core-module compile.

func WithHostResourceDtor

func WithHostResourceDtor(tag uint32, fn func(ctx context.Context, rep uint32) error) Option

WithHostResourceDtor registers the Go destructor run when the guest drops an owned handle of the host resource tagged `tag`.

func WithHostState

func WithHostState(key, value any) Option

WithHostState attaches an opaque value to every Instance built with this option, retrievable with Instance.HostState. It is how a host implementation of a stateful interface keeps state that lives exactly as long as one Instance -- the shape wazy's own wasi:http server side uses to find its request/response tables from ServeHTTP.

Use a package-private key type, not a bare string, so two independent host implementations cannot collide:

type myHostKey struct{}
component.WithHostState(myHostKey{}, newMyHost())
h := inst.HostState(myHostKey{}).(*myHost)

func WithImport

func WithImport(iface, name string, fn HostFunc, params, results []TypeDesc) Option

WithImport registers fn as the component's synchronous import iface/name, with the given WIT param/result types. iface is the interface name (e.g. "wasi:cli/environment") or "" for a top-level import; name is the function (or "" for a bare top-level func import).

func WithImportCustom

func WithImportCustom(iface, name string, fn HostFunc, fd FuncDesc, resolve Resolver) Option

WithImportCustom registers fn as the host implementation of iface/name with a hand-built signature -- the general form of WithImport, and the only one that can express a nested composite. Build fd and resolve from a TypeTable:

tbl := component.NewTypeTable()
fd := tbl.Func([]component.TypeRef{component.Prim("string")},
	tbl.Result(tbl.List(component.Prim("string")), component.Prim("u32")))
opt := component.WithImportCustom("acme:api/host@1.0.0", "lookup", fn, fd, tbl.Resolver())

iface is matched with its "@x.y.z" version suffix stripped, so one registration serves every patch version of an interface.

func WithResourceTag

func WithResourceTag(iface, name string, tag uint32) Option

WithResourceTag declares that the resource `name`, exported by the imported interface `iface`, is the one this host tags as `tag` when minting handles.

Required for any resource-bearing interface: the guest drops handles through a canon carrying the component binary's own type index, while the host mints them under a tag of its choosing. Without this mapping the two numberings disagree and the first drop trips the handle table's cross-type check.

func WithResourcesHook

func WithResourcesHook(hook func(*HandleTable)) Option

WithResourcesHook registers a callback run once per instantiation, with that instance's HandleTable, before any host func executes. This is how a host implementation gets the table it needs to mint nested handles.

type OptionDesc

type OptionDesc = binary.OptionDesc

OptionDesc is option<T>. Its Value is nil for none, or the inner value.

type OwnDesc

type OwnDesc = binary.OwnDesc

OwnDesc is own<R> -- an owned handle to a resource. Lifting one gives the host the rep it names and consumes the guest's handle.

type PendingCall

type PendingCall = instance.PendingCall

PendingCall is a live CallAsync invocation, suspended awaiting external import completions. See Instance.CallAsync.

type PrimitiveDesc

type PrimitiveDesc = binary.PrimitiveDesc

PrimitiveDesc is bool, s8-s64, u8-u64, f32, f64, char, or string. See Prim for the ergonomic spelling.

type RecordDesc

type RecordDesc = binary.RecordDesc

RecordDesc is a struct with named fields. Its Value is a []Value in field order.

type RecordField

type RecordField = binary.RecordField

RecordField is one named field of a RecordDesc.

type Resolver

type Resolver = abi.Resolver

Resolver maps a TypeRef's index back to its descriptor. TypeTable.Resolver produces the one matching a table.

type ResultDesc

type ResultDesc = binary.ResultDesc

ResultDesc is result<T, E>; either arm may be absent. Its Value is a ResultValue.

type ResultValue

type ResultValue = abi.ResultValue

ResultValue is the Go shape of a result value. IsErr selects the arm; Payload is that arm's value, or nil for an arm declared without a type.

A result is NOT a Go error: returning a Go error from a HostFunc traps the guest, whereas a ResultValue with IsErr set is an ordinary value the guest receives and can handle. Use the error return only for "this call cannot proceed", and ResultValue for a WIT-declared failure.

type StreamDesc

type StreamDesc = binary.StreamDesc

StreamDesc is stream<T>.

type TupleDesc

type TupleDesc = binary.TupleDesc

TupleDesc is a positional product type. Its Value is a []Value.

type TypeDesc

type TypeDesc = binary.TypeDesc

TypeDesc is one WIT type. The concrete descriptors below implement it. It is a sealed interface -- a type outside wazy cannot implement it, because the ABI dispatches on the concrete descriptors and an unknown one has no defined lowering.

type TypeRef

type TypeRef = binary.TypeRef

TypeRef refers to a type from inside a composite: either a primitive (spelled inline) or an index into the TypeTable the enclosing FuncDesc was built with. Prefer the TypeTable sugar constructors over building these by hand.

func Prim

func Prim(name string) TypeRef

Prim is the ergonomic spelling of a primitive TypeRef: Prim("u32"), Prim("string"). Valid names are bool, s8, s16, s32, s64, u8, u16, u32, u64, f32, f64, char, string.

type TypeTable

type TypeTable struct {
	// contains filtered or unexported fields
}

TypeTable interns the composite types one host func's signature refers to, handing back a TypeRef for each. It exists because a WIT type is a graph, not a tree: `list<list<u8>>` needs the inner `list<u8>` to be nameable from the outer one, and a TypeRef names it by index into exactly this table.

One table per func signature. Indices are local to it, and the Resolver it produces is what the engine uses to walk back from a TypeRef to a descriptor, so a FuncDesc and the table it was built from must be passed to WithImportCustom together.

The Add method is the primitive; the sugar methods below (List, Option, Result, Tuple, Record, Variant) cover the shapes that actually occur and keep TypeRef out of caller code:

tbl := component.NewTypeTable()
fd := tbl.Func(
	[]component.TypeRef{tbl.Record("name", component.Prim("string"), "count", component.Prim("u32"))},
	tbl.Result(tbl.List(component.Prim("string")), component.Prim("u32")),
)
opt := component.WithImportCustom("acme:api/host@1.0.0", "lookup", fn, fd, tbl.Resolver())

A TypeTable is not safe for concurrent use; build a signature on one goroutine, then it is read-only.

func NewTypeTable

func NewTypeTable() *TypeTable

NewTypeTable returns an empty TypeTable.

func (*TypeTable) Add

func (t *TypeTable) Add(td TypeDesc) TypeRef

Add interns td and returns the TypeRef naming it. A primitive is returned inline (it needs no table slot), so Add(PrimitiveDesc{...}) and Prim(...) are interchangeable.

func (*TypeTable) Borrow

func (t *TypeTable) Borrow(tag uint32) TypeRef

Borrow interns borrow<R> for the resource identified by tag.

func (*TypeTable) Enum

func (t *TypeTable) Enum(cases ...string) TypeRef

Enum interns an enum of the named cases. A value of it is the case index as a uint32.

func (*TypeTable) Flags

func (t *TypeTable) Flags(names ...string) TypeRef

Flags interns a flags bitset of the named flags. A value of it is a uint32 whose bits are set in declaration order.

func (*TypeTable) Func

func (t *TypeTable) Func(params []TypeRef, result TypeRef) FuncDesc

Func assembles a FuncDesc from params and a single unnamed result. Pass the zero TypeRef for a func that returns nothing.

func (*TypeTable) List

func (t *TypeTable) List(elem TypeRef) TypeRef

List interns list<elem>.

func (*TypeTable) Option

func (t *TypeTable) Option(elem TypeRef) TypeRef

Option interns option<elem>.

func (*TypeTable) Own

func (t *TypeTable) Own(tag uint32) TypeRef

Own interns own<R> for the resource identified by tag -- the same tag passed to WithResourceTag and used when minting handles.

func (*TypeTable) Record

func (t *TypeTable) Record(nameTypePairs ...any) TypeRef

Record interns a record from alternating name/type pairs: Record("port", Prim("u16"), "host", Prim("string")). Panics on an odd number of arguments or a non-string in a name position, since both are programmer errors in a signature that is built once at startup.

func (*TypeTable) Resolver

func (t *TypeTable) Resolver() Resolver

Resolver returns the Resolver over the table's current entries. Call it after the signature is fully built.

func (*TypeTable) Result

func (t *TypeTable) Result(ok, err TypeRef) TypeRef

Result interns result<ok, err>. Pass the zero TypeRef for an arm the WIT declares without a type: Result(ok, TypeRef{}) is `result<ok>`, and Result(TypeRef{}, TypeRef{}) is a bare `result`.

func (*TypeTable) Tuple

func (t *TypeTable) Tuple(elems ...TypeRef) TypeRef

Tuple interns tuple<elems...>.

func (*TypeTable) Variant

func (t *TypeTable) Variant(cases ...VariantCaseSpec) TypeRef

Variant interns a variant. Each case is a name and an optional payload; pass the zero TypeRef for a case that carries none. Case order is the discriminant order a VariantValue's Disc indexes into.

type Value

type Value = abi.Value

Value is a component-level call value: a Go value matching the Canonical ABI's lifting of a WIT type (uint32, int64, float64, string, []any for lists/records/tuples, uint32 for resource handles). It is the element type of Call/CallExport arguments and results and of host-import args/results.

type VariantCase

type VariantCase = binary.VariantCase

VariantCase is one case of a VariantDesc; a nil Type means no payload.

type VariantCaseSpec

type VariantCaseSpec struct {
	Name string
	Type TypeRef
}

VariantCaseSpec is one case for TypeTable.Variant: a name, and a payload type or the zero TypeRef for none.

type VariantDesc

type VariantDesc = binary.VariantDesc

VariantDesc is a discriminated union. Its Value is a VariantValue.

type VariantValue

type VariantValue = abi.VariantValue

VariantValue is the Go shape of a variant value: Disc is the case index in declaration order, Payload is that case's value (nil when the case carries none).

Directories

Path Synopsis
Package componenttest provides utilities for testing a host implementation of a component interface.
Package componenttest provides utilities for testing a host implementation of a component interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL