executor

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package executor provides a WebAssembly-based code execution engine for running untrusted Python and JavaScript code in a secure sandbox.

Overview

The executor manages WASM module compilation, caching, and execution. It supports both stateless execution (single Run call) and stateful sessions (multiple Run calls with persistent state).

Basic Usage

exec, err := executor.New(hostfunc.NewRegistry())
if err != nil {
    log.Fatal(err)
}
defer exec.Close()

result := exec.Run(ctx, python.New(), `print("hello")`)
fmt.Println(result.Output)

Sessions

Sessions maintain state across multiple executions:

session, err := exec.NewSession(python.New())
if err != nil {
    log.Fatal(err)
}
defer session.Close()

session.Run(ctx, `x = 42`)
session.Run(ctx, `print(x)`)  // Output: 42

Capabilities

By default, sandboxed code has no access to filesystem, network, or other system resources. Enable capabilities explicitly:

session, _ := exec.NewSession(python.New(),
    executor.WithSessionAllowedHosts([]string{"api.example.com"}),
    executor.WithSessionMount("/data", "./input", hostfunc.MountReadOnly),
    executor.WithSessionKV(),
)

Language Interface

To add support for a new language, implement the Language interface. See github.com/caffeineduck/goru/language/python for an example.

Package executor provides a language-agnostic WASM code execution engine.

Index

Constants

View Source
const (
	MountReadOnly        = hostfunc.MountReadOnly
	MountReadWrite       = hostfunc.MountReadWrite
	MountReadWriteCreate = hostfunc.MountReadWriteCreate
)

Mount permission modes (re-exported from hostfunc for convenience).

View Source
const (
	MemoryLimit1MB   uint32 = 16    // 1 MB (16 pages)
	MemoryLimit16MB  uint32 = 256   // 16 MB (256 pages)
	MemoryLimit64MB  uint32 = 1024  // 64 MB (1024 pages)
	MemoryLimit256MB uint32 = 4096  // 256 MB (4096 pages) - default
	MemoryLimit1GB   uint32 = 16384 // 1 GB (16384 pages)
)

Memory limit constants for use with WithMemoryLimit. Each WASM page is 64KB.

Variables

View Source
var (
	ErrSessionClosed = errors.New("session closed")
	ErrSessionBusy   = errors.New("session busy")
)

Session errors.

Functions

func CloseTestExecutor

func CloseTestExecutor()

CloseTestExecutor closes the shared test executor. Call this in TestMain if needed, but typically not necessary.

Types

type Executor

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

Executor manages WASM runtimes and compiled module caching.

func GetTestExecutor

func GetTestExecutor() (*Executor, error)

GetTestExecutor returns a shared executor for testing. This avoids the 1.5s cold start on each test. The executor is created once and reused.

func New

func New(registry *hostfunc.Registry, opts ...ExecutorOption) (*Executor, error)

New creates an Executor with the given host function registry.

func (*Executor) Close

func (e *Executor) Close() error

Close releases all resources held by the Executor.

func (*Executor) NewSession

func (e *Executor) NewSession(lang Language, opts ...SessionOption) (*Session, error)

NewSession creates a stateful execution session for the given language. Sessions maintain state across multiple Run calls and support capabilities like HTTP, filesystem access, and key-value storage.

func (*Executor) Run

func (e *Executor) Run(ctx context.Context, lang Language, code string, opts ...Option) Result

Run executes code in the specified language.

type ExecutorOption

type ExecutorOption func(*executorConfig)

ExecutorOption configures the Executor at creation time.

func WithDiskCache

func WithDiskCache(dir ...string) ExecutorOption

WithDiskCache enables persistent compilation cache for faster CLI startup. Optionally provide a custom directory; otherwise uses ~/.cache/goru or XDG_CACHE_HOME/goru.

Examples:

executor.New(registry, executor.WithDiskCache())            // default dir
executor.New(registry, executor.WithDiskCache("/tmp/cache")) // custom dir

func WithMemoryLimit

func WithMemoryLimit(pages uint32) ExecutorOption

WithMemoryLimit sets the maximum memory available to WASM modules. Each page is 64KB. Default is 256MB.

func WithPrecompile

func WithPrecompile(langs ...Language) ExecutorOption

WithPrecompile compiles the specified languages at Executor creation time. This moves the compilation cost to startup rather than first execution.

type Language

type Language interface {
	// Name returns a unique identifier for this language (e.g., "python", "javascript").
	// Used as the cache key for compiled modules.
	Name() string

	// Module returns the WASM binary for the language interpreter.
	Module() []byte

	// WrapCode prepares user code for execution by prepending stdlib imports,
	// host function bindings, or any language-specific boilerplate.
	WrapCode(code string) string

	// Args returns the command-line arguments to pass to the WASM module.
	// For Python: []string{"python", "-c", code}
	// For QuickJS: []string{"qjs", "--std", "-e", code}
	Args(wrappedCode string) []string

	// SessionInit returns code to inject before stdlib for session mode.
	// This code sets a flag that the stdlib checks to enter session loop.
	SessionInit() string
}

Language defines the interface for a WASM-based language runtime. Implement this interface to add support for new languages (Python, JavaScript, etc.)

type Option

type Option func(*runConfig)

Option configures execution behavior.

func WithAllowedHosts

func WithAllowedHosts(hosts []string) Option

WithAllowedHosts sets the list of hosts that HTTP requests can access.

func WithFSMaxFileSize

func WithFSMaxFileSize(size int64) Option

WithFSMaxFileSize sets the maximum file size for read operations.

func WithFSMaxPathLength

func WithFSMaxPathLength(length int) Option

WithFSMaxPathLength sets the maximum path length for filesystem operations.

func WithFSMaxWriteSize

func WithFSMaxWriteSize(size int64) Option

WithFSMaxWriteSize sets the maximum content size for write operations.

func WithHTTPMaxBodySize

func WithHTTPMaxBodySize(size int64) Option

WithHTTPMaxBodySize sets the maximum response body size for HTTP requests.

func WithHTTPMaxURLLength

func WithHTTPMaxURLLength(size int) Option

WithHTTPMaxURLLength sets the maximum URL length for HTTP requests.

func WithHTTPTimeout

func WithHTTPTimeout(d time.Duration) Option

WithHTTPTimeout sets the timeout for individual HTTP requests.

func WithKV

func WithKV() Option

WithKV enables the key-value store with default limits.

func WithKVConfig

func WithKVConfig(cfg hostfunc.KVConfig) Option

WithKVConfig enables the key-value store with custom configuration.

func WithMount

func WithMount(virtualPath, hostPath string, mode hostfunc.MountMode) Option

WithMount adds a filesystem mount point with the specified permissions. The virtual path is what sandboxed code sees; host path is the actual location.

Examples:

executor.WithMount("/data", "./input", executor.MountReadOnly)
executor.WithMount("/output", "./results", executor.MountReadWrite)
executor.WithMount("/workspace", "./work", executor.MountReadWriteCreate)

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the maximum execution time.

type Result

type Result struct {
	Output   string
	Duration time.Duration
	Error    error
}

Result holds the output and metadata from code execution.

type Session

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

Session represents a stateful execution environment that maintains state across multiple Run calls. Create sessions via Executor.NewSession.

func (*Session) CheckComplete

func (s *Session) CheckComplete(ctx context.Context, code string) (bool, error)

CheckComplete checks if the code is a complete statement (for multi-line REPL input)

func (*Session) Close

func (s *Session) Close() error

Close terminates the session and releases resources.

func (*Session) Run

func (s *Session) Run(ctx context.Context, code string) Result

Run executes code in the session, maintaining state from previous calls.

func (*Session) RunRepl

func (s *Session) RunRepl(ctx context.Context, code string) Result

RunRepl executes code in REPL mode - expressions are auto-printed and result stored in _

type SessionOption

type SessionOption func(*sessionConfig)

SessionOption configures session behavior.

func WithAllowedPackages

func WithAllowedPackages(packages []string) SessionOption

WithAllowedPackages enables package installation restricted to the specified packages.

func WithPackageInstall

func WithPackageInstall(enabled bool) SessionOption

WithPackageInstall enables runtime package installation via install_pkg().

func WithPackages

func WithPackages(path string) SessionOption

WithPackages mounts a directory as /packages for Python imports.

func WithSessionAllowedHosts

func WithSessionAllowedHosts(hosts []string) SessionOption

WithSessionAllowedHosts enables HTTP and sets allowed hosts.

func WithSessionFSMaxFileSize

func WithSessionFSMaxFileSize(size int64) SessionOption

WithSessionFSMaxFileSize sets the maximum file size for read operations.

func WithSessionHTTPMaxBodySize

func WithSessionHTTPMaxBodySize(size int64) SessionOption

WithSessionHTTPMaxBodySize sets the maximum response body size for HTTP requests.

func WithSessionHTTPMaxURLLength

func WithSessionHTTPMaxURLLength(size int) SessionOption

WithSessionHTTPMaxURLLength sets the maximum URL length for HTTP requests.

func WithSessionHTTPTimeout

func WithSessionHTTPTimeout(d time.Duration) SessionOption

WithSessionHTTPTimeout sets the timeout for individual HTTP requests.

func WithSessionKV

func WithSessionKV() SessionOption

WithSessionKV enables the in-memory key-value store with default limits.

func WithSessionKVConfig

func WithSessionKVConfig(cfg hostfunc.KVConfig) SessionOption

WithSessionKVConfig enables the key-value store with custom limits.

func WithSessionMount

func WithSessionMount(virtualPath, hostPath string, mode hostfunc.MountMode) SessionOption

WithSessionMount adds a filesystem mount point.

func WithSessionTimeout

func WithSessionTimeout(d time.Duration) SessionOption

WithSessionTimeout sets the maximum execution time per Run call.

Jump to

Keyboard shortcuts

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