instance

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 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 instance instantiates a decoded WebAssembly component and exposes its exported functions for calling. It covers the M3 "spine": a real component runs end to end, both the no-import export direction (M3 STEP 2) and the host-import direction (M3 STEP 3, this file plus host_import.go).

Scope

Two component shapes are supported, and anything outside them fails loudly with a specific, named error rather than silently returning a zero value:

  • No-import (M3 STEP 2): one embedded core module, instantiated as the component's single core instance with no arguments, exporting functions defined purely via "canon lift" of a core function reached through a single core-export alias.

  • Host-import (M3 STEP 3): the component imports one or more instances of host functions (e.g. `test:pkg/host` exporting `log: func(msg: string)`) that are lowered (canon lower) into core functions the guest core module imports and calls. The caller supplies Go implementations via WithImport. See host_import.go for the lowering/wrapper machinery.

The host-import path also handles a component with zero WIT imports whose world *exports an interface* rather than a bare function: wit-component packages the lifted funcs into a nested "re-export shim" component (a second, fully embedded component -- binary.Component.NestedComponents) and an Instance that instantiates it, with the top-level export naming that instance. See resolveInstanceExport / bindInstanceExport in host_import.go for how that shim is resolved back to the outer canon lifts, and CallExport for how a caller reaches a function inside it. A canon lift's post-return option (e.g. on a function returning a string) is also wired here: the post-return core func is called with the lift's flat results immediately after lifting, per definitions.py's canon_lift.

Still rejected in both: canon resource.* built-ins, non-func exports outside the re-export-shim shape above, multi-result functions, whole-parameter-list / result spilling to memory, string/list values when no linear memory is available, and any nested component beyond a pure re-export shim (e.g. the wasip2 CLI adapter shim, which embeds its own core module and instantiation graph -- out of scope here).

Decoder gaps worked around here

The component binary decoder (internal/component/binary) does not retain the per-alias core:sort discriminator (func vs memory vs table vs global) on binary.AliasDef. Rather than require a binary change, this package disambiguates core-export aliases by probing the actually-instantiated module's exports (a name that resolves to a Function is a core-func alias; a memory alias does not). It also does not retain the func signatures declared inside an imported instance type, which is why the host-import direction takes the imported function's WIT type from the caller via WithImport rather than from the decoded component.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncCall

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

AsyncCall is the per-invocation handle an AsyncHostFunc receives, mirroring the reference canon_lower's on_start/on_resolve closures (testdata/definitions.py ~2250-2268) collapsed into one object (on_start's role -- lifting args -- happens before the AsyncHostFunc is even called; see buildAsyncHostWrapper). Single-threaded contract: Resolve/Defer may only be called (a) synchronously inside the AsyncHostFunc invocation, or (b) from a thunk running on the instance's scheduler (i.e. from a Defer'd func, transitively) -- both provably on the one goroutine driving this Instance. Calling Resolve from anywhere else (another goroutine, or after the originating Call has returned) panics: external completion is CallAsync's job, not yet implemented (see the design doc's §2.5 "truly external completion").

func (*AsyncCall) Defer

func (ac *AsyncCall) Defer(fn func())

Defer enqueues fn on the instance's deterministic FIFO run queue (sched.go); it runs later, while the guest is suspended on a WAIT/YIELD or the blocking wait builtin. This is how an MVP async import defers completion without OS concurrency -- including multi-hop chains (Defer inside Defer) to exercise multiple scheduler-drive rounds.

Uses enqueueVoid, not enqueue: fn is stored directly on the runq entry instead of being wrapped in a func() error adapter closure, so a Deferred completion costs exactly fn's own allocation (if any), not two.

func (*AsyncCall) OnCancel

func (ac *AsyncCall) OnCancel(fn func())

OnCancel registers fn as the reference's Subtask.on_cancel for this call (Phase 3, docs/component-model-async-phase3-design.md §2.4): fn runs synchronously inside the guest's subtask.cancel. fn may Resolve/ ResolveCancelled synchronously (the guest then sees the final state, never BLOCKED) or later via Defer (an async cancel then returns BLOCKED; a sync cancel blocks on the scheduler until fn's eventual Resolve/ ResolveCancelled). Must be called before the AsyncHostFunc returns -- it sets a field on the subtask the wrapper has already constructed.

An import that never calls OnCancel leaves the subtask's onCancel nil: subtask.cancel then just records the request and otherwise ignores it -- spec-legal (a callee may ignore cancellation; the subtask still resolves whenever the import eventually completes normally via Resolve).

func (*AsyncCall) Resolve

func (ac *AsyncCall) Resolve(results []abi.Value)

Resolve delivers the import's results (reference Subtask.on_resolve, the canon_lower on_resolve closure it's built from). One-shot -- a second call panics, matching Subtask.resolve's assert(not self.resolved()).

  • Called while inCall (synchronously, before the AsyncHostFunc returns): the wrapper's epilogue observes st.resolved() and takes the reference's immediate fast path -- packed [RETURNED], the subtask never enters the table, no event, no WAIT needed.
  • Called later, from a scheduler thunk (the subtask already parked): performs the reference's on_resolve + on_progress in one step -- lowers results into guest memory now (through the retptr captured at call time) and installs the SUBTASK pending-event closure, so the next WAIT driver's predicate check sees it.

func (*AsyncCall) ResolveCancelled

func (ac *AsyncCall) ResolveCancelled()

ResolveCancelled resolves the call as cancelled (reference on_resolve (None), definitions.py ~2258-2264): always CANCELLED_BEFORE_RETURNED -- a host-import subtask is never STARTING (buildAsyncHostWrapper lifts args eagerly, before the AsyncHostFunc -- and therefore any OnCancel hook -- ever runs), so it has necessarily already STARTED by the time a cancellation can be requested. Same one-shot + same-goroutine discipline as Resolve; same parked-path pending-event installation. Panics if called without cancellationRequested (the reference asserts a None result implies cancellation_requested).

type AsyncHostFunc

type AsyncHostFunc func(ctx context.Context, args []abi.Value, call *AsyncCall) error

AsyncHostFunc starts one async import call (reference: the FuncInst callee canon_lower invokes with on_start/on_resolve/caller). It receives the lifted arguments and an *AsyncCall to complete the call, synchronously or later via Defer. Returning a non-nil error traps the guest call that invoked the import (mirroring HostFunc).

type CompileCache

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

CompileCache caches wazy.CompiledModule handles for core module bytes, letting repeated Instantiate calls against the SAME component skip re-compiling (re-JITting) its embedded core modules every time. Pass one via WithCompileCache to opt in; the default (no cache) behavior is unchanged -- every Instantiate call recompiles its core modules exactly as before.

Key

A cache entry is keyed by the exact core-module bytes handed to CompileModule -- after any component-layer rewrite (e.g. rewriteEmptyImportModuleName's anonymous-import-name patch), so the key always matches what was actually compiled. This is sufficient because nothing about how a core module is COMPILED varies by caller here: the only ModuleConfig settings the component layer applies (WithName/WithStartFunctions) take effect at InstantiateModule time, not CompileModule time, so two instantiations that differ only in those still safely share one CompiledModule. A future caller needing compile-affecting ModuleConfig (e.g. a per-call FunctionListenerFactory) would need to fold that into the key too -- this cache does not do so today.

Ownership and lifetime

A CompiledModule stored here is owned BY THE CACHE, not by any Instance built from it. Instance.Close only closes the api.Module instances it created (via InstantiateModule); it never closes the CompiledModule that produced them -- unlike Runtime.InstantiateWithConfig's implicit-compile path (which marks its CompiledModule closeWithModule so an instance's Close cleans it up too), CompileModule+InstantiateModule through this cache never sets that flag. So a cached CompiledModule, and the compiled code it references, stays alive across many Instance lifetimes until the cache itself is closed. Call Close on the CompileCache (typically alongside the Runtime it was built against) once it's no longer needed; after that, every Instance ever built through it is invalid.

Runtime pairing

A CompiledModule belongs to the Runtime that compiled it -- wazy has no cross-Runtime CompiledModule reuse. A CompileCache must therefore be used with exactly one Runtime: the same r passed to every Instantiate call that also passes this cache. Using one CompileCache across two different Runtimes is a caller bug (the second Runtime's InstantiateModule would receive a CompiledModule it never compiled); CompileCache does not detect or guard against this -- pairing cache and Runtime correctly is the caller's responsibility.

Concurrency

CompileCache is safe for concurrent use: multiple goroutines may call Instantiate with the same cache concurrently, including racing a first Instantiate of the same component bytes. A miss race compiles at most twice; the loser's redundant CompiledModule is closed immediately rather than stored, and every caller (winner or loser) still gets back a valid, usable CompiledModule.

func NewCompileCache

func NewCompileCache() *CompileCache

NewCompileCache returns an empty CompileCache ready to pass to WithCompileCache. See CompileCache's doc for its ownership/lifetime and Runtime-pairing rules.

func (*CompileCache) Close

func (c *CompileCache) Close(ctx context.Context) error

Close releases every CompiledModule this cache holds. Every Instance ever built through this cache becomes invalid once this returns -- its underlying compiled code is gone. Safe to call once, typically alongside closing the Runtime this cache was paired with.

type CopyResult

type CopyResult uint32

CopyResult is the public mirror of copyResult.

const (
	CopyCompleted CopyResult = CopyResult(copyCompleted)
	CopyDropped   CopyResult = CopyResult(copyDropped)
	CopyCancelled CopyResult = CopyResult(copyCancelled)
)

type FutureReader

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

func (*FutureReader) Cancel

func (r *FutureReader) Cancel()

Cancel revokes a parked Get.

func (*FutureReader) Close

func (r *FutureReader) Close()

Close drops the readable end: a parked (or future) guest write completes with DROPPED.

func (*FutureReader) Get

func (r *FutureReader) Get(onDone func(res CopyResult, v abi.Value))

Get requests the future's one value.

type FutureWriter

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

FutureWriter/FutureReader are StreamWriter/StreamReader's future twins: one element, one shot.

func (*FutureWriter) Close

func (w *FutureWriter) Close()

Close is ONLY legal after Set completed or reported DROPPED (WritableFutureEnd.drop's trap_if(state != DONE)) -- panics otherwise.

func (*FutureWriter) Set

func (w *FutureWriter) Set(v abi.Value, onDone func(res CopyResult))

Set completes immediately if a guest read is parked; otherwise parks until the guest reads (or reports DROPPED if the reader closed first).

type HandleTable

type HandleTable = handleTable

HandleTable is one component instance's resource handle table: the thing that maps a guest-visible handle to the host representation behind it. A host func that mints an own<T>/borrow<T> nested inside a composite result must do so through this table (the engine translates only top-level handles automatically), which is what WithResourcesHook exists to hand over.

type Harness

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

Harness builds a host implementation's registered funcs without instantiating a component, so they can be called directly. It backs the public component/componenttest package -- see that package's doc for why this exists.

func NewHarness

func NewHarness(opts []Option) *Harness

NewHarness applies opts and runs the resource hooks, exactly as Instantiate would before any host func executes.

func (*Harness) Func

func (h *Harness) Func(iface, name string) HostFunc

Func returns the HostFunc registered for iface/name, or nil. iface is matched with its version suffix stripped, matching registration.

func (*Harness) Registered

func (h *Harness) Registered() map[string][]string

Registered returns every import these options registered, as interface name -> func names. Interface names appear with their version suffix already stripped, matching how registration keys them.

func (*Harness) Resources

func (h *Harness) Resources() *HandleTable

Resources returns the handle table the hooks were given -- the same one a real instantiation would hand out, so handles minted by a host func under test can be resolved here.

type HostFunc

type HostFunc func(ctx context.Context, args []abi.Value) ([]abi.Value, error)

HostFunc is a Go implementation of a component import. It receives the lifted component-level argument values and returns the component-level result values. Returning an error aborts the guest call that invoked it (the error surfaces from the originating Instance.Call).

type Instance

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

Instance is an instantiated WebAssembly component: the set of instantiated core/host modules plus, for each component-level exported function, the binding needed to call it through its canon lift signature.

func Instantiate

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

Instantiate decodes componentBytes as a WebAssembly component, instantiates its embedded core module(s) into r (registering caller-provided host implementations for any imports), and wires up the export -> canon lift -> core func bindings needed to call exported functions via Call.

See the package doc for exactly which component shapes are supported; anything outside them is rejected with a descriptive error.

func (*Instance) Call

func (in *Instance) Call(ctx context.Context, exportName string, args ...abi.Value) ([]abi.Value, error)

Call invokes the component-level exported function named exportName with args. Each arg is lowered into core wasm values per its declared parameter type, the underlying core function is called with the flattened arguments, and the raw core results are lifted back into abi.Values per the export's result type.

func (*Instance) CallAsync

func (in *Instance) CallAsync(ctx context.Context, export string, args ...abi.Value) (*PendingCall, error)

CallAsync starts an async (callback) export and returns as soon as it first parks awaiting an external completion -- or a completed PendingCall if it resolves outright. Progress resumes when an outstanding AsyncHostFunc is Resolve()d (from any goroutine) and the caller drives it with Await.

Milestone limits: one outstanding CallAsync per Instance; the export must be an async (callback) lift.

func (*Instance) CallExport

func (in *Instance) CallExport(ctx context.Context, instanceName, memberName string, args ...abi.Value) ([]abi.Value, error)

CallExport invokes memberName inside the exported instance instanceName.

A WIT world that exports an *interface* (rather than a bare function) compiles to a component whose top-level export is instance-typed: the tooling packages the interface's lifted functions into a nested "re-export shim" component and an Instance (section 5) that instantiates it, and the top-level export names that instance -- see resolveInstanceExport in host_import.go. CallExport is how a caller reaches a function inside such an instance, e.g. CallExport(ctx, "component:adder/calc", "add", u32(2), u32(3)).

This is sugar for Call(ctx, instanceName+"#"+memberName, args...); both spellings work, since instance members are bound into the same exports map as plain func exports.

func (*Instance) Close

func (in *Instance) Close(ctx context.Context) error

Close releases every module instantiated for this component (in reverse order of instantiation). It does not close the Runtime passed to Instantiate, which the caller owns.

func (*Instance) CoreModuleCount

func (in *Instance) CoreModuleCount() int

CoreModuleCount returns the number of embedded core modules (real, non-synthetic core wasm binaries from the component's CoreModules section) this Instance instantiated. Only meaningful for a component instantiated via the general graph engine (graph.go), i.e. one with more than one embedded core module; see needsGraphPath.

func (*Instance) DropResource

func (in *Instance) DropResource(ctx context.Context, iface, resourceName string, handle uint32) error

DropResource drops an own<resource> handle the host received from a guest export (e.g. one returned by a constructor or factory func), completing the resource lifecycle: it runs the guest's destructor if the component defines one, then removes the handle so the slot is freed and any later use of that handle fails loud. iface/resourceName name the resource (e.g. "example:res/counters", "counter"). Dropping a borrow, an unknown handle, or one with outstanding lends fails loud.

The destructor is the guest core func the component exports as "<iface>#[dtor]<resourceName>" (wit-component emits it for every guest-defined resource); if no such export exists the handle is still removed. Host-owned resources (WASI/http) are not dropped this way -- the host owns their lifecycle directly.

func (*Instance) HostState

func (in *Instance) HostState(key any) any

HostState returns the value registered under key by WithHostState, or nil.

func (*Instance) InstanceExports

func (in *Instance) InstanceExports() []string

InstanceExports returns the names of the interfaces this component instance exports, as they appear in the binary (version suffix included).

A host implementation needs this to find an export whose exact versioned name it cannot know in advance: a component exporting wasi:http/incoming-handler@0.2.3 and one exporting @0.2.0 are the same interface to a host that wants to drive it. The caller matches on the versionless prefix and uses the full name it finds here to Call.

func (*Instance) NewFuture

func (in *Instance) NewFuture(elem binary.TypeDesc) (*FutureWriter, abi.Value, error)

NewFuture is NewStream's future twin.

func (*Instance) NewStream

func (in *Instance) NewStream(elem binary.TypeDesc) (*StreamWriter, abi.Value, error)

NewStream creates a stream pair for passing data INTO or OUT OF the guest: the host keeps one end (the returned *StreamWriter); the returned abi.Value is the *sharedStream identity, ready to hand to the guest as a Call/CallAsync arg (instance.go's resolveArgHandlesDepth mints a fresh READABLE end for it in the callee's table) or as an async-import Resolve result (host_import.go's allocHandleResult does the same). elem is nil for a bare stream.

func (*Instance) Resources

func (in *Instance) Resources() *HandleTable

Resources returns this instance's handle table.

WithResourcesHook covers the registration-time need (a host func minting a handle nested in a result). This covers the other direction: a host that DRIVES an exported interface must mint the own<T>/borrow<T> handles it passes in, and only has the Instance to work from -- which is exactly what wasi:http's server side does to hand the guest an incoming-request.

func (*Instance) WASICalls

func (in *Instance) WASICalls() []string

WASICalls returns the "iface.func" name of every canon-lower this Instance's graph engine wired up, in the order they were declared in the component binary. Only meaningful for a component instantiated via the general graph engine (graph.go).

type Option

type Option func(*config)

Option configures Instantiate.

func WithAsyncImport

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

WithAsyncImport registers fn for a component import that guests lower with the async option (CanonOpt kind 0x06). iface/name/params/results have the same meaning as WithImport's. Binding an async-lowered import to a WithImport-registered fn (or a sync-lowered import to a WithAsyncImport-registered fn) fails loud at bind time -- see graph.go's computeCanonHostFunc.

func WithCompileCache

func WithCompileCache(cache *CompileCache) Option

WithCompileCache opts Instantiate into reusing already-compiled core modules from cache instead of recompiling (re-JITting) them on every call. Pass the SAME *CompileCache across repeated Instantiate calls for the SAME component (and the same Runtime -- see CompileCache's doc for the Runtime-pairing rule) to skip redundant compilation of its embedded core modules; the first Instantiate against a given component populates the cache, later ones hit it.

Omitting this option (the default) preserves the exact prior behavior: every Instantiate call recompiles its core modules from scratch.

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` -- the hook for releasing whatever the rep names.

func WithHostState

func WithHostState(key, value any) Option

WithHostState attaches an opaque value to every Instance built with this option, retrievable via Instance.HostState(key). It is how a host implementation of a stateful interface keeps per-instance state: the value is created once per Instantiate call and lives exactly as long as the Instance.

key should be a package-private type, not a bare string, so two independent host implementations cannot collide.

func WithImport

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

WithImport registers a Go implementation for a component import. iface is the imported interface name (e.g. "test:pkg/host"), name is the function name within it (e.g. "log"), and params/results are that function's WIT parameter and result types as abi/binary type descriptors (e.g. binary.PrimitiveDesc{Prim: "string"}).

func WithImportCustom

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

WithImportCustom registers fn as the host implementation of iface/name with a hand-built signature: fd describes the WIT types and resolve maps its TypeRefs back to descriptors (both from a TypeTable).

This is the general form of WithImport. WithImport synthesizes a FuncDesc from a flat list of types, which cannot express a composite whose children are themselves composites; passing the FuncDesc directly can express any WIT type, at the cost of building the type table yourself.

func WithResourceTag

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

WithResourceTag declares that the resource named `name`, exported by the imported interface `iface`, is the resource this host implementation tags as `tag` when it mints handles.

This is not optional for a resource-bearing interface. The guest's own generated bindings drop handles through a canon resource.drop carrying the component binary's type index, while the host mints them under a caller-chosen tag; 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 invoked once per instantiation with that instance's HandleTable, before any host func can run. A host implementation needs it to mint handles for own<T>/borrow<T> nested inside composite results, which the automatic top-level translation does not cover.

type PendingCall

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

PendingCall is the handle CallAsync returns: one async export invocation in flight, suspended awaiting external import completions.

func (*PendingCall) Await

func (p *PendingCall) Await(ctx context.Context) ([]abi.Value, error)

Await blocks until the call resolves (or ctx is done), driving the scheduler as external completions arrive. It is the sole driver after CallAsync returns; call it from a single goroutine.

func (*PendingCall) Cancel

func (p *PendingCall) Cancel(ctx context.Context) error

Cancel aborts the pending call: it stops driving, reaps any parked guest state, and resolves the handle with a cancellation error. This milestone does not deliver a graceful Component Model task.cancel to the guest.

func (*PendingCall) Done

func (p *PendingCall) Done() <-chan struct{}

Done is closed when the call resolves, fails, is cancelled, or the instance closes. After it closes, Await returns immediately.

type StreamReader

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

StreamReader is the host-held readable end of a stream whose writable end lives in a guest table (or another host).

func (*StreamReader) Cancel

func (r *StreamReader) Cancel()

Cancel revokes a parked Read.

func (*StreamReader) Close

func (r *StreamReader) Close()

Close drops the readable end: a parked (or future) guest write completes with DROPPED.

func (*StreamReader) Read

func (r *StreamReader) Read(n uint32, onDone func(res CopyResult, vals []abi.Value))

Read requests up to n elements. Same one-shot/park contract as Write.

type StreamWriter

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

StreamWriter is the host-held writable end of a stream whose readable end lives (or will live) in a guest table. NOT a table entry, NOT a waitable: completion surfaces as Go callbacks, not events.

func (*StreamWriter) Cancel

func (w *StreamWriter) Cancel()

Cancel revokes a parked Write. onDone (from the pending Write) fires with CANCELLED and the partial progress. No-op if the Write already completed.

func (*StreamWriter) Close

func (w *StreamWriter) Close()

Close drops the writable end: a parked or future guest read completes with DROPPED; subsequent guest reads get DROPPED immediately. Idempotent.

func (*StreamWriter) Write

func (w *StreamWriter) Write(vals []abi.Value, onDone func(res CopyResult, n uint32))

Write offers vals to the stream. onDone fires EXACTLY ONCE with the result and the number of elements actually transferred:

  • immediately (before Write returns), if a guest read is parked (rendezvous) or the writable end's counterpart was dropped (copyDropped, n=0);
  • later, from inside a guest stream.read builtin, when the guest finally reads (the host buffer was parked -- backpressure).

A second Write before onDone fires panics: rendezvous streams have no host-side queue, by design.

Jump to

Keyboard shortcuts

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