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
- Variables
- type CallStats
- type Engine
- type EngineOption
- type HostFunc
- type Instance
- type InstanceSpec
- type JSError
- type Limits
- type Pool
- func (p *Pool) Borrow(ctx context.Context) (Instance, error)
- func (p *Pool) Broadcast(ctx context.Context, fn func(Instance) (CallStats, error)) error
- func (p *Pool) Do(ctx context.Context, fn func(Instance) (CallStats, error)) (CallStats, error)
- func (p *Pool) DrainAndClose(timeout time.Duration) error
- func (p *Pool) RecordStats(stats CallStats)
- func (p *Pool) ReplaceOnBroken(inst Instance)
- func (p *Pool) Return(inst Instance)
- func (p *Pool) Stats() PoolStats
- type PoolSpec
- type PoolStats
Constants ¶
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 ¶
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 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 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 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 ¶
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 ¶
Borrow checks out one warm isolate from the pool, waiting until one is available, ctx expires, or DrainAndClose is called.
func (*Pool) Broadcast ¶
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 ¶
Do borrows an isolate, invokes fn, records stats, and returns or replaces it cleanly.
func (*Pool) DrainAndClose ¶
DrainAndClose stops new checkouts, waits up to timeout for in-flight calls to complete, and closes all pooled isolates.
func (*Pool) RecordStats ¶
RecordStats updates pool failure counters from CallStats after an invocation.
func (*Pool) ReplaceOnBroken ¶
ReplaceOnBroken closes a broken/tainted isolate and asynchronously replenishes the pool with a freshly warmed isolate unless shutting down.
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.