worker

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package worker is factory-agent's worker loop (supervise.md §The worker loop): it registers with the dispatcher (its refresh token, else the one-time enrollment token), polls for leases (a long poll by default, or a brief poll and a sleep: Poll), runs each leased task through a runner.Runner while heartbeating, reports the Outcome (complete, abandon, throttle), and drains on SIGTERM.

The agent token lives in memory only: a restart registers again with the refresh token, which rotates on each registration. Tokens are never logged.

Index

Constants

View Source
const (
	BasePath                = "/api/v1"
	HeaderEnrollmentToken   = "X-Factory-Enrollment-Token"
	HeaderAgentRefreshToken = "X-Factory-Agent-Refresh-Token"
)

The dispatcher's API base path and the registration credential headers (contracts.md §HTTP API).

View Source
const (
	// DefaultLeaseWait is the long poll's wait (the dispatcher caps it at 60 s).
	DefaultLeaseWait = 30 * time.Second
	// MaxLeaseWait is the longest wait the dispatcher takes.
	MaxLeaseWait = 60 * time.Second
	// MinPollInterval is the shortest interval a zero wait may have: shorter would poll in a
	// hot loop.
	MinPollInterval = time.Second
	// DefaultHeartbeat is used when a lease doesn't say (pool.lease.heartbeat is 30 s).
	DefaultHeartbeat = 30 * time.Second
	// DefaultWallClock bounds a drain for a task whose TaskSpec sets no maxWallClock.
	DefaultWallClock = time.Hour
	// DefaultThrottle is how long a throttled harness rests when it gave no reset time
	// (harness-adapters.md: else +15 min).
	DefaultThrottle = 15 * time.Minute
	// DefaultMinBackoff and DefaultMaxBackoff bound the exponential backoff on failed calls.
	DefaultMinBackoff = time.Second
	DefaultMaxBackoff = time.Minute
	// DefaultReportAttempts is how often complete and abandon are tried on transient errors.
	DefaultReportAttempts = 5
)

Defaults.

Variables

This section is empty.

Functions

func APIBase

func APIBase(dispatcher string) string

APIBase is the API base URL of a dispatcher.

Types

type APIError

type APIError struct {
	Op     string
	Status int
	Code   string
	Title  string
	Detail string
}

APIError is a dispatcher answer other than the operation's success. It carries the problem's code and text, never a request's credentials.

func (*APIError) Error

func (e *APIError) Error() string

type Enrollment

type Enrollment interface {
	// Token is the refresh token when one is saved (refresh true), else the one-time
	// enrollment token.
	Token() (tok string, refresh bool, err error)
	// Save keeps the next refresh token durably; it is called before the registration that
	// returned it is used.
	Save(refresh string) error
	// Forget drops a refresh token the dispatcher refused.
	Forget() error
}

Enrollment is an enrolled agent's registration credential (P1 §6; enroll.Files).

type Options

type Options struct {
	// Dispatcher is the dispatcher's base URL (the API is under BasePath).
	Dispatcher   string
	Pool         string
	Host         string
	AgentVersion string
	Capabilities v1alpha1.AgentCapabilities
	Lending      v1alpha1.Lending

	// Enrollment registers with the refresh token (else the enrollment token) and saves each
	// rotated one.
	Enrollment Enrollment
	// Runner executes leased tasks.
	Runner runner.Runner

	// HTTPClient calls the dispatcher. Default: http.DefaultClient's transport, no timeout
	// (each call carries its own deadline).
	HTTPClient apiclient.HttpRequestDoer
	Clock      clock.Clock
	Logger     *slog.Logger

	// Poll is how the lease loop asks for tasks; DefaultPoll is the long poll. It has no
	// default: its zero Wait means zero.
	Poll Poll
	// DefaultWallClock bounds a drain for tasks without limits.maxWallClock. Default 1 h.
	DefaultWallClock time.Duration
	// MinBackoff and MaxBackoff bound retries. Defaults 1 s and 1 min.
	MinBackoff, MaxBackoff time.Duration
	// ReportAttempts bounds complete/abandon retries. Default 5.
	ReportAttempts int
}

Options configure a Worker. Pool, Host, AgentVersion, Capabilities, Enrollment, Runner and a valid Poll are required.

type Poll added in v0.2.0

type Poll struct {
	// Wait is how long each LeaseTask asks the dispatcher to hold the request: whole seconds
	// from 0s to MaxLeaseWait.
	Wait time.Duration
	// Interval is how long the loop sleeps after a 204 before it polls again; 0 polls again at
	// once. A poll that gets a task polls again at once whatever the interval. At least
	// MinPollInterval when Wait is zero.
	Interval time.Duration
}

Poll is how the lease loop asks for tasks (P3 §Agents poll briefly). A zero Wait means zero: the dispatcher runs one matching pass and answers at once. The zero Poll is invalid (it would poll in a hot loop); DefaultPoll is today's long poll.

func DefaultPoll added in v0.2.0

func DefaultPoll() Poll

DefaultPoll is the long poll: wait 30 s, and after a 204 poll again at once.

func (Poll) Validate added in v0.2.0

func (p Poll) Validate() error

Validate checks the wait's range and whole seconds, a non-negative interval, and that a zero wait has an interval of at least MinPollInterval. It is the one place these rules live: agent.yaml's poll block is checked with it too. The error is a *PollError.

type PollError added in v0.2.0

type PollError struct {
	Field  string
	Value  time.Duration
	Reason string
}

PollError is a Poll that Validate refuses: Field is "wait" or "interval" (agent.yaml's poll keys), Value the refused duration.

func (*PollError) Error added in v0.2.0

func (e *PollError) Error() string

type Worker

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

Worker is one registered agent's lease loop.

func New

func New(o Options) (*Worker, error)

New checks the options and builds a Worker.

func (*Worker) AgentID

func (w *Worker) AgentID() string

AgentID is the registered agent's id ("" before registration).

func (*Worker) Drain

func (w *Worker) Drain()

Drain stops leasing: running tasks finish (or are abandoned with shutdown once their wall-clock budget is spent), then the agent deregisters and Run returns. Safe to call more than once and from any goroutine.

func (*Worker) Run

func (w *Worker) Run(ctx context.Context) error

Run registers, then leases and runs tasks until Drain (or a fatal error), waits for the running tasks and deregisters. Cancelling ctx aborts: running tasks are cancelled and abandoned with shutdown. It returns nil after a drain or an abort, and the error when registration is refused.

func (*Worker) SetLending

func (w *Worker) SetLending(ctx context.Context, l v1alpha1.Lending) error

SetLending changes the owner's consent (SIGHUP): the local concurrency now, and the dispatcher's copy through PATCH /agents/{id} once registered.

func (*Worker) Throttled

func (w *Worker) Throttled() time.Time

Throttled is when the agent may lease again after a throttled run (zero when it isn't throttled).

func (*Worker) Token

func (w *Worker) Token() string

Token is the current agent token ("" before registration). Never log it.

Jump to

Keyboard shortcuts

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