worker

package
v0.169.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 42 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 is the ws-worker client (main plan §4, §6): a `gofer worker` process dials the central hub over a single WebSocket, registers, and then receives job dispatches which it runs LOCALLY with its own job.Service / local runner (review #8: the worker re-validates project/agent/exec with its own config). It streams each local job's stdout/stderr back to the hub as log frames and pushes the authoritative terminal result.

WP3/C7 scope: Run is a reconnect loop with exponential backoff + full jitter that rotates through MULTIPLE hub addresses (server_link.urls) on failure, re-registering on each (re)connect (§5.2). Each connection runs a heartbeat ping sender + a read-deadline'd recv loop so a half-open hub is detected (§5.1). The loop exits only when ctx is cancelled (worker shutdown).

Index

Constants

View Source
const (
	// DefaultInitialBackoff is the first-retry base wait (full-jitter exponent base).
	DefaultInitialBackoff = 1 * time.Second
	// DefaultMaxBackoff caps the backoff so a long hub outage retries at a bounded
	// (≤ this) cadence.
	DefaultMaxBackoff = 30 * time.Second
	// DefaultPingInterval is the worker's heartbeat ping cadence (symmetric with the
	// hub, so a half-open hub is detected by the worker too, §5.1).
	DefaultPingInterval = 15 * time.Second
	// DefaultReadDeadline bounds a single read on the worker side (half-open hub
	// detection). Must be ≥ 2× the ping interval, mirroring the hub invariant.
	DefaultReadDeadline = 45 * time.Second
)

Reconnect / heartbeat defaults (P3 §4.2 / §4.1). All overridable via the worker.yaml server_link.reconnect block; these apply when unset.

View Source
const (
	FlagUpgradeFrom  = "upgrade-from"  // pid of the process being replaced
	FlagUpgradeID    = "upgrade-id"    // Upgrade.RequestID, echoed in Register.UpgradeID
	FlagUpgradeReady = "upgrade-ready" // marker file the new process writes once registered
)

Flags the replacement process is started with (appended to the original args by the old process and stripped again before the next upgrade). They are hidden plumbing, not an operator interface.

Variables

This section is empty.

Functions

func JobXferBridge

func JobXferBridge(cl *Client, lim xfer.Limits) job.XferBridge

JobXferBridge builds the worker's job file seam over a connected client. limits are this worker's own caps (its config's server.xfer), resolved by the command from the same core.Build the job service came from.

func Probe

func Probe(ctx context.Context, url, token string, reg wsproto.Register) (wsproto.Registered, error)

Probe dials one hub address and performs a SINGLE register handshake: it sends the register frame the caller built (from the same worker.yaml a real worker would start with), reads the ack, closes the connection and returns the ack.

It exists for `gofer worker doctor` (CFG-09): the operator wants to know whether THIS machine can reach the hub and whether the hub accepts its worker_id + token, before (or instead of) reading the worker log to find out.

It deliberately does NOT reuse Client.runSession: that path publishes the connection, seeds the per-session transfer base, opens a policy session and then runs the recv loop — none of which a one-shot check may touch. What the two DO share is the wire shape (wsproto.Register/Registered), the bearer header and the same read envelope helper, so a probe cannot silently drift from what a real register sends.

A NOT-accepted ack is not an error: it carries the hub's own reason (worker_id not bound to this token, protocol too old) and the caller prints it verbatim. Only transport/decode failures come back as an error.

func ReadPolicyCacheFile

func ReadPolicyCacheFile(path, workerID string) (*wsproto.Policy, error)

ReadPolicyCacheFile reads a last-known-good policy cache. It returns (nil, nil) when the file is absent (never applied / invalidated) and an error when it is present but unusable (half file, bad JSON, or a different worker's cache) — a caller treats any error as "no cache" with a WARN, never a panic.

func Serve

func Serve(cl *Client, wc *config.WorkerConfig) error

Serve runs a built worker Client until SIGINT/SIGTERM, owning the signal/ctx start-stop orchestration (D-B4: moved out of the worker command, which now only loads config, builds the local Core + Client and calls Serve). It mirrors serve's graceful-shutdown style: a signal cancels the worker ctx, which makes Client.Run exit its reconnect/recv/heartbeat loops and close the connection (going-away); signal.Stop on return so the signal goroutine never leaks (ws-worker §5.6). wc supplies the process-level settings the client needs from the worker's own config (the structured startup log, the XFER-01 transfer deadline).

func StripUpgradeArgs

func StripUpgradeArgs(args []string) []string

StripUpgradeArgs removes the handover flags (both "--flag value" and "--flag=value" spellings) so a process that was itself started by an upgrade can start the next one.

func SwitchBinary

func SwitchBinary(target, candidate string) (rollback func() error, err error)

SwitchBinary atomically puts candidate at target and leaves one rollback copy at target.old. On Unix rename is atomic; on Windows a running executable may be renamed, so the same sequence works without stopping the old process first.

func VerifyUpgradeFile

func VerifyUpgradeFile(path string, size int64, wantSHA256 string) error

VerifyUpgradeFile checks the worker-side download before it can replace the running binary. Size and digest are both mandatory protocol facts.

func WritePolicyCacheFile

func WritePolicyCacheFile(path, workerID string, p *wsproto.Policy, seq uint64) error

WritePolicyCacheFile atomically writes the last-known-good policy cache to path (same-dir temp + rename, 0600). Callers MkdirAll the parent. It is a pure file helper — the caller (writePolicyCacheGuarded) owns the token/ordering guards.

func WriteReadyMarker

func WriteReadyMarker(path, upgradeID string) error

WriteReadyMarker records that the process registered after an upgrade handover.

Types

type ChildProc

type ChildProc interface {
	Pid() int
	// Exited is closed when the process has exited.
	Exited() <-chan struct{}
	Kill() error
}

ChildProc is the started replacement process.

type Client

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

Client connects one worker to the hub. It is constructed with the resolved hub address list + token + the worker's identity and local job service.

func New

func New(cfg Config, jobs Jobs) *Client

New builds a worker client. jobs is the worker's local job service (built from its own config by the command).

func (*Client) OnSessionStart

func (cl *Client) OnSessionStart(localID string, sess *ptyrunner.PtySession)

OnSessionStart implements ptyrunner.SessionObserver: the PtyRunner calls it (synchronously, once) right after a pty session starts, handing us SOLE-reader ownership. It MUST NOT block (SessionObserver contract) — it only delivers the session to a parked waiter or buffers it for a waiter that has not arrived yet (the pump itself is started later by handleDispatch, T5). localID is the worker's LOCAL job id (= the id waitSession keys on).

func (*Client) Run

func (cl *Client) Run(ctx context.Context) error

Run is the worker's reconnect supervisor (C7, §5.2): it repeatedly dials a hub address (rotating through cl.urls on failure), registers and runs one connection session until the connection drops, then backs off (exponential + full jitter, reset after a successful registration) and retries. It returns only when ctx is cancelled (worker shutdown / signal) — a transient hub outage never permanently disconnects the worker.

func (*Client) SetExit

func (cl *Client) SetExit(f func())

SetExit installs the graceful-shutdown trigger an upgrade handover calls once the new process is up. worker.Serve wires it to its signal context.

func (*Client) SetXferTimeout

func (cl *Client) SetXferTimeout(d time.Duration)

SetXferTimeout overrides the single-transfer deadline. worker.Serve calls it from the worker's own config before any frame can arrive (the hub cannot know this machine's budget); <= 0 keeps the default.

func (*Client) WaitIdle

func (cl *Client) WaitIdle(ctx context.Context) bool

WaitIdle waits until all currently-running dispatch goroutines have returned, or ctx is cancelled. It is primarily a test/shutdown synchronization helper; the reconnect loop intentionally does not wait on dispatches between sessions.

type Config

type Config struct {
	WorkerID            string
	URLs                []string
	Token               string
	Labels              []string
	Projects            []string
	InteractiveProjects []string
	Agents              []string
	// AgentCaps is the typed agent capability report (built from the worker config's
	// agents map by the command); Agents stays the bare key list.
	AgentCaps []wsproto.AgentBrief
	// Tools are the worker's declared external tools (CFG-16), reported on register.
	Tools []wsproto.ToolBrief
	// GoferVersion is the worker binary's display version (buildinfo).
	GoferVersion string
	MaxConc      int
	// XferLimits are this worker's file-transfer caps (its own config's server.xfer),
	// used by the job file seam (XFER-01 X2): the collect step filters what it reports
	// with them, and OwnsArtifacts stays false — the hub owns the job row, so it pulls
	// a collected file back itself.
	XferLimits xfer.Limits
	// Reload re-reads and applies the worker's config, returning the capabilities of
	// the config it applied (see ReloadFunc). Injected by the command; nil disables
	// config reload (a reload request is then answered with an error, never silently
	// accepted).
	Reload ReloadFunc
	// Upgrade overrides the upgrade implementation (tests); UpgradeDeps builds the
	// default one from the command layer's paths. Both nil = remote upgrade refused.
	Upgrade     UpgradeFunc
	UpgradeDeps *UpgradeDeps
	// Handover is set when this process was started by an upgrade handover.
	Handover *Handover
	// PolicyMode is true when the worker sources projects from server Policy (roots
	// configured, T5-A). LEGACY/EMPTY workers leave it false.
	PolicyMode bool
	// CachePath is the last-known-good policy cache file (POLICY mode only); empty
	// disables the cache. InitialPolicy seeds the in-memory LKG at construction (a
	// cold start that recovered a cached policy passes it here so a first SIGHUP
	// re-projects it, verification 9).
	CachePath      string
	InitialPolicy  *wsproto.Policy
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
	PingInterval   time.Duration
	ReadDeadline   time.Duration
	Rng            *mathrand.Rand
	Tunnel         config.WorkerTunnelConfig
	// Dirs reports the roots mapping and per-project directories (may be nil).
	Dirs DirsFunc
}

Config is the resolved worker-client wiring (the command resolves env/URLs). URLs may list multiple hub addresses (C7 failover); InitialBackoff/MaxBackoff/ PingInterval/ReadDeadline are 0-defaulted to the package constants. Rng is the jitter source (nil = time-seeded; tests inject a deterministic one).

type DirsFunc

type DirsFunc func() (roots []config.WorkerRoot, projects map[string]string)

DirsFunc reports where this worker runs things: its roots mapping (POLICY mode) and the directory every served project currently resolves to. It is injected by the command layer, which owns worker.yaml and the live config (G021); existence is checked here, at report time, so a directory that vanishes later shows up on the next heartbeat.

type Handover

type Handover struct {
	UpgradeID string
	FromPID   int
	ReadyPath string
	// OnReady runs once, after registration and before the marker is written (the
	// command layer repoints the daemon pidfile here).
	OnReady func()
}

Handover is set on a process that was started by an upgrade (the flags above): it registers with Register.UpgradeID and, once registered, takes over the pidfile and writes the readiness marker the old process is polling for.

type Jobs

type Jobs interface {
	Submit(req job.JobRequest) (job.JobResult, error)
	Get(id string) (job.JobResult, bool)
	Wait(id string) (job.JobResult, bool)
	// Cancel cancels a running local job (P2 cancel frame). Stable no-op for a
	// terminal job, error only for an unknown id (mirrors job.Service.Cancel).
	Cancel(id string) error
	// GetInteractions returns the local job's interactions so the client can bridge
	// new pending ones to the hub as interaction{open} frames (P2).
	GetInteractions(id string) ([]job.Interaction, error)
	// AnswerInteraction delivers the hub's answer to the local job so it resumes
	// (P2 answer frame).
	AnswerInteraction(jobID, interactionID, answer string) (job.Interaction, error)
	// SetEventObserver installs the callback that receives the whitelisted job events
	// this service records for a DISPATCHED job (SUP-01 G); nil clears it. The
	// service decides which types are mirrorable (job.mirroredEventTypes) — the
	// client only transports them.
	SetEventObserver(job.JobEventObserver)
	// SetXferBridge installs the job file seam (XFER-01 X2): the service uses it to
	// place a dispatched job's staged uploads in this machine's cwd and to filter what
	// its collect globs report. The client supplies one (see New).
	SetXferBridge(job.XferBridge)
	// Config returns the worker's CURRENT runtime config. The client needs it for the
	// work that must be resolved on THIS machine rather than by the hub: a file
	// transfer's project root (XFER-01 re-validates the dispatch's project/path against
	// the worker's own config, exactly like a locally submitted job's --cwd). It is a
	// live accessor, not a snapshot, so a reloaded config is honoured.
	Config() *config.Config
}

Jobs is the subset of job.Service the worker client needs. job.Service satisfies it; an interface keeps the client testable.

type ReloadFunc

type ReloadFunc func(p *wsproto.Policy) (ReloadOutcome, error)

ReloadFunc re-reads the worker's config from disk and applies it, returning the capability snapshot derived from the SAME config it applied.

It is INJECTED by the command layer (only it knows where worker.yaml lives and how to map it onto a config.Config); the worker package owns the orchestration around it (queueing, serialisation, session generations, receipts) — see G021.

The p argument is the policy to project onto the local config:

  • p != nil (POLICY mode apply, or a SIGHUP re-projecting the in-memory last-known-good): the seam projects p's projects through the worker's roots.
  • p == nil (LEGACY SIGHUP, or a POLICY SIGHUP with no last-known-good yet): the seam sources projects from its own local config (LEGACY) or no-ops the project set (POLICY, T5-A) — it must NEVER wipe a running POLICY config to empty.

Contract the implementation MUST honour (this is what makes "a bad config keeps the old one" true): build and validate the new config COMPLETELY first, and only then apply it (core.ReloadWith). Any failure — unreadable file, bad YAML, failed validation — must return an error BEFORE anything is applied, leaving the worker running its previous config untouched. The apply stage cannot fail, so it cannot roll back. The returned Caps must be derived from the very config that was applied.

type ReloadOutcome

type ReloadOutcome struct {
	Caps       wsproto.Caps
	AppliedRev int64
	Rejected   []wsproto.AppliedRejection
	Degraded   []wsproto.AppliedDegrade
	Tunnel     *config.WorkerTunnelConfig
}

ReloadOutcome is what the injected reload seam reports after building + applying a config: the capability snapshot of the config it applied (Caps — the SAME source a later reconnect registers with), plus the policy-apply diagnostics the Applied frame carries. AppliedRev echoes the projected Policy's Rev (0 for a legacy/no-op reload); Rejected/Degraded are diagnostic only and never gate routing (wsproto.Applied).

type RolledBackError

type RolledBackError struct{ Err error }

RolledBackError reports an upgrade that installed the new binary, started the new process and then restored the old binary because the new process never came up.

func (*RolledBackError) Error

func (e *RolledBackError) Error() string

func (*RolledBackError) Unwrap

func (e *RolledBackError) Unwrap() error

type SpawnSpec

type SpawnSpec struct {
	Exe     string
	Args    []string
	Env     []string
	LogPath string
}

SpawnSpec describes the replacement process to start.

type UpgradeDeps

type UpgradeDeps struct {
	// ExePath is the running binary (default: os.Executable).
	ExePath string
	// Args / Environ are what the new process is started with (default: os.Args[1:] /
	// os.Environ()). Upgrade flags already present in Args are stripped.
	Args    []string
	Environ []string
	// ReadyPath names the readiness marker file for an upgrade id.
	ReadyPath func(upgradeID string) string
	// LogPath receives the new process's stdout/stderr.
	LogPath string

	Fetch        func(ctx context.Context, urlPath, dst string, size int64) error
	CheckVersion func(ctx context.Context, bin string) (string, error)
	Spawn        func(spec SpawnSpec) (ChildProc, error)
	// Poll is the drain / readiness polling interval (default 200ms).
	Poll time.Duration
}

UpgradeDeps are the process-level facts the default UpgradeFunc needs. The command layer fills the paths (it owns the run-dir layout, G021); the function fields are test seams and default to the real implementations when nil.

type UpgradeFunc

type UpgradeFunc func(ctx context.Context, req wsproto.Upgrade, accepted func(version string)) error

UpgradeFunc runs one server-authorized binary upgrade to the point where this process either hands over to the new binary (nil: the process is about to exit) or gives up (error). It calls accepted(version) exactly once, as soon as the candidate binary is downloaded, verified and known to run — the hub answers its caller then, well before the (possibly long) drain. An error returned after accepted is the outcome the client reports later; wrap it in *RolledBackError when the new binary was installed and had to be rolled back. The default implementation lives in this package (upgrade_run.go) and is wired from UpgradeDeps by the command layer.

Jump to

Keyboard shortcuts

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