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
- Variables
- func CloseTestExecutor()
- type Executor
- type ExecutorOption
- type Language
- type Option
- func WithAllowedHosts(hosts []string) Option
- func WithFSMaxFileSize(size int64) Option
- func WithFSMaxPathLength(length int) Option
- func WithFSMaxWriteSize(size int64) Option
- func WithHTTPMaxBodySize(size int64) Option
- func WithHTTPMaxURLLength(size int) Option
- func WithHTTPTimeout(d time.Duration) Option
- func WithKV() Option
- func WithKVConfig(cfg hostfunc.KVConfig) Option
- func WithMount(virtualPath, hostPath string, mode hostfunc.MountMode) Option
- func WithTimeout(d time.Duration) Option
- type Result
- type Session
- type SessionOption
- func WithAllowedPackages(packages []string) SessionOption
- func WithPackageInstall(enabled bool) SessionOption
- func WithPackages(path string) SessionOption
- func WithSessionAllowedHosts(hosts []string) SessionOption
- func WithSessionFSMaxFileSize(size int64) SessionOption
- func WithSessionHTTPMaxBodySize(size int64) SessionOption
- func WithSessionHTTPMaxURLLength(size int) SessionOption
- func WithSessionHTTPTimeout(d time.Duration) SessionOption
- func WithSessionKV() SessionOption
- func WithSessionKVConfig(cfg hostfunc.KVConfig) SessionOption
- func WithSessionMount(virtualPath, hostPath string, mode hostfunc.MountMode) SessionOption
- func WithSessionTimeout(d time.Duration) SessionOption
Constants ¶
const ( MountReadOnly = hostfunc.MountReadOnly MountReadWrite = hostfunc.MountReadWrite MountReadWriteCreate = hostfunc.MountReadWriteCreate )
Mount permission modes (re-exported from hostfunc for convenience).
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 ¶
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 ¶
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) 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.
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 ¶
WithAllowedHosts sets the list of hosts that HTTP requests can access.
func WithFSMaxFileSize ¶
WithFSMaxFileSize sets the maximum file size for read operations.
func WithFSMaxPathLength ¶
WithFSMaxPathLength sets the maximum path length for filesystem operations.
func WithFSMaxWriteSize ¶
WithFSMaxWriteSize sets the maximum content size for write operations.
func WithHTTPMaxBodySize ¶
WithHTTPMaxBodySize sets the maximum response body size for HTTP requests.
func WithHTTPMaxURLLength ¶
WithHTTPMaxURLLength sets the maximum URL length for HTTP requests.
func WithHTTPTimeout ¶
WithHTTPTimeout sets the timeout for individual HTTP requests.
func WithKVConfig ¶
WithKVConfig enables the key-value store with custom configuration.
func WithMount ¶
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 ¶
WithTimeout sets the maximum execution time.
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 ¶
CheckComplete checks if the code is a complete statement (for multi-line REPL input)
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.