worker

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func Raise

func Raise(typ, message string) error

Raise returns an exception for a host function to raise: the engine raises the builtin class typ, or RuntimeError when there is none.

Types

type ByteArray

type ByteArray []byte

Tuple, Set, and FrozenSet are those engine types; a list is []any.

type Dict

type Dict []Item

A Dict is a dict's items, in order.

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

func (*Exception) Error

func (e *Exception) Error() string

func (*Exception) Unwrap

func (e *Exception) Unwrap() error

type FrozenSet

type FrozenSet []any

Tuple, Set, and FrozenSet are those engine types; a list is []any.

type Func

type Func func(rt *Runtime, args []any, kwargs map[string]any) (any, error)

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.

func (*Function) String

func (f *Function) String() string

type Item

type Item struct {
	Key, Value any
}

An Item is one key and value of a Dict.

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

func (*Object) String

func (o *Object) String() string

type Op

type Op int

Op is a rich comparison of Runtime.Compare.

const (
	Lt Op = 11 + iota
	Le
	Eq
	Ne
	Gt
	Ge
)

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 New

func New(opts Options) (*Runtime, error)

New starts a worker and waits until it is ready.

func (*Runtime) Call

func (rt *Runtime) Call(function any, args []any, kwargs map[string]any) (any, error)

Call calls function: a global name (string), an *Object, or a *Function.

func (*Runtime) Close

func (rt *Runtime) Close() error

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) Closed

func (rt *Runtime) Closed() bool

Closed reports whether the runtime was closed or lost.

func (*Runtime) Collect

func (rt *Runtime) Collect() (int64, error)

Collect runs the cycle collector and returns the number of values freed.

func (*Runtime) Compare

func (rt *Runtime) Compare(object *Object, op Op, other any) (any, error)

Compare is object < other, or another rich comparison.

func (*Runtime) Contains

func (rt *Runtime) Contains(object *Object, item any) (bool, error)

Contains is item in object.

func (*Runtime) Define

func (rt *Runtime) Define(name string, f Func) error

Define binds a host function as the global name.

func (*Runtime) Delete

func (rt *Runtime) Delete(name string) error

Delete deletes a global; a KeyError when there is none.

func (*Runtime) Dir

func (rt *Runtime) Dir(object *Object) (any, error)

Dir is dir(object).

func (*Runtime) Eval

func (rt *Runtime) Eval(source string) (any, error)

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) Exec

func (rt *Runtime) Exec(source string) error

Exec runs source for its effects.

func (*Runtime) Function

func (rt *Runtime) Function(name string, f Func) *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) Get

func (rt *Runtime) Get(name string) (value any, ok bool, err error)

Get reads a global, falling back to builtins; ok is false when there is none.

func (*Runtime) GetAttr

func (rt *Runtime) GetAttr(object *Object, name string) (any, error)

GetAttr is getattr(object, name).

func (*Runtime) GetItem

func (rt *Runtime) GetItem(object *Object, key any) (any, error)

GetItem is object[key].

func (*Runtime) Hash

func (rt *Runtime) Hash(object *Object) (int64, error)

Hash is hash(object).

func (*Runtime) Iter

func (rt *Runtime) Iter(object *Object) (any, error)

Iter is iter(object).

func (*Runtime) Len

func (rt *Runtime) Len(object *Object) (int64, error)

Len is len(object).

func (*Runtime) LoadNative added in v0.8.0

func (rt *Runtime) LoadNative(name, path string) error

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

func (rt *Runtime) Mount(directory, path string, readOnly bool) error

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) Next

func (rt *Runtime) Next(object *Object) (value any, ok bool, err error)

Next is next(object); ok is false at the end.

func (*Runtime) Pid

func (rt *Runtime) Pid() int

Pid returns the worker's process id.

func (*Runtime) RegisterModule

func (rt *Runtime) RegisterModule(name string, members map[string]any, source string) error

RegisterModule makes `import name` create a module whose attributes are members, then run source in it. Registering a name again replaces it.

func (*Runtime) Repr

func (rt *Runtime) Repr(object *Object) (string, error)

Repr is repr(object).

func (*Runtime) Set

func (rt *Runtime) Set(name string, value any) error

Set binds a global.

func (*Runtime) SetAttr

func (rt *Runtime) SetAttr(object *Object, name string, value any) error

SetAttr is setattr(object, name, value).

func (*Runtime) SetItem

func (rt *Runtime) SetItem(object *Object, key, value any) error

SetItem is object[key] = value.

func (*Runtime) Str

func (rt *Runtime) Str(object *Object) (string, error)

Str is str(object).

func (*Runtime) Truth

func (rt *Runtime) Truth(object *Object) (bool, error)

Truth is bool(object).

func (*Runtime) Usage added in v0.5.0

func (rt *Runtime) Usage() (steps, memory int64, err error)

Usage returns the steps the last operation spent and the bytes the engine holds.

func (*Runtime) Version

func (rt *Runtime) Version() string

Version returns the engine version the worker reported.

type Set

type Set []any

Tuple, Set, and FrozenSet are those engine types; a list is []any.

type TimeoutError

type TimeoutError struct {
	Timeout time.Duration
}

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 Tuple

type Tuple []any

Tuple, Set, and FrozenSet are those engine types; a list is []any.

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

Jump to

Keyboard shortcuts

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