worker

package
v0.0.0-...-53bd38a Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 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 one script as a long-lived child process and exchanges line-delimited JSON with it: one object per line on the child's stdin, one per line back on its stdout. It knows nothing about HTTP or the pipeline; the script plugin builds the messages and reads the replies.

The protocol:

  • The child's first line is its handshake (see Handshake). Nothing is sent until it arrives.
  • Each Call writes one object carrying an "id" and reads lines until one is an object with that id. Every other line is the script's own output — a print, a library's warning — and is returned with the reply as Logs, so stray output cannot corrupt the exchange.
  • A Call can hold parts of the message back. Their names are in the message's "more" list. Before it replies, the child can ask for one with {"id": N, "fetch": name}, and gets {"id": N, "fetch": name, "value": ...} on its stdin. So a script that never reads a large part costs nothing for it on either side of the pipe.
  • Calls are serialised: a script is a plain read-reply loop, and its state cannot race.
  • A script that takes longer than the call timeout to answer a message it was sent has its whole process group killed. So does a child that exits. Either way a new one is started in the background after a backoff, and the script's in-memory state is gone. A call never waits for a start: one that finds no running child fails at once (ErrStarting), so a slow-starting script costs requests nothing.

Index

Constants

View Source
const (
	DefaultStartTimeout = 5 * time.Second
	DefaultCallTimeout  = 2 * time.Second
)

Defaults for a Config that leaves them zero.

View Source
const Protocol = 2

Protocol is the handshake version this package speaks.

Variables

View Source
var ErrBackoff = errors.New("worker: restarting after a failure")

ErrBackoff is returned by Call while a crashed worker waits to be restarted.

View Source
var ErrStarting = errors.New("worker: script is starting")

ErrStarting is returned by Call while the child is being started in the background.

Functions

func Environ

func Environ(base []string, sdkDir string) []string

Environ returns the environment a script runs with: base without the proxy variables, PATH replaced by the user's login-shell PATH when one can be read, and PYTHONPATH led by sdkDir so `import cortex` resolves.

The login PATH matters on macOS: launchd starts the service with /usr/bin:/bin:/usr/sbin:/sbin, where `#!/usr/bin/env python3` finds the system Python rather than the one the user installed and tested the script with.

Types

type Config

type Config struct {
	// Path is the executable: the script itself, run through its shebang.
	Path string
	// Args are passed after Path. Empty for a script.
	Args []string
	// Env is the child's whole environment. See Environ.
	Env []string
	// StartTimeout bounds the wait for the handshake.
	StartTimeout time.Duration
	// CallTimeout bounds one Call when its context carries no earlier deadline.
	CallTimeout time.Duration
}

Config describes the child to run.

type Handshake

type Handshake struct {
	// Cortex is the protocol version the child speaks; it must be Protocol.
	Cortex int `json:"cortex"`
	// Hooks names the hooks the script implements: "request", "response".
	Hooks []string `json:"hooks"`
	// Enforce: the script's denies and edits apply. False is shadow mode.
	Enforce bool `json:"enforce"`
	// RewriteResponse: the script may rewrite response bodies.
	RewriteResponse bool `json:"rewrite_response"`
}

Handshake is the child's first line.

func (Handshake) Has

func (h Handshake) Has(hook string) bool

Has reports whether the script implements hook.

type Pool

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

Pool keeps workers alive across pipeline builds. A config reload rebuilds every plugin, and a script that restarted on every build would lose its state whenever anything at all in the config changed. The pool hands the next build the worker the previous build was using, for as long as the script file and the child's command and environment are unchanged.

A build is a holder. It acquires workers while it is configured, activates once its pipeline starts, and releases them when its pipeline is shut down. A worker stops when no holder has it, so:

  • an edited script gets a new worker beside the old one, and the old one keeps serving the running pipeline until that pipeline is drained and shut down;
  • a removed script's worker stops with the last pipeline that ran it;
  • a build that never starts — a reload refused after its plugins were configured — is never shut down either, so its holds would leak. Activate sweeps them: builds are made one at a time, so any holder older than the one starting that never started itself was abandoned.

func NewPool

func NewPool() *Pool

NewPool returns an empty pool.

func (*Pool) Acquire

func (p *Pool) Acquire(holder int, cfg Config, hash string) *Worker

Acquire returns the worker for this version of cfg.Path and this cfg, starting a new one when none runs it.

func (*Pool) Activate

func (p *Pool) Activate(holder int)

Activate marks holder's pipeline as running, and stops every worker held only by builds that were abandoned before it.

func (*Pool) NewHolder

func (p *Pool) NewHolder() int

NewHolder returns a holder id for one build. Ids increase, which is what lets Activate tell an abandoned build from a live one.

func (*Pool) Release

func (p *Pool) Release(holder int)

Release gives up every worker holder holds, stopping each one no other holder has.

type Reply

type Reply struct {
	// Line is the reply object, id included.
	Line json.RawMessage
	// Logs are the lines the script wrote that were not the reply, oldest first.
	Logs []string
}

Reply is what one Call returned.

type Worker

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

Worker is one script's child process, restarted as needed. Safe for concurrent use; calls are serialised. Workers from one Pool entry share a child and differ only in their call timeout.

func New

func New(cfg Config) *Worker

New returns a worker for cfg. Nothing runs until Start or the first Call.

func (*Worker) Call

func (w *Worker) Call(ctx context.Context, msg, more map[string]any) (Reply, error)

Call sends msg with a fresh "id" and returns the child's reply to it. msg must marshal to a JSON object. more holds the parts the child gets only when it fetches them; each is encoded at that time.

func (*Worker) CallTimeout

func (w *Worker) CallTimeout() time.Duration

CallTimeout is the bound on each of w's calls.

func (Worker) Handshake

func (w Worker) Handshake() Handshake

Handshake returns the last handshake the child sent; zero before the first start.

func (Worker) Start

func (w Worker) Start(ctx context.Context) (Handshake, error)

Start runs the child and waits for its handshake, or for the start already in progress. Calling it on a running worker returns the running child's handshake. ctx bounds the wait; the start itself is bounded by StartTimeout.

func (Worker) Stop

func (w Worker) Stop()

Stop ends the child and refuses further calls.

Jump to

Keyboard shortcuts

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