wasm

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package wasm provides a backend that executes code compiled to WebAssembly. Provides strong in-process isolation; requires constrained SDK surface.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrWASMRuntimeNotAvailable is returned when WASM runtime is not available.
	ErrWASMRuntimeNotAvailable = errors.New("wasm runtime not available")

	// ErrModuleCompilationFailed is returned when WASM module compilation fails.
	ErrModuleCompilationFailed = errors.New("wasm module compilation failed")

	// ErrModuleExecutionFailed is returned when WASM module execution fails.
	ErrModuleExecutionFailed = errors.New("wasm module execution failed")

	// ErrUnsupportedLanguage is returned when the language cannot be compiled to WASM.
	ErrUnsupportedLanguage = errors.New("language not supported for wasm compilation")

	// ErrClientNotConfigured is returned when no Runner is configured.
	ErrClientNotConfigured = errors.New("wasm client not configured")

	// ErrInvalidModule is returned when the WASM module is invalid.
	ErrInvalidModule = errors.New("invalid wasm module")

	// ErrMemoryExceeded is returned when the memory limit is exceeded.
	ErrMemoryExceeded = errors.New("memory limit exceeded")

	// ErrFuelExhausted is returned when the fuel limit is exhausted.
	ErrFuelExhausted = errors.New("fuel limit exhausted")
)

Errors for WASM backend operations.

Functions

This section is empty.

Types

type Backend

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

Backend executes code compiled to WebAssembly.

func New

func New(cfg Config) *Backend

New creates a new WASM backend with the given configuration.

func (*Backend) Execute

Execute runs code compiled to WebAssembly.

func (*Backend) Kind

func (b *Backend) Kind() runtime.BackendKind

Kind returns the backend kind identifier.

type CompiledModule

type CompiledModule interface {
	// Name returns the module name if available.
	Name() string

	// Exports lists exported functions.
	Exports() []string

	// Close releases the compiled module.
	Close(ctx context.Context) error
}

CompiledModule represents a pre-compiled WASM module.

type Config

type Config struct {
	// Runtime specifies the WASM runtime to use.
	// Options: wasmtime, wasmer, wazero
	// Default: wazero
	Runtime string

	// MaxMemoryPages is the maximum memory pages (64KB each).
	// Default: 256 (16MB)
	MaxMemoryPages int

	// EnableWASI enables WASI (WebAssembly System Interface).
	// Default: true
	EnableWASI bool

	// AllowedHostFunctions lists host functions the WASM module can call.
	AllowedHostFunctions []string

	// Client is the WASM runner implementation.
	// If nil, Execute() returns ErrClientNotConfigured.
	Client Runner

	// ModuleLoader optionally pre-compiles modules.
	// If nil, modules are compiled on-demand.
	ModuleLoader ModuleLoader

	// HealthChecker optionally verifies runtime health.
	// If nil, health checks are skipped.
	HealthChecker HealthChecker

	// Logger is an optional logger for backend events.
	Logger Logger
}

Config configures a WASM backend.

type HealthChecker

type HealthChecker interface {
	// Ping checks if the WASM runtime is operational.
	Ping(ctx context.Context) error

	// Info returns runtime information.
	Info(ctx context.Context) (RuntimeInfo, error)
}

HealthChecker verifies WASM runtime availability. This is an optional interface - backends may skip health checks.

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is the interface for logging.

Contract: - Concurrency: implementations must be safe for concurrent use. - Errors: logging must be best-effort and must not panic.

type ModuleLoader

type ModuleLoader interface {
	// Load compiles a WASM binary into a reusable module.
	// The returned module reference can be used in Spec.Module.
	Load(ctx context.Context, binary []byte) (CompiledModule, error)

	// Close releases all cached modules.
	Close(ctx context.Context) error
}

ModuleLoader compiles and caches WASM modules. This is an optional interface - backends may compile on-demand.

type Mount

type Mount struct {
	// HostPath is the path on the host filesystem.
	HostPath string

	// GuestPath is the path inside the WASM module.
	GuestPath string

	// ReadOnly mounts the path as read-only.
	ReadOnly bool
}

Mount defines a filesystem mount for WASI.

type ResourceSpec

type ResourceSpec struct {
	// MemoryPages is the maximum memory in 64KB pages.
	// Zero uses runtime default (typically 256 = 16MB).
	MemoryPages uint32

	// FuelLimit is the maximum fuel for metered execution.
	// Zero means unlimited (no metering).
	FuelLimit uint64

	// StackSize is the maximum call stack size in bytes.
	// Zero uses runtime default.
	StackSize uint32
}

ResourceSpec defines WASM resource limits.

type Result

type Result struct {
	// ExitCode is the module's exit code (0 = success).
	ExitCode int

	// Stdout contains the module's stdout output.
	Stdout string

	// Stderr contains the module's stderr output.
	Stderr string

	// Duration is the execution time.
	Duration time.Duration

	// FuelConsumed is the fuel used (if metering enabled).
	FuelConsumed uint64

	// MemoryUsed is peak memory usage in bytes.
	MemoryUsed uint64
}

Result captures the output of WASM execution.

type Runner

type Runner interface {
	// Run executes code in a WASM sandbox and returns the result.
	// The module lifecycle (compile, instantiate, execute, cleanup) is atomic.
	//
	// The implementation must:
	//   - Validate the spec before execution
	//   - Respect ctx cancellation
	//   - Respect spec.Timeout if set
	//   - Capture stdout and stderr
	//   - Return the exit code
	//   - Clean up the module instance on completion or error
	Run(ctx context.Context, spec Spec) (Result, error)
}

Runner is the primary interface for WASM module execution. Implementations may use wazero, wasmer, wasmtime, or mocks.

The interface is intentionally minimal following Go best practices: "The bigger the interface, the weaker the abstraction."

Implementations are expected to:

  • Compile/load the WASM module
  • Configure memory limits and WASI
  • Execute the module with provided input
  • Capture stdout/stderr
  • Respect context cancellation and spec timeout

type RuntimeInfo

type RuntimeInfo struct {
	// Name is the runtime name (wazero, wasmer, wasmtime).
	Name string

	// Version is the runtime version.
	Version string

	// Features lists supported features.
	Features []string
}

RuntimeInfo contains WASM runtime metadata.

type SecuritySpec

type SecuritySpec struct {
	// EnableWASI enables WebAssembly System Interface.
	// Default: true for most use cases.
	EnableWASI bool

	// AllowedHostFunctions lists host functions the module can import.
	// Empty means no host functions allowed (maximum isolation).
	AllowedHostFunctions []string

	// EnableNetwork allows WASI network access.
	// Default: false for sandbox isolation.
	EnableNetwork bool

	// EnableClock allows access to system clock.
	// Default: true (needed for timing operations).
	EnableClock bool
}

SecuritySpec defines WASM security settings.

type Spec

type Spec struct {
	// Module is the compiled WASM binary (required).
	// This can be raw .wasm bytes or a precompiled module reference.
	Module []byte

	// EntryPoint is the exported function to call (default: "_start" for WASI).
	EntryPoint string

	// Args are command-line arguments passed to the module.
	Args []string

	// Env contains environment variables in KEY=value format.
	Env []string

	// Stdin provides input to the module's stdin.
	Stdin []byte

	// WorkingDir is the working directory for WASI filesystem operations.
	WorkingDir string

	// Mounts defines filesystem mounts for WASI.
	Mounts []Mount

	// Resources defines resource limits.
	Resources ResourceSpec

	// Security defines security settings.
	Security SecuritySpec

	// Timeout is the maximum execution duration.
	Timeout time.Duration

	// Labels are metadata labels for tracking.
	Labels map[string]string
}

Spec defines what to execute in a WASM sandbox and how.

type StreamEvent

type StreamEvent struct {
	// Type identifies the event type.
	Type StreamEventType

	// Data contains the event payload (stdout/stderr bytes).
	Data []byte

	// ExitCode is set when Type is StreamEventExit.
	ExitCode int

	// Error is set when Type is StreamEventError.
	Error error
}

StreamEvent represents a streaming output event from WASM execution.

type StreamEventType

type StreamEventType string

StreamEventType identifies the type of streaming event.

const (
	// StreamEventStdout indicates stdout data.
	StreamEventStdout StreamEventType = "stdout"

	// StreamEventStderr indicates stderr data.
	StreamEventStderr StreamEventType = "stderr"

	// StreamEventExit indicates module exit.
	StreamEventExit StreamEventType = "exit"

	// StreamEventError indicates an error occurred.
	StreamEventError StreamEventType = "error"
)

type StreamRunner

type StreamRunner interface {
	Runner

	// RunStream executes and streams stdout/stderr as events.
	// The returned channel is closed when execution completes.
	// Callers should drain the channel to receive the exit event.
	RunStream(ctx context.Context, spec Spec) (<-chan StreamEvent, error)
}

StreamRunner provides streaming execution for long-running modules. This is an optional extension to Runner.

Jump to

Keyboard shortcuts

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