Documentation
¶
Overview ¶
Package worker runs untrusted Python from Go.
Each Runtime starts one spy-worker process, which owns a Small Python context and seals itself under the operating system's sandbox before it runs any code, and speaks the worker protocol (docs/packaging/protocol.md) over its standard input and output. Values cross by copy; anything else stays in the worker and is reached through an *Object handle. A crash, a protocol violation, or a worker that does not stop at its timeout loses the worker, and the runtime with it.
rt, err := worker.New(worker.Options{Timeout: 5 * time.Second})
if err != nil {
return err
}
defer rt.Close()
rt.Define("greet", func(rt *worker.Runtime, args []any, kwargs map[string]any) (any, error) {
if name, ok := args[0].(string); ok && len(args) == 1 {
return "hello " + name, nil
}
return nil, worker.Raise("TypeError", "greet(name)")
})
v, err := rt.Eval("greet('spy')") // "hello spy"
Values cross as Go values: nil (None), bool, int64 or *big.Int (int), float64, complex128, string, []byte, ByteArray, []any (list), Tuple, Set, FrozenSet, Dict, *Object, and *Function. Sending also accepts the other integer and float types and map[string]any, in sorted key order. Sets and dicts are kept as sequences, so the parent never hashes what the worker sends. A string holding a lone surrogate keeps its three-byte form.
Example ¶
package main
import (
"fmt"
"time"
"github.com/soasme/small-python/go/worker"
)
func main() {
rt, err := worker.New(worker.Options{Timeout: 5 * time.Second, MemoryLimit: 64 << 20})
if err != nil {
panic(err)
}
defer rt.Close()
rt.Define("greet", func(rt *worker.Runtime, args []any, kwargs map[string]any) (any, error) {
if name, ok := args[0].(string); ok && len(args) == 1 {
return "hello " + name, nil
}
return nil, worker.Raise("TypeError", "greet(name)")
})
v, err := rt.Eval("greet('spy')")
fmt.Println(v, err)
}
Output: hello spy <nil>
Index ¶
- Variables
- func Raise(typ, message string) error
- type ByteArray
- type Dict
- type Exception
- type FrozenSet
- type Func
- type Function
- type Item
- type Object
- type Op
- type Options
- type Runtime
- func (rt *Runtime) Call(function any, args []any, kwargs map[string]any) (any, error)
- func (rt *Runtime) Close() error
- func (rt *Runtime) Closed() bool
- func (rt *Runtime) Collect() (int64, error)
- func (rt *Runtime) Compare(object *Object, op Op, other any) (any, error)
- func (rt *Runtime) Contains(object *Object, item any) (bool, error)
- func (rt *Runtime) Define(name string, f Func) error
- func (rt *Runtime) Delete(name string) error
- func (rt *Runtime) Dir(object *Object) (any, error)
- func (rt *Runtime) Eval(source string) (any, error)
- func (rt *Runtime) Exec(source string) error
- func (rt *Runtime) Function(name string, f Func) *Function
- func (rt *Runtime) Get(name string) (value any, ok bool, err error)
- func (rt *Runtime) GetAttr(object *Object, name string) (any, error)
- func (rt *Runtime) GetItem(object *Object, key any) (any, error)
- func (rt *Runtime) Hash(object *Object) (int64, error)
- func (rt *Runtime) Iter(object *Object) (any, error)
- func (rt *Runtime) Len(object *Object) (int64, error)
- func (rt *Runtime) LoadNative(name, path string) error
- func (rt *Runtime) Mount(directory, path string, readOnly bool) error
- func (rt *Runtime) Next(object *Object) (value any, ok bool, err error)
- func (rt *Runtime) Pid() int
- func (rt *Runtime) RegisterModule(name string, members map[string]any, source string) error
- func (rt *Runtime) Repr(object *Object) (string, error)
- func (rt *Runtime) Set(name string, value any) error
- func (rt *Runtime) SetAttr(object *Object, name string, value any) error
- func (rt *Runtime) SetItem(object *Object, key, value any) error
- func (rt *Runtime) Str(object *Object) (string, error)
- func (rt *Runtime) Truth(object *Object) (bool, error)
- func (rt *Runtime) Usage() (steps, memory int64, err error)
- func (rt *Runtime) Version() string
- type Set
- type TimeoutError
- type Tuple
- type WorkerError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInvalid = errors.New("invalid use of the runtime")
ErrInvalid is matched, with errors.Is, by the errors of misuse: a closed runtime, a value of another runtime, a message over the limit, Eval in a host function.
Functions ¶
Types ¶
type ByteArray ¶
type ByteArray []byte
Tuple, Set, and FrozenSet are those engine types; a list is []any.
type Exception ¶
type Exception struct {
// Type is the class name, qualified by its module unless it is a builtin.
Type string
// Message is the text CPython's traceback shows after the type.
Message string
Filename string
Line int64
// Object is the exception itself, when the worker could send it.
Object *Object
// Cause is the host function's error the exception was raised for, if
// it escaped unchanged.
Cause error
}
An Exception is an engine exception that escaped, or one a host function raises.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/soasme/small-python/go/worker"
)
func main() {
rt, _ := worker.New(worker.Options{})
defer rt.Close()
failed := errors.New("disk on fire")
rt.Define("save", func(*worker.Runtime, []any, map[string]any) (any, error) { return nil, failed })
_, err := rt.Eval("save()")
var e *worker.Exception
fmt.Println(errors.As(err, &e), e.Type, errors.Is(err, failed))
}
Output: true RuntimeError true
type FrozenSet ¶
type FrozenSet []any
Tuple, Set, and FrozenSet are those engine types; a list is []any.
type Func ¶
A Func is a host function. It receives the runtime, for nested requests, and the call's arguments.
type Function ¶
type Function struct {
// contains filtered or unexported fields
}
A Function is a host function registered with a runtime, as a value to pass into it.
type Object ¶
type Object struct {
// contains filtered or unexported fields
}
An Object is a handle to an engine value held by the worker. Operate on it with the runtime's methods. The worker releases it with the next message after the garbage collector finds it unreachable.
Example ¶
package main
import (
"fmt"
"github.com/soasme/small-python/go/worker"
)
func main() {
rt, _ := worker.New(worker.Options{})
defer rt.Close()
rt.Exec("class Counter:\n def __init__(self): self.n = 0\n def bump(self, by=1):\n self.n += by\n return self.n")
counter, _ := rt.Call("Counter", nil, nil)
bump, _ := rt.GetAttr(counter.(*worker.Object), "bump")
rt.Call(bump, nil, nil)
n, _ := rt.Call(bump, nil, map[string]any{"by": 10})
field, _ := rt.GetAttr(counter.(*worker.Object), "n")
fmt.Println(n, field)
}
Output: 11 11
type Options ¶
type Options struct {
// Bare leaves out the standard module sys.
Bare bool
// StepLimit bounds the evaluation steps of each top-level Eval or Exec;
// 0 is unlimited. Exceeding it raises RuntimeError in the engine.
StepLimit uint64
// MemoryLimit bounds the bytes the engine may hold; 0 is unlimited.
// Exceeding it raises MemoryError in the engine.
MemoryLimit uint64
// OutputLimit bounds the bytes each top-level Eval or Exec may print;
// 0 is unlimited. Exceeding it raises RuntimeError in the engine.
OutputLimit uint64
// Timeout bounds the time one operation may spend running in the
// worker, host functions excluded; 0 is unlimited. Exceeding it stops
// the operation with a *TimeoutError.
Timeout time.Duration
// MessageLimit is the largest message in bytes, either direction;
// 0 means 64 MiB.
MessageLimit uint32
// Output receives printed text; nil means os.Stdout.
Output io.Writer
// Loader maps a module name to its source, or reports that there is
// none. For `import pkg.mod` it is asked for pkg.mod.__init__ (a
// package), then pkg.mod; source for pkg.mod.__namespace__ makes a
// namespace package.
Loader func(name string) (source string, ok bool)
// Policy is asked before the engine opens a file ("open": file, mode),
// imports a module for the first time ("import": name), executes source
// text ("exec": source), or reads input ("input": prompt, if given). An
// error refuses the event; one that is not an *Exception raises
// PermissionError.
Policy func(event string, args Tuple) error
// Worker is the spy-worker executable; empty means the one on $PATH.
Worker string
}
Options configure a Runtime. The zero value is the default.
Example ¶
package main
import (
"fmt"
"time"
"github.com/soasme/small-python/go/worker"
)
func main() {
rt, _ := worker.New(worker.Options{StepLimit: 100_000, Timeout: time.Second})
defer rt.Close()
err := rt.Exec("while True: pass")
fmt.Println(err.(*worker.Exception).Type, rt.Closed())
v, _ := rt.Eval("1 + 1")
fmt.Println(v)
}
Output: RuntimeError false 2
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
A Runtime is one Small Python engine in its own worker process. It is not safe for concurrent use. While a host function runs, it receives the runtime and may make nested requests (Call, Get, object operations, ...), but not Eval or Exec.
func (*Runtime) Close ¶
Close ends the worker: it closes the worker's input, waits a second for it to exit, and terminates it otherwise. In a host function of the runtime it fails with ErrInvalid, as eval and exec do.
func (*Runtime) Eval ¶
Eval runs source and returns the value of its last expression statement.
Example ¶
package main
import (
"fmt"
"github.com/soasme/small-python/go/worker"
)
func main() {
rt, _ := worker.New(worker.Options{})
defer rt.Close()
v, _ := rt.Eval("[1, 2.5, 'three', (4,), {'five': None}, 2 ** 64]")
fmt.Printf("%#v\n", v.([]any)[:5])
fmt.Println(v.([]any)[5])
}
Output: []interface {}{1, 2.5, "three", worker.Tuple{4}, worker.Dict{worker.Item{Key:"five", Value:interface {}(nil)}}} 18446744073709551616
func (*Runtime) Function ¶
Function returns a host function as a value to pass into the engine, where it becomes a builtin function named name. The runtime keeps f until it ends.
func (*Runtime) LoadNative ¶ added in v0.8.0
LoadNative opens the shared library at path, a native module built with spy-module.h, in the worker, so that `import name` runs its init there. The policy is asked first, with "dlopen" (name, path), path resolved as the worker receives it. Like Mount, it is refused once the worker has run code; the library's init and functions then run inside the sandbox.
func (*Runtime) Mount ¶
Mount lets the engine's open() reach a host directory at the absolute engine path path, or at its resolved host path when path is empty. Mounts are fixed once the worker has run code.
func (*Runtime) RegisterModule ¶
RegisterModule makes `import name` create a module whose attributes are members, then run source in it. Registering a name again replaces it.
type TimeoutError ¶
A TimeoutError reports that an operation ran past the runtime's timeout. The engine stops the operation and the runtime stays open; a worker that does not stop within a grace period is ended, which loses the runtime.
Example ¶
package main
import (
"errors"
"fmt"
"time"
"github.com/soasme/small-python/go/worker"
)
func main() {
rt, _ := worker.New(worker.Options{Timeout: 200 * time.Millisecond})
defer rt.Close()
err := rt.Exec("while True: pass")
var timeout *worker.TimeoutError
fmt.Println(errors.As(err, &timeout), rt.Closed())
}
Output: true false
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
type WorkerError ¶
type WorkerError struct {
Message string
// State is the worker's exit, when it exited on its own.
State *os.ProcessState
}
A WorkerError reports that the worker was lost: it crashed, broke the protocol, or was ended.
func (*WorkerError) Error ¶
func (e *WorkerError) Error() string