jsrt

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package jsrt isolates the embedded JavaScript runtime behind an engine-agnostic sandbox abstraction so plugins run in pooled, memory-capped, preemptively time-bounded ES2023 isolates without CGo.

Index

Constants

View Source
const (
	// MaxBundleBytes caps a plugin's compiled server.js bundle at 5 MiB.
	MaxBundleBytes = 5 * 1024 * 1024
	// DefaultPoolSize is the default number of warm JS isolates maintained per plugin.
	DefaultPoolSize = 2
	// DefaultMemoryLimit is the default per-isolate heap limit (64 MiB).
	DefaultMemoryLimit = 64 * 1024 * 1024
	// DefaultMaxStackSize caps the QuickJS call stack per isolate (1 MiB).
	DefaultMaxStackSize = 1 * 1024 * 1024
	// DefaultTimeout is the default execution timeout for a single JS call.
	DefaultTimeout = 2 * time.Second
	// DefaultMaxTimerDelay bounds setTimeout delays inside a single invocation.
	DefaultMaxTimerDelay = 30 * time.Second
)

Variables

View Source
var (
	// ErrTimeout indicates JS execution exceeded the per-call deadline and the isolate was terminated.
	ErrTimeout = errors.New("jsrt: execution timed out")
	// ErrOutOfMemory indicates JS execution hit the isolate's 64 MiB memory cap.
	ErrOutOfMemory = errors.New("jsrt: memory limit exceeded")
	// ErrPoolClosed indicates Borrow or Do was called after DrainAndClose started.
	ErrPoolClosed = errors.New("jsrt: runtime pool closed")
	// ErrBundleTooLarge indicates the JS bundle exceeds MaxBundleBytes.
	ErrBundleTooLarge = errors.New("jsrt: bundle exceeds maximum allowed size")
	// ErrInvalidModule indicates the bundle could not be compiled or lacks expected exports.
	ErrInvalidModule = errors.New("jsrt: invalid module")
)

Functions

This section is empty.

Types

type CallStats

type CallStats struct {
	Duration  time.Duration
	TimedOut  bool
	OOM       bool
	Recreated bool
}

CallStats reports resource usage and failure mode for a single JS invocation.

type Engine

type Engine interface {
	Compile(ctx context.Context, filename string, code []byte) ([]byte, error)
	NewInstance(ctx context.Context, spec InstanceSpec) (Instance, error)
	Close() error
}

Engine compiles plugin bundles and instantiates isolated JS runtimes.

func NewEngine

func NewEngine(opts ...EngineOption) (Engine, error)

NewEngine creates a QuickJS-NG/Wazero runtime engine and warms up the shared precompiled WASM module with preemption enabled.

type EngineOption

type EngineOption func(*engineConfig)

EngineOption customizes Engine construction.

func WithCacheDir

func WithCacheDir(dir string) EngineOption

WithCacheDir stores compiled wazero machine code caches on disk across restarts.

func WithLogger

func WithLogger(log *slog.Logger) EngineOption

WithLogger sets the fallback logger for the engine.

type HostFunc

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

HostFunc is a Go capability callable (and awaitable via Promise) from JS.

type Instance

type Instance interface {
	ID() uint64
	Eval(ctx context.Context, filename, code string) (any, CallStats, error)
	InvokeExport(ctx context.Context, method string, args ...any) (any, CallStats, error)
	InvokeGlobal(ctx context.Context, path string, args ...any) (any, CallStats, error)
	RegisterHostFunc(name string, fn HostFunc) error
	SetGlobalJSON(name string, value any) error
	Tainted() bool
	Close() error
}

Instance is one stateful, single-threaded JS isolate checked out from a Pool. Callers must never share one Instance concurrently across goroutines without returning it to the Pool.

type InstanceSpec

type InstanceSpec struct {
	ID       string
	Filename string
	Code     []byte
	Bytecode []byte
	Limits   Limits
	Log      *slog.Logger
	// Prepare runs inside a fresh isolate before evaluating the module so host
	// bridges and globals can be registered cleanly.
	Prepare func(ctx context.Context, inst Instance) error
	// OnReady runs right after the module evaluates inside the isolate (e.g. to
	// run plugin setup(ctx) and populate per-isolate handler closures).
	OnReady func(ctx context.Context, inst Instance) error
}

InstanceSpec configures a single JS isolate created by Engine.

type JSError

type JSError struct {
	Message string
	Stack   string
}

JSError represents an uncaught JavaScript exception or rejected Promise.

func (*JSError) Error

func (e *JSError) Error() string

type Limits

type Limits struct {
	PoolSize       int
	MemoryLimit    int
	MaxStackSize   int
	Timeout        time.Duration
	MaxBundleBytes int
}

Limits configures isolate resource bounds for a plugin pool. Zero fields fall back to package defaults.

type Pool

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

Pool manages warm JS isolates (default 2) with bounded checkout, automatic replacement of tainted isolates, and graceful in-flight draining on shutdown.

func NewPool

func NewPool(engine Engine, spec PoolSpec) (*Pool, error)

NewPool compiles spec.Code once, warms PoolSize isolates (running OnSetup on the first and OnWarm on the rest), and returns a ready pool.

func (*Pool) Borrow

func (p *Pool) Borrow(ctx context.Context) (Instance, error)

Borrow checks out one warm isolate from the pool, waiting until one is available, ctx expires, or DrainAndClose is called.

func (*Pool) Broadcast

func (p *Pool) Broadcast(ctx context.Context, fn func(Instance) (CallStats, error)) error

Broadcast borrows every warm isolate in the pool (up to PoolSize) and invokes fn on each one, ensuring state notifications (such as settings updates) reach all isolates rather than only a single checked-out instance.

func (*Pool) Do

func (p *Pool) Do(ctx context.Context, fn func(Instance) (CallStats, error)) (CallStats, error)

Do borrows an isolate, invokes fn, records stats, and returns or replaces it cleanly.

func (*Pool) DrainAndClose

func (p *Pool) DrainAndClose(timeout time.Duration) error

DrainAndClose stops new checkouts, waits up to timeout for in-flight calls to complete, and closes all pooled isolates.

func (*Pool) RecordStats

func (p *Pool) RecordStats(stats CallStats)

RecordStats updates pool failure counters from CallStats after an invocation.

func (*Pool) ReplaceOnBroken

func (p *Pool) ReplaceOnBroken(inst Instance)

ReplaceOnBroken closes a broken/tainted isolate and asynchronously replenishes the pool with a freshly warmed isolate unless shutting down.

func (*Pool) Return

func (p *Pool) Return(inst Instance)

Return returns an isolate to the pool, or replaces it if tainted or unhealthy.

func (*Pool) Stats

func (p *Pool) Stats() PoolStats

Stats returns a snapshot of current pool utilization and fault counters.

type PoolSpec

type PoolSpec struct {
	ID       string
	Filename string
	Code     []byte
	Limits   Limits
	Log      *slog.Logger
	Prepare  func(ctx context.Context, inst Instance) error
	// OnSetup runs once on the first warm instance so the host can collect declared
	// hooks/routes before adding the instance into the serving pool.
	OnSetup func(ctx context.Context, inst Instance) error
	// OnWarm runs on each additional or replacement instance to replay setup
	// handler bindings cleanly into that isolate's heap.
	OnWarm func(ctx context.Context, inst Instance) error
}

PoolSpec configures a warm isolate pool for a single plugin.

type PoolStats

type PoolStats struct {
	Size      int    `json:"size"`
	Idle      int    `json:"idle"`
	InUse     int64  `json:"inUse"`
	Recreated uint64 `json:"recreated"`
	Timeouts  uint64 `json:"timeouts"`
	OOMs      uint64 `json:"ooms"`
}

PoolStats summarizes live runtime metrics for an isolate pool.

Jump to

Keyboard shortcuts

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