wasm

package
v0.7.21 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package wasm is the WASM/WASI runtime driver — the third implementation of internal/runtime.Runtime (after pkg/docker and internal/runtime/firecracker).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CheckpointHost

type CheckpointHost interface {
	CheckpointSandbox(ctx context.Context, sandbox *models.Sandbox) (checkpointPath, cloneGen string, err error)
	RehydrateSandbox(ctx context.Context, sandbox *models.Sandbox, hostMounts []mounts.ContainerBind) (*models.SandboxRuntimeState, error)
}

CheckpointHost is the Phase 6 drain/checkpoint/rehydrate surface the service layer type-asserts from runtime.Runtime.

type Config

type Config struct {
	RunDir             string
	ModulesDir         string
	DefaultMemoryMB    int
	DefaultWallTimeout time.Duration
	DrainTimeout       time.Duration
	// ResidentHostEnabled routes non-listen creates to a shared resident
	// compile-once/instantiate-many host per (ownerRef, digest, memoryMB) bucket
	// instead of a fresh per-sandbox worker (plans/wasm-resident-module-host.md).
	// Default false; requires a resident supervisor wired via SetResidentHostSupervisor.
	ResidentHostEnabled bool
	// ResidentHostMaxInstances caps co-tenants per host process; 0 = unbounded.
	// When full, the driver spills to <bucket>-2.sock (SB_WASM_RESIDENT_HOST_MAX_INSTANCES).
	ResidentHostMaxInstances int
	// ResidentHostIdleTTL reaps a resident host holding zero instances for this
	// long; 0 disables the reaper (SB_WASM_RESIDENT_HOST_IDLE_TTL).
	ResidentHostIdleTTL time.Duration
}

Config holds host-side WASM runtime settings.

func FromDaemonConfig

func FromDaemonConfig(cfg config.Config) Config

FromDaemonConfig projects the WASM slice of daemon config into driver config.

type Driver

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

Driver implements runtime.Runtime for WASM sandboxes. WASM satisfies only the core Runtime interface — not ContainerRuntime (host-mediated networking).

func New

func New(cfg Config, logger *slog.Logger) *Driver

New constructs a WASM driver. The zero value is not usable.

func (*Driver) CheckpointLiveSandbox

func (d *Driver) CheckpointLiveSandbox(ctx context.Context, sandbox *models.Sandbox) (string, string, error)

CheckpointLiveSandbox writes mem.snap for a live sandbox without passivating or evicting the worker. Used by periodic boundary checkpoint sweeps.

func (*Driver) CheckpointSandbox

func (d *Driver) CheckpointSandbox(ctx context.Context, sandbox *models.Sandbox) (string, string, error)

CheckpointSandbox writes mem.snap for a live sandbox and tears down its worker.

func (*Driver) Create

func (d *Driver) Create(ctx context.Context, req models.CreateSandboxRequest, sandboxID, _ string, hostMounts []mounts.ContainerBind) (*models.SandboxRuntimeState, error)

func (*Driver) CreateSnapshot

func (d *Driver) CreateSnapshot(ctx context.Context, sandboxID, _ string) (string, error)

func (*Driver) Destroy

func (d *Driver) Destroy(ctx context.Context, sandbox *models.Sandbox) error

func (*Driver) DrainNetworkByteCounters

func (d *Driver) DrainNetworkByteCounters() map[string]struct{ BytesIn, BytesOut int64 }

DrainNetworkByteCounters implements NetworkByteCounter for the service netstats sink.

func (*Driver) EnsureHTTPListener

func (d *Driver) EnsureHTTPListener(ctx context.Context, sandboxID string, guestPort int) (string, error)

func (*Driver) Inspect

func (d *Driver) Inspect(ctx context.Context, sandboxID string) (*models.SandboxRuntimeState, error)

func (*Driver) ListManaged

func (d *Driver) ListManaged(ctx context.Context) (map[string]*models.SandboxRuntimeState, error)

func (*Driver) MigrateSandbox

func (d *Driver) MigrateSandbox(ctx context.Context, sandbox *models.Sandbox, destDir string) (string, string, error)

MigrateSandbox checkpoints a live sandbox (if needed) and copies mem.snap into destDir for cross-node handoff (plans/wasm-runtime.md §4.4).

func (*Driver) Ping

func (d *Driver) Ping(context.Context) error

func (*Driver) PrewarmResidentHosts

func (d *Driver) PrewarmResidentHosts(ctx context.Context, refs []string)

PrewarmResidentHosts brings up the resident host and compiles each ref's module at daemon boot, so the FIRST create for a standard module is a ~ms Instantiate instead of paying the one-time ~seconds CompileModule on the create path. Best-effort and meant to be backgrounded by the caller.

func (*Driver) RehydrateSandbox

func (d *Driver) RehydrateSandbox(ctx context.Context, sandbox *models.Sandbox, hostMounts []mounts.ContainerBind) (*models.SandboxRuntimeState, error)

RehydrateSandbox reloads a passivated sandbox from mem.snap (§4.3).

func (*Driver) ReleaseHTTPListener

func (d *Driver) ReleaseHTTPListener(sandboxID string, guestPort int)

func (*Driver) RemoveImage

func (d *Driver) RemoveImage(ctx context.Context, imageRef string) error

RemoveImage deletes a module artifact from the host cache. imageRef may be a module ref (file://, relative under ModulesDir, or absolute path) or a bare digest hex string. Missing paths are treated as success (idempotent GC).

func (*Driver) ResidentHostStats

func (d *Driver) ResidentHostStats() ResidentHostStats

ResidentHostStats returns the current resident-host footprint (see the type doc for how it relates to admission headroom).

func (*Driver) Resize

func (d *Driver) Resize(ctx context.Context, sandboxID string, req models.ResizeSandboxRequest) error

func (*Driver) RunResidentReaper

func (d *Driver) RunResidentReaper(ctx context.Context, ttl time.Duration)

RunResidentReaper periodically tears down resident host processes that have held zero instances for at least ttl, reclaiming their compiled-module + runtime RAM (PR-C). Pre-warmed standard-module hosts are pinned and never reaped. ttl<=0 (or the flag off) disables it. Blocks until ctx is cancelled, so the daemon runs it in a goroutine and shutdown stops it.

func (*Driver) ServeToolbox

func (d *Driver) ServeToolbox(_ context.Context, sandboxID, token string, w http.ResponseWriter, r *http.Request)

ServeToolbox implements ToolboxHost.

func (*Driver) SetModuleResolver

func (d *Driver) SetModuleResolver(r ModuleResolver)

SetModuleResolver injects the module resolver (pkg/wasmmod.Resolver in production).

func (*Driver) SetNetworkBlocks

func (d *Driver) SetNetworkBlocks(sandboxID string, blockIngress, blockEgress bool)

SetNetworkBlocks implements NetworkPolicySink for WASM quota enforcement.

func (*Driver) SetResidentHostSupervisor

func (d *Driver) SetResidentHostSupervisor(s WorkerSupervisor)

SetResidentHostSupervisor wires the supervisor that owns shared resident-host processes. Only consulted when cfg.ResidentHostEnabled; leaving it nil (the default) keeps every create on the per-sandbox worker path.

func (*Driver) SetStateKV

func (d *Driver) SetStateKV(kv statekv.Store)

SetStateKV wires the durable host-KV store (§4.6).

func (*Driver) SetWarmPool

func (d *Driver) SetWarmPool(p WarmPool)

SetWarmPool injects the warm worker pool. Nil leaves every create on the cold path.

func (*Driver) SetWorkerClientFactory

func (d *Driver) SetWorkerClientFactory(f WorkerClientFactory)

SetWorkerClientFactory overrides worker IPC for tests.

func (*Driver) SetWorkerSupervisor

func (d *Driver) SetWorkerSupervisor(s WorkerSupervisor)

SetWorkerSupervisor injects the worker subprocess supervisor.

func (*Driver) Start

func (d *Driver) Start(ctx context.Context, sandboxID string) (*models.SandboxRuntimeState, error)

func (*Driver) StartSandbox

func (d *Driver) StartSandbox(ctx context.Context, sandbox *models.Sandbox, hostMounts []mounts.ContainerBind) (*models.SandboxRuntimeState, error)

StartSandbox reconstructs a stopped sandbox from its persisted row and mounts.

func (*Driver) Stop

func (d *Driver) Stop(ctx context.Context, sandboxID string) error

func (*Driver) SyncAllowedPorts

func (d *Driver) SyncAllowedPorts(sandboxID string, ports []int)

func (*Driver) SyncGuestListenPorts

func (d *Driver) SyncGuestListenPorts(ctx context.Context, sandboxID string, ports []int) error

SyncGuestListenPorts enables or disables the guest wasip1 listener to match exposed HTTP ports. When multiple ports are exposed, the lowest port wins. Port 0 requests an ephemeral guest bind; the resolved host port is stored on the instance and ProxyHTTP dials via guestPort=0.

type GuestListenPortSyncer

type GuestListenPortSyncer interface {
	SyncGuestListenPorts(ctx context.Context, sandboxID string, ports []int) error
}

GuestListenPortSyncer hot-updates wasip1 listener caps after expose_port.

type LiveCheckpointHost

type LiveCheckpointHost interface {
	CheckpointLiveSandbox(ctx context.Context, sandbox *models.Sandbox) (checkpointPath, cloneGen string, err error)
}

LiveCheckpointHost writes a boundary checkpoint without passivating the sandbox. Periodic checkpoint sweeps use this so live sandboxes stay admitted and routable.

type MigrationHost

type MigrationHost interface {
	MigrateSandbox(ctx context.Context, sandbox *models.Sandbox, destDir string) (checkpointPath, cloneGen string, err error)
}

MigrationHost streams a boundary checkpoint to a sibling node (§4.4).

type ModuleResolver

type ModuleResolver interface {
	Resolve(ctx context.Context, ref string) (*wasmmod.ResolvedModule, error)
}

ModuleResolver resolves a module reference to a local .wasm path.

type NetworkByteCounter

type NetworkByteCounter interface {
	DrainNetworkByteCounters() map[string]struct{ BytesIn, BytesOut int64 }
}

NetworkByteCounter drains ingress/egress byte deltas observed at the HTTP mediator.

type NetworkPolicySink

type NetworkPolicySink interface {
	SetNetworkBlocks(sandboxID string, blockIngress, blockEgress bool)
}

NetworkPolicySink applies ingress/egress quota blocks at the mediator.

type PortGateway

type PortGateway interface {
	EnsureHTTPListener(ctx context.Context, sandboxID string, guestPort int) (dialAddr string, err error)
	ReleaseHTTPListener(sandboxID string, guestPort int)
	SyncAllowedPorts(sandboxID string, ports []int)
}

PortGateway is the host-mediated HTTP ingress surface for WASM sandboxes. Caddy and the loopback ingress proxy dial the loopback address returned by EnsureHTTPListener rather than a guest container IP.

func AsPortGateway

func AsPortGateway(rt any) (PortGateway, bool)

AsPortGateway returns the HTTP ingress surface when rt implements it.

type ResidentHostStats

type ResidentHostStats struct {
	Buckets   int `json:"buckets"`   // distinct (ownerRef, digest, memoryMB) groups
	Hosts     int `json:"hosts"`     // resident host processes (base RAM ≈ Hosts × module size)
	Instances int `json:"instances"` // live co-tenant instances across all hosts
}

ResidentHostStats is a point-in-time snapshot of the resident-host footprint, exposed via expvar (aerolvm_wasm_resident_hosts) so operators can size memory headroom. Admission (pkg/capacity) counts each sandbox at its full memoryMB (an over-count that cushions the guest's actual linear memory) but does NOT see a host process's own RAM (the shared compiled module + runtime, ~the module's on-disk size per bucket). PR-C keeps that accounting deliberately conservative: Hosts here lets an operator reserve headroom via MemoryFloorRatio / MemoryReservationRatio (roughly Hosts × module footprint).

type StartHost

type StartHost interface {
	StartSandbox(ctx context.Context, sandbox *models.Sandbox, hostMounts []mounts.ContainerBind) (*models.SandboxRuntimeState, error)
}

StartHost reconstructs a stopped sandbox using persisted sandbox metadata.

type ToolboxHost

type ToolboxHost interface {
	ServeToolbox(ctx context.Context, sandboxID, token string, w http.ResponseWriter, r *http.Request)
}

ToolboxHost serves toolbox HTTP in-process for WASM sandboxes.

type WarmPool

type WarmPool interface {
	NoteModule(digest, modulePath string)
	Acquire(ctx context.Context, digest, modulePath string, memoryMB int) (*wasmpool.Slot, error)
}

WarmPool is the seam Driver.Create uses for pre-compiled worker hits. Production wiring uses *wasmpool.Pool; tests inject a fake.

type WorkerClient

type WorkerClient interface {
	Ping(sandboxID string) error
	InstanceLoaded(ctx context.Context, sandboxID string) (bool, error)
	LoadModule(sandboxID, path string, memoryMB int) (wasmengine.LoadTimings, error)
	Instantiate(sandboxID string, caps wasmengine.Capabilities) error
	Invoke(sandboxID, export string) error
	Exec(sandboxID string, caps wasmengine.Capabilities, export string) (wasmengine.RunResult, error)
	StopInstance(sandboxID string) error
	Checkpoint(ctx context.Context, sandboxID, outDir string, meta wasmengine.SnapshotConfig) error
	Restore(sandboxID, dir string, caps wasmengine.Capabilities) error
	SetCapability(sandboxID string, caps wasmengine.Capabilities) error
	NetstatsTick(sandboxID string) (bytesIn, bytesOut int64, err error)
	SetNetworkBlocks(sandboxID string, blockIngress, blockEgress bool) error
	SetListenPort(sandboxID string, port int, host string) error
	ResolvedListenPort(sandboxID string) (int, error)
	ProxyHTTP(sandboxID string, guestPort int, w http.ResponseWriter, r *http.Request) error
}

WorkerClient is the IPC surface the driver uses inside a worker subprocess.

type WorkerClientFactory

type WorkerClientFactory func(socketPath string) WorkerClient

WorkerClientFactory builds a client for a worker socket path.

type WorkerSupervisor

type WorkerSupervisor interface {
	Ensure(ctx context.Context, sandboxID, socketPath string) error
	Stop(sandboxID string) error
}

WorkerSupervisor owns per-sandbox worker subprocesses.

type WorkerSupervisorSpawnCounter

type WorkerSupervisorSpawnCounter interface {
	SpawnCount(sandboxID string) int
}

Directories

Path Synopsis
Package statekv implements the host KV capability for durable WASM sandboxes (plans/wasm-runtime.md §4.6).
Package statekv implements the host KV capability for durable WASM sandboxes (plans/wasm-runtime.md §4.6).
Package toolhost implements the host-side toolbox for WASM sandboxes (plans/wasm-runtime.md §3).
Package toolhost implements the host-side toolbox for WASM sandboxes (plans/wasm-runtime.md §3).

Jump to

Keyboard shortcuts

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