wasm

package module
v0.0.0-...-12a90eb Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 8 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.

README

crucible/wasm

Run Crucible state behaviors as WebAssembly: polyglot guards (and, ahead, services) authored in any language and evaluated by the host over a serializable JSON ABI.

Status: experimental, pre-1.0. The runtime is feature-complete for guards and tested against a real compiled guest; the API may still change before v1.

Import path: github.com/stablekernel/crucible/wasm

What it is

A guard is normally a Go func or a CEL expression. wasm adds a third option: a guard implemented as a WebAssembly module, so behavior logic can be written in any language that compiles to WASM and dropped into a machine by name. The host invokes the module over a small JSON ABI through wazero, a pure-Go, CGo-free runtime, so adopting it adds no C toolchain and no cross-compilation burden.

It lives apart from the kernel so the wazero dependency never enters the stdlib-only core: a deployment that uses only Go or CEL guards never compiles WASM in. The ABI is core WebAssembly, not the Component Model (which would require a CGo runtime).

Quick start

mod, err := wasm.Compile(ctx, moduleBytes) // instantiate once; reuse across calls
if err != nil {
	return err
}
defer mod.Close(ctx)

reg := state.NewRegistry[Order]()
guard := wasm.Guard[string](reg, "approved", mod) // a WASM-backed state.GuardBinding

def := state.ForgeFor[Order]("order").
	Guard("approved", func(state.GuardCtx[Order]) bool { return false }). // stub; Provide overwrites
	State("pending").
	Transition("pending").On("submit").GoTo("submitted").WhenExpr(guard).
	State("submitted").
	Initial("pending").
	Quench()
// ... ToJSON → LoadFromJSON → Provide(reg) → Quench: the guard now evaluates in WASM.

The guard composes like any other: combine it with And/Or/Not, or reference it by name from a JSON-authored machine. A broken module is fail-safe: an evaluation error reports false, so the guarded transition is blocked rather than taken on a bad verdict.

The JSON ABI

A guest module exports two functions over its linear memory:

Export Signature Purpose
alloc (size u32) u32 return a pointer to a writable region of at least size bytes for the host to write the request into
eval (ptr u32, size u32) u64 read the JSON request at [ptr, ptr+size), evaluate, write the JSON response, return packed (outPtr<<32 | outLen)

For a guard the request is {"context": <ctx-json>} and the response {"ok": <bool>}. Because the payloads are JSON, the same module works for any host language. A Module serializes concurrent Eval calls behind a mutex (one linear memory per instance).

alloc need not be a general-purpose allocator. The reference guest backs it with a fixed input buffer at a stable address and simply returns that address, sizing the buffer large enough for expected requests; a guest is free to implement a real growing allocator instead. The host writes exactly size bytes there and reads the response back from the pointer eval returns. The host bounds-checks the response region against linear memory and rejects an out-of-range pointer/length rather than reading out of bounds.

A guest can be written in any WASM-targeting language; the test suite compiles a tiny Go //go:wasmexport guest with the standard toolchain (GOOS=wasip1 GOARCH=wasm, -buildmode=c-shared), no TinyGo and no committed binary.

Timeout and cancellation

The runtime is built so a guest that runs away (an infinite loop, a pathological input) does not block the host forever: pass a context with a deadline or cancel to Eval, and the call is interrupted and returns an error when the context is done. Bound each evaluation with a per-call timeout context for untrusted guests.

Performance

Indicative per-call overhead (Apple Silicon dev machine, go test -bench); reproduce with go test -bench=. -benchmem -run=^$ ./.... Each Eval marshals the request, crosses into the guest, and reads the response back; the cost is dominated by the JSON round-trip across the linear-memory boundary, so a WASM guard is heavier than an in-process Go or CEL guard and is best reserved for genuinely polyglot logic.

Stability

Stability label: experimental (pre-1.0; the API may change). Each module is independently versioned per-module SemVer.

Design & docs

Design rationale and guides live on the documentation site. For questions or proposals, open a GitHub issue.

License

Apache-2.0. See the repository LICENSE and NOTICE.

Documentation

Overview

Package wasm runs Crucible behaviors authored as WebAssembly modules, invoked over a serializable JSON ABI through the pure-Go wazero runtime (no CGo). It is the polyglot binding path: a guard (and later a service) can be implemented in any language that compiles to WebAssembly, and the host calls it with a JSON request and reads a JSON response.

The module lives apart from the kernel so the wazero dependency never enters the stdlib-only core. The ABI is core WebAssembly plus two exported functions — alloc and eval — over the guest's linear memory; it is not the WebAssembly Component Model (which would require a CGo runtime), trading that for a pure-Go host.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Guard

func Guard[S comparable, C any](reg *state.Registry[C], name string, mod *Module) state.GuardNode[S]

Guard registers a WebAssembly-backed guard under name in reg and returns the rich IR node that references it. The module is already compiled (Compile); Guard only binds it, so a JSON-authored machine that Provides reg resolves the guard to the WASM evaluator. The returned node composes like any named-ref guard: drop it into a transition with WhenExpr, or combine it with And/Or/Not. It is tagged rich so analysis knows its truth lives in the module rather than the kernel's tree.

Types

type CompileOption

type CompileOption func(*compileConfig)

CompileOption configures Compile. New capabilities arrive as additional options, so the signature never breaks. No option changes the default behavior; each is additive.

func WithRuntimeConfig

func WithRuntimeConfig(cfg wazero.RuntimeConfig) CompileOption

WithRuntimeConfig overrides the wazero RuntimeConfig the module is built with, for hosts that need to tune compilation (interpreter vs compiler), memory limits, or other wazero knobs. The default already closes a running guest when the call context is done, so a caller that supplies its own config should retain WithCloseOnContextDone(true) to keep timeout/cancellation working.

type Module

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

Module is a compiled and instantiated WebAssembly behavior module exposing the Crucible JSON ABI. A guest exports:

alloc(size uint32) uint32              — reserve size bytes, return the pointer
eval(ptr uint32, size uint32) uint64   — evaluate the JSON request at [ptr,ptr+size),
                                          return packed (outPtr<<32 | outLen)

One Module owns one linear memory, so Eval serializes concurrent calls behind a mutex. Close releases the runtime.

func Compile

func Compile(ctx context.Context, wasmBytes []byte, opts ...CompileOption) (*Module, error)

Compile instantiates a behavior module from its WebAssembly bytes and resolves its ABI exports. The bytes are a wasip1 module (a Go //go:wasmexport guest, or any language's equivalent); WASI preview 1 is provided for the Go runtime's needs.

The runtime is built with WithCloseOnContextDone(true), so a guest that runs away (an infinite loop, a pathological input) is interrupted when the context passed to Eval / Compile is canceled or hits its deadline: the call returns an error rather than blocking the host indefinitely. Pass a per-call timeout context to bound a guest's execution.

func (*Module) Close

func (m *Module) Close(ctx context.Context) error

Close releases the underlying runtime and its instances.

func (*Module) Eval

func (m *Module) Eval(ctx context.Context, request []byte) ([]byte, error)

Eval sends the JSON request to the guest and returns its JSON response. It allocates input space in the guest, writes the request there, calls eval, and reads the response back from the returned pointer. Calls are serialized.

Jump to

Keyboard shortcuts

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