Documentation
¶
Overview ¶
Package workerapi is the internal transport between a control node and an elastic worker. It is the *second transport* for the one orchestrator implementation: a worker runs the same supervise.Manager, and the control node reaches it through Client, which satisfies the same proxy.Backends interface the local loopback adapter does. Single-node (--role=all) is the degenerate case where no Client exists and serving stays loopback.
The surface is deliberately tiny — exactly what the control node needs against a supervise.Key: start/reuse a process (Ensure), stop it, read its status, and a capacity heartbeat. It is a remote-code-execution surface by design (the worker starts arbitrary preview processes), so it is shared-secret authenticated and MUST live on a private listener that is never reachable from the ALB/internet.
Index ¶
- Constants
- type Client
- func (c *Client) Configure(ctx context.Context, cfg WorkerConfig) error
- func (c *Client) Drain(ctx context.Context, draining bool) error
- func (c *Client) EnsureRunning(ctx context.Context, k supervise.Key, repoName string) (string, error)
- func (c *Client) Exec(ctx context.Context, k supervise.Key, opts supervise.ExecOptions, ...) error
- func (c *Client) Heartbeat(ctx context.Context) (Heartbeat, error)
- func (c *Client) Report(ctx context.Context) ([]supervise.ProcReport, error)
- func (c *Client) RunLog(ctx context.Context, repo, side, hash string, attempt int, offset int64) (supervise.RunLog, error)
- func (c *Client) Status(ctx context.Context, k supervise.Key) (status, detail string, err error)
- func (c *Client) Stop(ctx context.Context, k supervise.Key, reason string) error
- type ControlClient
- type ControlServer
- type HTTPError
- type Heartbeat
- type Registrar
- type Server
- type Supervisor
- type WireKey
- type WorkerConfig
Constants ¶
const AuthHeader = "Authorization"
AuthHeader carries the shared secret ("Bearer <secret>"). The secret comes from SSM/config on both ends.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// SpecResolver resolves the control-side run spec shipped with each
// ensure request (plus the peer backend's, for a process-mode frontend) —
// supervise.(*Manager).ResolveWireSpec in production. Nil sends none,
// which only serves against a worker whose own DB knows the artifact;
// outside tests that means every ensure fails "not provisioned".
SpecResolver func(k supervise.Key) (supervise.WireSpec, error)
// InitMarker records a backend init proven complete on the worker —
// supervise.(*Manager).AdoptRemoteInitDone in production. A successful
// backend ensure implies the init steps succeeded (the worker fails the
// ensure otherwise), so the control DB can adopt the result without any
// wire change, old workers included. Without it, init_done_at never
// leaves the worker's in-memory spec cache, and every cold placement on
// a fresh worker re-runs init — a fleet resting at zero workers re-ran
// it on nearly every wake. Nil skips the write.
InitMarker func(k supervise.Key) error
// InitRevoker withdraws a backend init the control DB records as done —
// supervise.(*Manager).RevokeInitDone in production, the mirror image of
// InitMarker. It fires when an ensure that SHIPPED InitDone=true came
// back as a start failure the worker actually reported: the worker
// skipped init on our say-so and the process never went healthy, so the
// effects init owns (the per-preview database, say) may be gone. The
// next ensure then ships InitDone=false and the worker re-runs init.
//
// Only a worker-reported failure counts. A transport error, a timeout,
// or a cancelled context proves nothing — the worker may never have run
// a thing — and revoking on those would re-run init for every network
// blip. That distinction is why post returns a typed *HTTPError.
// Nil skips the write.
InitRevoker func(k supervise.Key) error
// contains filtered or unexported fields
}
Client is the control-node transport to one worker. Its EnsureRunning satisfies proxy.Backends, so the proxy routes to a remote worker exactly as it routes to a local Manager — the "one orchestrator, two transports" property. host is the worker's routable address (how the control node reaches the worker's supervised processes); the worker returns only the port.
func NewClient ¶
NewClient dials a worker. baseURL is its private worker-API URL; host is the address the control node reaches its processes on; secret is the shared secret. A nil httpClient gets a default with a sane timeout.
func (*Client) Configure ¶ added in v0.15.0
func (c *Client) Configure(ctx context.Context, cfg WorkerConfig) error
Configure pushes runtime settings to the worker — the dashboard-edited warm cap and idle-timeout override. The control node's heartbeat loop re-pushes after a worker reboot, so the settings survive the fleet.
func (*Client) Drain ¶
Drain marks the worker draining (or clears it) — used by a control-node lifecycle handler winding a worker down before its instance terminates.
func (*Client) EnsureRunning ¶
func (c *Client) EnsureRunning(ctx context.Context, k supervise.Key, repoName string) (string, error)
EnsureRunning starts (or reuses) the keyed process on the worker and returns the "host:port" the control node's proxy dials.
func (*Client) Exec ¶ added in v0.31.1
func (c *Client) Exec(ctx context.Context, k supervise.Key, opts supervise.ExecOptions, stream io.ReadWriter) error
Exec forwards one `preview exec` session to the worker: it dials the worker's exec endpoint (WebSocket upgrade) and copies execstream frames blindly in both directions — the frames need no re-framing per hop. It returns when the worker ends the session (normally after FrameExit) or the transport fails; ctx bounds only the handshake.
func (*Client) Report ¶ added in v0.14.0
Report fetches the worker's full live-state dump: every non-idle key's status, failure detail, and resource sample.
func (*Client) RunLog ¶ added in v0.14.0
func (c *Client) RunLog(ctx context.Context, repo, side, hash string, attempt int, offset int64) (supervise.RunLog, error)
RunLog fetches an incremental run-log slice from the worker's disk.
type ControlClient ¶ added in v0.24.0
type ControlClient struct {
// contains filtered or unexported fields
}
ControlClient is the worker-side transport to the control node's registration endpoint — the reverse direction of Client. A self-registering worker calls Register on boot and periodically (so a restarted control node re-learns it), and Deregister on graceful shutdown.
func NewControlClient ¶ added in v0.24.0
func NewControlClient(baseURL, secret string, hc *http.Client) *ControlClient
NewControlClient dials the control node's registration API. A nil httpClient gets a default with a sane timeout.
func (*ControlClient) Deregister ¶ added in v0.24.0
func (c *ControlClient) Deregister(ctx context.Context, endpoint string) error
Deregister removes this worker from the control node's fleet.
func (*ControlClient) Register ¶ added in v0.24.0
func (c *ControlClient) Register(ctx context.Context, endpoint, host, instanceID string) error
Register announces this worker to the control node: endpoint is this worker's own worker-API base URL, host the routable host its processes serve on, and instanceID its cloud instance-id (empty if it has none) so the control node can scale-in-protect it while busy.
type ControlServer ¶ added in v0.24.0
type ControlServer struct {
// contains filtered or unexported fields
}
ControlServer is the control node's inbound half of the worker protocol: workers announce themselves here instead of being hand-listed in the control node's flags. It shares the worker API's shared-secret trust model and MUST likewise live on a private listener the ALB can never reach — a caller who can register an endpoint can steer preview traffic to a host of its choosing and make the control node dial arbitrary addresses.
func NewControlServer ¶ added in v0.24.0
func NewControlServer(reg Registrar, secret string) *ControlServer
NewControlServer wraps reg behind the shared-secret check.
func (*ControlServer) Handler ¶ added in v0.24.0
func (s *ControlServer) Handler() http.Handler
Handler returns the authenticated control-API mux. Mount it on a private listener only.
type HTTPError ¶ added in v0.31.3
HTTPError is a response the peer actually produced: the request reached it and it answered non-2xx. Callers that must tell "the far side ran something and it failed" from "the far side was never reached" (EnsureRunning's init revocation) match on this; a transport error, a timeout, or a cancelled context is a plain error instead.
type Heartbeat ¶
type Heartbeat struct {
Running int `json:"running"`
MaxWarm int `json:"max_warm"`
MinWarm int `json:"min_warm,omitempty"`
IdleTimeoutSeconds int `json:"idle_timeout_seconds,omitempty"`
Draining bool `json:"draining"`
// WarmHits and ColdStarts are the worker's cumulative EnsureRunning
// outcome counts since it started — summed across the fleet for the
// dashboard's warm-ratio statistic. They reset when a worker reboots
// (routine on a spot tier), so the control node's registry detects the
// regression and banks the previous values, keeping fleet totals
// monotonic for as long as the control node runs.
WarmHits int64 `json:"warm_hits"`
ColdStarts int64 `json:"cold_starts"`
// Events are the process events recorded on this worker since its last
// heartbeat (drained at read — at-most-once). A worker's own database is
// ephemeral, so the control node replays these into its process_events
// trail, which feeds the dashboard's startup-latency percentiles.
Events []supervise.ProcEventRecord `json:"events,omitempty"`
}
Heartbeat is the worker's capacity report, the input to fleet placement and scale-out. Draining marks a worker an ASG lifecycle hook is winding down: the control node routes new work elsewhere but keeps serving what is already warm. The runtime-config fields echo what the worker currently applies, so the control node's reconcile loop can spot (and re-push onto) a worker that rebooted back to its boot flags.
type Registrar ¶ added in v0.24.0
type Registrar interface {
// Register adds (or replaces) a worker by its advertised worker-API
// endpoint, reaching its preview processes at host. instanceID is the
// worker's cloud instance-id when it has one (used for scale-in
// protection), empty otherwise.
Register(endpoint, host, instanceID string) error
// Deregister removes a worker that is leaving the fleet.
Deregister(endpoint string) error
}
Registrar is the control-side sink a self-registering worker calls into. The implementation (in cmd/server) builds the workerapi.Client for the endpoint, attaches the control-DB SpecResolver, and adds it to the fleet registry — exactly the wiring the static --worker-endpoint boot loop does, reused so a dynamic worker joins by the same path a hand-listed one does.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server exposes a Supervisor over HTTP behind a shared-secret check. Mount Handler() on a private listener only.
func (*Server) SetDraining ¶
SetDraining marks the worker draining (or not). A draining worker keeps serving what is already warm but reports Draining in its heartbeat so the control node's placement stops sending it new work — the pre-terminate half of an ASG scale-in lifecycle hook.
type Supervisor ¶
type Supervisor interface {
EnsureRunning(ctx context.Context, k supervise.Key, repoName string) (int, error)
OfferWireSpec(k supervise.Key, s supervise.WireSpec)
Stop(k supervise.Key, reason string)
Status(k supervise.Key) string
LastFailure(k supervise.Key) (supervise.Failure, bool)
Report(ctx context.Context) []supervise.ProcReport
RunLog(repoName, side, hash string, attempt int, offset int64) (supervise.RunLog, error)
Exec(ctx context.Context, k supervise.Key, opts supervise.ExecOptions, stream io.ReadWriter) error
Running() int
MaxWarm() int
SetMaxWarm(n int)
DrainEvents() []supervise.ProcEventRecord
MinWarm() int
SetMinWarm(n int)
IdleOverride() time.Duration
SetIdleOverride(d time.Duration)
HitStats() (warm, cold int64)
}
Supervisor is the worker-local orchestration surface the API exposes. It is exactly the subset of supervise.Manager the control node drives remotely, so *supervise.Manager satisfies it and tests can substitute a fake.
type WireKey ¶
type WireKey struct {
RepoID int64 `json:"repo_id"`
Side string `json:"side"`
Hash string `json:"hash"`
Peer string `json:"peer,omitempty"`
}
WireKey is the JSON form of a supervise.Key crossing the boundary.
type WorkerConfig ¶ added in v0.16.0
type WorkerConfig struct {
// MaxWarm is the soft warm target; MinWarm the floor of most-recent
// processes exempt from idle timeouts.
MaxWarm *int `json:"max_warm,omitempty"`
MinWarm *int `json:"min_warm,omitempty"`
// IdleTimeoutSeconds > 0 overrides every manifest's idle_timeout; 0
// restores per-manifest values.
IdleTimeoutSeconds *int `json:"idle_timeout_seconds,omitempty"`
}
WorkerConfig is the control-pushed runtime settings bundle. Fields are pointers so a push only touches what it names; a rebooted worker falls back to its boot flags until the control node's reconcile loop pushes again.