wshub

package
v0.167.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: 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

Index

Constants

View Source
const (
	// DefaultPingInterval is how often the hub sends a ping frame to each worker.
	DefaultPingInterval = 15 * time.Second
	// DefaultReadDeadline bounds a single conn.Read; exceeding it tears the
	// connection down (half-open detection, review #7). It MUST be ≥ 2× the ping
	// interval or normal heartbeats would themselves time out.
	DefaultReadDeadline = 45 * time.Second
)

Heartbeat / half-open detection defaults (P3 §4.1). All configurable; these are the constants applied when serve passes nothing. read deadline is ~3× the ping interval so a GC/scheduling hiccup that drops one or two pings does not falsely flag a worker offline (and falsely fail its in-flight jobs, §6.1).

View Source
const BeatNotifyInterval = 10 * time.Second

BeatNotifyInterval caps how often one worker's heartbeat reaches the heartbeat observer: the browser's runners page needs a fresh last_heartbeat / in_flight / messenger / dirs, but not one refetch per frame (logs arrive far more often).

Variables

View Source
var ErrFileXferUnsupported = errors.New("worker protocol too old for file transfer")

ErrFileXferUnsupported is returned when the target worker is connected and healthy but speaks a protocol older than the one carrying the file-transfer frames. Like ErrWorkerTooOld it is NOT a failure of the worker (it keeps running its jobs), and it must be surfaced as "upgrade and restart this worker" rather than retried: the transfer cannot be queued for a later version — the caller's file is either moved now or not at all.

View Source
var ErrReloadTimeout = errors.New("worker did not answer the reload request in time")

ErrReloadTimeout is returned when the worker acknowledged nothing within the caller's deadline. The reload is NOT known to have failed — the worker may still apply it — so the caller must report "no receipt in time", not "reload failed".

View Source
var ErrTranscriptTailUnsupported = errors.New("worker protocol too old for transcript tail")

ErrTranscriptTailUnsupported is returned when the worker is connected but speaks a protocol older than the transcript_tail frames. It is not a fault of the worker; the caller degrades (the summarizer falls back to the session's last message).

View Source
var ErrUpgradeTimeout = errors.New("worker did not answer the upgrade request in time")
View Source
var ErrUpgradeUnsupported = errors.New("worker protocol too old for remote upgrade")
View Source
var ErrWorkerAtCapacity = errors.New("worker at capacity")

ErrWorkerAtCapacity is returned by Dispatch when the target worker is at its advertised max_concurrent (§5.4). Queueing is deferred to WP4; the caller maps this to a failed job with a clear error so the submitter can retry / pick another worker rather than silently block.

View Source
var ErrWorkerDraining = errors.New("worker is being upgraded and takes no new jobs; retry shortly")

ErrWorkerDraining is returned by Dispatch while the worker is being upgraded: it finishes its in-flight jobs but takes no new ones.

View Source
var ErrWorkerOffline = errors.New("worker offline")

ErrWorkerOffline is returned by Dispatch/RegisterSink when no live connection exists for the target worker_id.

View Source
var ErrWorkerTooOld = errors.New("worker protocol too old to reload config")

ErrWorkerTooOld is returned when the target worker is connected and healthy but speaks a protocol older than the one that carries the reload frames. It is NOT a failure of the worker: it keeps running its jobs exactly as before, it just cannot be asked to re-read its config — the operator has to restart it after upgrading. Callers must surface it as such (a "restart me" prompt), never as a server fault.

Functions

This section is empty.

Types

type AdoptedJob

type AdoptedJob struct {
	Sink                 JobSink
	StdoutOff, StderrOff int64
}

AdoptedJob is one job the hub takes over from a previous serve process: the sink that will receive its frames on the new connection plus the server-side offsets the worker must rewind to (the hub echoes them in the resume ack, exactly as it does for a job held live in `recovering`).

type Adopter

type Adopter interface {
	// AdoptAfterRestart reconciles the store-held `recovering` jobs of workerID
	// against a worker process that just registered with instanceID and the given
	// inflight list (always non-nil for a RECOV-01 worker: an empty list is a
	// statement, "I track nothing").
	//
	// It returns the adopting sinks for the jobs that process PROVES it still runs
	// (the same process instance, reported in flight) — keyed by job id, with the
	// byte offsets already persisted server-side, so the hub can put them into the
	// resume ack — and fails every other store-held recovering job of that worker,
	// returning their ids as lost so the hub can log them. Failing them there (rather
	// than here) keeps the terminal write in the layer that owns the store; the hub
	// only reports the outcome.
	AdoptAfterRestart(workerID, instanceID string, inflight []wsproto.InflightJob) (adopted map[string]AdoptedJob, lost []string)
}

Adopter is the seam through which the hub ADOPTS the `recovering` jobs a PREVIOUS serve process left in the store (RECOV-01 R4). It exists because the hub is not allowed to know about jobs: the store, the log files and the classify/finish path belong to the job service, which implements this contract behind the assembly layer.

Without it a restart is a dead end: the old process's sinks died with it, so the hub's recovery set — built from LIVE connections only — can never hold the rows the store still has, and the one-shot startup window can only defer their failure. With it, a worker process that reconnects and reports the job in its `inflight` list gets the job (and its logs) back instead of losing it.

type HeartbeatConfig

type HeartbeatConfig struct {
	PingInterval time.Duration
	ReadDeadline time.Duration
}

HeartbeatConfig holds the hub-side heartbeat / read-deadline timings. A zero value (both fields 0) means "use the package defaults" (resolved in withDefaults).

type Hub

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

Hub is the serve-process singleton: WS accept + worker registry + per-job inbound-frame demux + dispatch + heartbeat. One instance is shared by every worker runner (assemble.buildCore). It is safe for concurrent use.

func New

func New(bindings map[string]string) *Hub

New builds a Hub. bindings is the worker_id → expected caller-id map (from cfg.Server.Workers); a nil map means no worker may register (per-worker token is mandatory, §7 / review #1).

func (*Hub) Accept

func (h *Hub) Accept(w http.ResponseWriter, req *http.Request, callerID string)

Accept upgrades GET /v1/workers/connect to a WebSocket and runs the per-connection read loop. The route layer (httpapi) has already done Bearer auth and passes the resolved callerID; Accept does the worker_id↔caller binding check (review #1) then the register handshake.

It receives rux's c.Resp directly: rux v2.0.2 fixed the P0 finding — its *responseWriter.Hijack() now flushes the recorded 101 status to the underlying writer before detaching the connection, so the old wsUpgradeWriter adapter (the spike workaround that forced an early flush) is no longer needed.

func (*Hub) Answer

func (h *Hub) Answer(workerID, jobID, interactionID, answer string) error

Answer sends an answer frame to the worker so its local job's interaction resumes (P2). It errors when the worker is offline (best-effort: the host interaction is already authoritative, so a lost answer never blocks the host).

func (*Hub) Cancel

func (h *Hub) Cancel(workerID, jobID string) error

Cancel sends a cancel frame to the worker so it cancels the matching local job (P2). It errors when the worker is offline (best-effort: the host classifies the job from its own ctx regardless, so a lost cancel never strands the host).

RECOV-01: when the worker is offline but the job is being held in `recovering` for it, the intent is RECORDED and delivered as soon as that job is resumed — otherwise a cancel issued during the outage would be lost and the worker would keep running a job the host has already finished as cancelled.

F3 (bd h-aii-tcpm): the same goes for a frame that cannot be WRITTEN, and for the window in which the connection is already out of the registry but its jobs are not yet `recovering` — parkCancel covers both, so a cancel is never silently dropped between the host's decision and the worker's teardown.

func (*Hub) DeregisterSink

func (h *Hub) DeregisterSink(workerID, jobID string)

DeregisterSink removes the per-job sink (workerRunner defers this on Run exit) and releases the in-flight slot it occupied.

func (*Hub) DisconnectWorker

func (h *Hub) DisconnectWorker(workerID string)

DisconnectWorker closes the current connection for workerID. It is used by the administrator worker removal API after the config transaction commits.

func (*Hub) Dispatch

func (h *Hub) Dispatch(workerID string, d wsproto.Dispatch) error

Dispatch sends a dispatch frame to the target worker. It errors when the worker is offline (ErrWorkerOffline) or already at its advertised max_concurrent (ErrWorkerAtCapacity, §5.4 — queueing is WP4). On success the job is recorded in the worker's in-flight set so a disconnect can fail it (§5.3) and so capacity accounting stays correct.

func (*Hub) IsOnline

func (h *Hub) IsOnline(workerID string) bool

IsOnline reports whether a worker is currently registered (a live connection exists). Used for readiness checks / future /v1/runners observability (C6).

func (*Hub) LastHeartbeat

func (h *Hub) LastHeartbeat(workerID string) int64

LastHeartbeat returns the unix-seconds timestamp of the most recent inbound frame for workerID (0 when offline). It seeds the C6/P4 /v1/runners surface.

func (*Hub) LiveInstance

func (h *Hub) LiveInstance(workerID string) (string, bool)

LiveInstance returns the current live connection's process instance id for a worker. It is a narrow PTY relay seam: callers can bind a one-time nonce to a specific worker process without seeing the underlying connection.

func (*Hub) OpenTunnel

func (h *Hub) OpenTunnel(workerID, tunnelID, network, target, relayNonce string) error

OpenTunnel sends a tunnel control frame without consuming job capacity.

func (*Hub) PushPolicyAll

func (h *Hub) PushPolicyAll()

PushPolicyAll broadcasts the current per-worker Policy to every live connection that negotiated policy support (SupportsPolicy). It is called OFF the caller's config-write lock (core.flushPush): each frame is written under a short per-connection deadline (policyWriteTimeout) and a slow/failing connection is logged and skipped — never allowed to stall the others (D-HIGH-5). A skipped worker re-converges on its next reconnect / the next push.

With no policy source wired (T1, until T3) this returns immediately: there is nothing to compute, so the broadcast is a legitimate no-op.

func (*Hub) RegisterSink

func (h *Hub) RegisterSink(workerID, jobID string, sk JobSink) error

RegisterSink registers a per-job sink on the worker's connection. The workerRunner calls this BEFORE Dispatch so the first log frame is never lost (review #2). It errors when the worker is offline.

func (*Hub) ReloadWorker

func (h *Hub) ReloadWorker(ctx context.Context, workerID, reason string) (wsproto.Caps, error)

ReloadWorker asks one worker to re-read its local config and waits for the answer.

It is SYNCHRONOUS on purpose: the caller is holding an HTTP request open on the outcome, and "202 accepted" for an operation that can fail on the far side (a syntax error in the worker's config) is how a failed reload becomes an invisible one. The whole request/receipt correlation lives here, in the hub, because the ReloadResult frame arrives on the hub's per-connection read loop — the layer above (serve/httpapi) only maps the returned error onto a status code.

The wait ends on exactly one of four events:

  • the matching ReloadResult arrives → applied (Caps already stored, see readLoop) or ReloadRejected with the worker's reason;
  • the worker disconnects → ErrWorkerOffline immediately. Waiting out the full deadline for a process that is provably gone is a bug, not caution;
  • ctx expires → ErrReloadTimeout, and the pending entry is removed (a waiter that leaves must never leak its slot);
  • ctx is cancelled (client hung up) → ctx.Err().

Errors: ErrWorkerOffline (not connected / dropped mid-wait), ErrWorkerTooOld (protocol below wsproto.ReloadMinProtocolVersion), *ReloadRejected (worker said no), ErrReloadTimeout (no receipt), or a write error. On success the returned Caps is the worker's new capability snapshot — already applied to the registry BEFORE this returns, so a caller that reads /v1/meta right after can never see the stale view.

func (*Hub) SendFileXfer

func (h *Hub) SendFileXfer(ctx context.Context, workerID string, req wsproto.FileXfer) (wsproto.FileXferResult, error)

SendFileXfer sends one transfer instruction to a worker and waits for its result.

It is SYNCHRONOUS: the dispatch the caller is driving (a staged transfer) can only be settled done/failed by the worker's report, so the alternative to waiting is a record left dispatched until its timeout. The wait ends on exactly one of three events — the matching file_xfer_result, the connection dying, or ctx expiring — and the pending entry is removed on all of them (a waiter that leaves must never leak its slot). Nothing is queued or retried: a worker that is offline or too old fails the transfer with a reason the operator can act on (design §一.2).

The frame carries NO job id (a transfer is not a job, exactly like tunnel_open), so the worker's read loop demuxes it by frame type, and the reply is correlated by XferID instead.

func (*Hub) SendSessionCommand

func (h *Hub) SendSessionCommand(workerID, jobID, cmdID, action, prompt string) error

SendSessionCommand sends a protocol-v13 say/end command to a worker. The command id is supplied by the job service and is preserved across retries so the worker can deduplicate it.

func (*Hub) SendTranscriptTail

func (h *Hub) SendTranscriptTail(ctx context.Context, workerID string, req wsproto.TranscriptTail) (wsproto.TranscriptTailResult, error)

SendTranscriptTail asks a worker for the end of a session transcript and waits for the answer. The wait ends on exactly one of: the matching result, the connection dying, or ctx expiring; the pending entry is removed on all of them.

func (*Hub) SetAdopter

func (h *Hub) SetAdopter(a Adopter)

SetAdopter wires the RECOV-01 R4 adoption seam. Like SetRecoverWindow it is called once at assemble time, before any connection is accepted; a nil adopter (the default) leaves adoption off and a restarted serve fails the rows after the window, exactly as before R4.

func (*Hub) SetFileXferResultHandler

func (h *Hub) SetFileXferResultHandler(fn func(wsproto.FileXferResult))

SetFileXferResultHandler installs the fallback for a file_xfer_result that no dispatch is waiting for: the waiter already gave up (timeout, disconnect) or the record was settled elsewhere. The assembly (core) points it at the transfer manager, whose OnWorkerResult settles a record that is still dispatched and ignores one that is already terminal — so a late report can never reopen a finished transfer. A nil handler (hub used standalone, tests) simply drops such frames.

func (*Hub) SetHeartbeat

func (h *Hub) SetHeartbeat(hc HeartbeatConfig)

SetHeartbeat overrides the heartbeat timings (serve resolves them from config; defaults apply for any unset field). Must be called before Accept handles any connection (i.e. at assemble time, single-threaded).

func (*Hub) SetHeartbeatObserver

func (h *Hub) SetHeartbeatObserver(fn func(workerID string))

SetHeartbeatObserver installs (nil clears) the callback fired at most once per BeatNotifyInterval per worker while that worker's frames keep arriving. Like the presence observer it runs on the connection goroutine and must only enqueue.

func (*Hub) SetPolicyRepush

func (h *Hub) SetPolicyRepush(timeout time.Duration, attempts int)

SetPolicyRepush configures the finite retry window for a worker that has not acknowledged the latest policy. Non-positive values restore the defaults.

func (*Hub) SetPolicySource

func (h *Hub) SetPolicySource(ps PolicySource)

SetPolicySource wires the Policy computation seam (T1-E). serve/core calls it once at assemble time (single-threaded) before any broadcast. A nil source leaves PushPolicyAll a no-op.

func (*Hub) SetPresenceObserver

func (h *Hub) SetPresenceObserver(fn func(workerID string, online bool))

SetPresenceObserver installs (nil clears) the callback fired when a worker connection is registered or torn down. It runs on the connection's goroutine, so it must only enqueue (the browser push hub turns it into a `runners` invalidation).

func (*Hub) SetRecoverWindow

func (h *Hub) SetRecoverWindow(d time.Duration)

SetRecoverWindow sets the RECOV-01 reconnect window (serve resolves it from server.job_recover_window_sec; 0 disables recovery, restoring the pre-RECOV-01 behaviour of failing a worker's in-flight jobs the moment its connection dies). Must be called before Accept handles any connection (assemble time).

func (*Hub) SetStop

func (h *Hub) SetStop(stop <-chan struct{})

SetStop wires the serve-level shutdown channel and starts the shutdown watcher goroutine: when stop closes, every live connection is gracefully closed (close code 1001 going-away), which unblocks every per-connection read loop and stops the heartbeat goroutines (§5.6). Idempotent-unsafe: call once at assemble time.

func (*Hub) SetUpgradeObserver

func (h *Hub) SetUpgradeObserver(o UpgradeObserver)

SetUpgradeObserver wires the upgrade bookkeeping. Call before the hub accepts connections.

func (*Hub) Shutdown added in v0.142.1

func (h *Hub) Shutdown(ctx context.Context) error

Shutdown closes every live worker connection (going-away) and waits until each one's disconnect disposal has finished — its in-flight jobs are held in `recovering` or failed, and that state is persisted — or until ctx expires. A connection arriving afterwards is refused. Callers run it before closing the store (core.Close); the stop channel of SetStop only signals and does not wait.

func (*Hub) TranscriptTailSupported

func (h *Hub) TranscriptTailSupported(workerID string) (supported, online bool)

TranscriptTailSupported reports whether the worker is live and speaks the frame.

func (*Hub) UpdateBindings

func (h *Hub) UpdateBindings(bindings map[string]string)

UpdateBindings applies the server.workers worker_id→caller map to future registrations and disconnects live connections that are no longer admitted. Existing connections with a changed token binding are also closed so the next connection must authenticate with the new token.

func (*Hub) UpgradeWorker

func (h *Hub) UpgradeWorker(ctx context.Context, workerID string, req wsproto.Upgrade) (string, error)

UpgradeWorker asks a connected worker to upgrade itself and waits for its FIRST answer: "accepted" (binary downloaded, verified and runnable; the handover now proceeds on its own, nil error, the version it reported is returned) or a failure. The final outcome arrives later through the UpgradeObserver (the new process registering with Register.UpgradeID, or a rollback/failure report).

The worker is marked draining BEFORE the frame is written, so no new job can slip in between the request and the worker noticing it; a failed request lifts the mark.

func (*Hub) WorkerProtocol

func (h *Hub) WorkerProtocol(workerID string) (int, bool)

WorkerProtocol returns the wire protocol version the worker's live connection reported at registration (ok=false when the worker is offline / never connected). It is the negotiated-feature check for callers that must know whether an additive dispatch field will be understood — see wsproto.SupportsSessionLoad.

func (*Hub) WorkerSnapshot

func (h *Hub) WorkerSnapshot(workerID string) (WorkerSnapshot, bool)

WorkerSnapshot returns a read-only view of workerID's live state (ok=false when offline / never connected): last_heartbeat, in-flight job count and labels. It is the C6/P4 /v1/runners observability accessor; the handler reads it through a narrow interface so it never touches the internal conn.

type JobSink

type JobSink interface {
	// WriteLog mirrors one inbound log frame onto the host job's stream writer.
	// Implementations MUST NOT block the caller indefinitely (it is the hub's
	// single read loop): bound/throttle internally, never spawn a per-frame
	// goroutine that could reorder relative to Finish.
	WriteLog(stream string, seq int, text string)
	// OnInteraction bridges one worker-raised interaction frame (P2): action is
	// open|answered|cancelled and interaction is the raw job.Interaction body.
	// It must not block the hub's read loop (the blocking WaitAnswer wait is the
	// sink's own goroutine, not this call). The answer is sent back over WS via
	// the hub the sink was constructed with.
	OnInteraction(action string, interaction json.RawMessage)
	// OnOutcome stashes the worker-captured产出 (P4) for the job; the workerRunner
	// returns it on the runner.Result so the host applies it before finishing. It
	// arrives strictly BEFORE Finish (the worker sends the outcome frame just
	// before the result frame), enforced by the single in-order read loop. It must
	// be non-blocking (the hub's read loop).
	OnOutcome(o wsproto.Outcome)
	// OnJobEvent bridges one worker-raised job life-cycle event (SUP-01 G): the
	// approval gate / verify step events the worker recorded while executing this
	// job, which the host records on ITS row (tagged with the worker that raised
	// them). Duplicates are dropped by the hub before this is called. It runs on the
	// hub's single read loop, so it must not block for long (the host's own event
	// write is a local insert).
	OnJobEvent(ev wsproto.JobEvent)
	// Finish delivers the authoritative terminal result, unblocking the
	// workerRunner.Run wait. It must be non-blocking (drop a duplicate result).
	Finish(res wsproto.Result)
	// Suspend signals that the worker connection dropped while this job was in
	// flight, but the job is being HELD for a possible reconnect (RECOV-01) instead
	// of being failed: the host job moves to `recovering` and the worker gets a
	// bounded window to come back. It must not block (the hub calls it from the
	// disconnect path).
	//
	// The two return values are the byte counts this sink has durably written to the
	// host job's stdout/stderr logs — the SERVER-side offsets the hub echoes in the
	// resume ack so the reconnecting worker rewinds to exactly what was persisted
	// (no gap, no duplicate). They are only meaningful for a worker job; the hub
	// never calls Suspend when recovery is disabled.
	Suspend(reason string) (stdoutOff, stderrOff int64)
	// Resume signals that the worker process came back and still has this job
	// (RECOV-01): the host job returns to `running`. It must be idempotent w.r.t. a
	// concurrent Finish/OnDisconnect (whichever terminal signal landed first wins,
	// and a Resume after one is a no-op) and must not block.
	Resume()
	// OnDisconnect signals that the worker connection dropped while this job was
	// in flight (worker-lost, §5.3). It unblocks the workerRunner.Run wait with
	// err (worker disconnected) so the host job is finished failed via the existing
	// classify/finish path. It must be non-blocking (the hub calls it from the
	// disconnect path) and idempotent w.r.t. a concurrent Finish (whichever lands
	// first wins; a result that beat the disconnect keeps the job's real outcome).
	//
	// With RECOV-01 recovery enabled this is called when the recovery window
	// EXPIRES (err = worker lost), not at the moment of the disconnect.
	OnDisconnect(err error)
}

JobSink receives the worker frames the hub demuxes for one job and signals the terminal result. It decouples the hub (transport) from the workerRunner (which owns the host-side mirror writers + the Run wait). The concrete implementation (boundedSink) lives in internal/runner/worker and applies the C4-style back-pressure (review #3).

Lifecycle / ordering invariants (review #2):

  • The workerRunner registers a sink (RegisterSink) BEFORE the hub sends the dispatch frame, so the very first log frame is never dropped.
  • The hub's single per-connection read loop calls WriteLog/OnInteraction/ Finish for a job IN ORDER (never one goroutine per frame), so Finish is always observed after every preceding WriteLog/OnInteraction for that job, and an interaction{open} can never be reordered after the result (which would otherwise be rejected by injectInteraction on a terminal job).

type PolicySource

type PolicySource interface {
	PolicyFor(workerID string) (wsproto.Policy, bool)
}

PolicySource is the seam through which the hub obtains the Policy for one worker without importing config or knowing how a policy is computed (T1-E). ok is false when no policy applies to that worker (source not wired, or the worker has no projects) — the hub then pushes nothing to it.

type ReloadRejected

type ReloadRejected struct {
	WorkerID string
	Reason   string
}

ReloadRejected is returned when the worker answered but REFUSED the new config (bad YAML, unknown agent, …). It is the good case of a bad outcome: the worker is alive, still running its previous config, and told us exactly why. Reason is the worker's own message and must reach the user verbatim — swallowing it is how a broken config turns into a silent no-op.

func (*ReloadRejected) Error

func (e *ReloadRejected) Error() string

type SessionStateReconciler

type SessionStateReconciler interface {
	ReconcileSessionState(workerID string, inflight []wsproto.InflightJob)
}

SessionStateReconciler receives every v13 register snapshot after recovery sinks are attached. It is separate from Adopter so live reconnects and server-restart adoption use the same persisted turn-event reconciliation.

type UpgradeObserver

type UpgradeObserver interface {
	UpgradeReported(workerID string, r wsproto.UpgradeResult)
	UpgradeRegistered(workerID, upgradeID, version string)
}

UpgradeObserver receives the upgrade events that happen outside the request/answer of UpgradeWorker: a worker's later failure/rollback report, and the registration of the replacement process (the success signal of a handover).

type WorkerRegistry

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

WorkerRegistry maps worker_id → live connection, concurrency-safe.

func (*WorkerRegistry) All

func (r *WorkerRegistry) All() []*workerConn

All returns a snapshot of every live connection (used on hub shutdown to gracefully close them all).

func (*WorkerRegistry) Get

func (r *WorkerRegistry) Get(workerID string) (*workerConn, bool)

Get returns the live connection for workerID, if any.

func (*WorkerRegistry) LastHeartbeat

func (r *WorkerRegistry) LastHeartbeat(workerID string) int64

LastHeartbeat returns the unix-seconds timestamp of the most recent inbound frame for workerID (0 when offline / never seen). It seeds the C6/P4 /v1/runners observability surface without exposing the internal conn.

func (*WorkerRegistry) MarkPolicyApplied

func (r *WorkerRegistry) MarkPolicyApplied(wc *workerConn, rev int64, rejected []wsproto.AppliedRejection, degraded []wsproto.AppliedDegrade)

MarkPolicyApplied records a worker's Applied report for one policy rev on ONE connection. It shares UpdateCaps's two invariants, on purpose (T4-D):

  1. It takes a *workerConn and drops the update unless this conn is still the registered one — a late Applied from a superseded/old process must not touch the live conn's diagnostic state (the same r.conns[id] != wc guard UpdateCaps uses).
  2. It writes under wc.mu, the lock WorkerSnapshot reads pending/rev under.

Clearing pending is Rev-MONOTONIC: only an Applied at or above the rev the hub is waiting on (wc.policyRev) clears pending and advances appliedRev. A stale Applied (rev < policyRev — the worker's report for an older rev arriving after the hub already pushed a newer one) is IGNORED and never rolls state back; rolling back would report an un-converged worker as converged. This pending is the SERVER-side diagnostic — a separate rev ladder from the worker executor's own applied lastRev.

func (*WorkerRegistry) Put

func (r *WorkerRegistry) Put(wc *workerConn) (old *workerConn)

Put registers wc under its worker_id. If a connection already exists for that worker_id it is returned (old) so the caller can gracefully close it: a same-worker_id reconnect replaces the prior connection (constraint #5; the token binding already guarantees it is the same authenticated identity).

The replaced connection is marked superseded — so its read-loop teardown does NOT fail its in-flight jobs (§5.5) — ONLY when the new conn carries the SAME instance_id, i.e. it is the same worker PROCESS re-establishing a dropped connection (a transient network reconnect): that process is still running those jobs, so failing them would be wrong. When the instance_id DIFFERS, a new process has taken over the worker_id (the old one restarted / was replaced); its in-flight jobs died with it, so the old conn is left un-superseded and its teardown fails them — the orphan-job fix (z8ow). Empty instance_id on BOTH (legacy workers) compares equal, preserving the original supersede-always behaviour.

func (*WorkerRegistry) Remove

func (r *WorkerRegistry) Remove(workerID string, wc *workerConn)

Remove deletes workerID's entry ONLY when the currently-registered connection is wc. This avoids a read-loop teardown for a replaced connection accidentally evicting the new connection that took its place.

func (*WorkerRegistry) UpdateCaps

func (r *WorkerRegistry) UpdateCaps(wc *workerConn, c wsproto.Caps)

UpdateCaps applies a worker's re-reported capabilities (a successful reload's ReloadResult.Caps, or an unsolicited SIGHUP-driven Caps frame) to ONE specific connection. Three things it must get right, none of them optional:

  1. It takes a *workerConn, not a worker_id. A worker that reconnects gets a NEW conn under the same id, while the OLD conn's read loop may still be draining frames — a caps frame from the dead process must not overwrite the live one's capabilities. So the update is dropped unless this conn is still the registered one (currentLocked check below).
  2. It writes meta under wc.mu, the same lock WorkerSnapshot reads it under. meta used to be immutable-after-register (published through the registry lock), which is exactly why the old lock-free read was safe and no longer is.
  3. It writes BOTH concurrency fields. wc.meta.MaxConcurrent is the displayed value; wc.maxConcurrent is the one tryReserve actually admits against. Updating only the first would show a new limit while enforcing the old one.

Caps is a FULL SNAPSHOT, not a patch: an empty Projects list means "this worker now serves no project", and is applied as such. MaxConc is NOT an exception to that rule — wsproto.Caps has no omitempty (see its doc) and every producer of a Caps value (workerCaps, the register-time seed) fills MaxConc unconditionally from the worker's resolved config, so a decoded 0 IS the worker's current "no cap" setting, not an absent field. Gating on c.MaxConc > 0 here would silently keep the OLD limit on a reload that intentionally uncaps the worker (max_concurrent: 0 in worker.yaml) — that was tried once and reverted (tools-49r); 0 is applied like any other value.

func (*WorkerRegistry) WorkerSnapshot

func (r *WorkerRegistry) WorkerSnapshot(workerID string) (WorkerSnapshot, bool)

WorkerSnapshot returns a point-in-time read-only view of workerID's live connection (ok=false when offline / never connected). It is the registry's C6 observability accessor: the handler reads it through a narrow interface so it never touches the internal conn.

The conn is looked up under the registry RLock, but everything it reads OUT of the conn is read under the per-conn lock (snapshot): since config hot-reload (P1) the capability fields are mutable on a live connection, so reading meta outside wc.mu would be a data race against UpdateCaps. The in-flight count comes from the same critical section, so a snapshot is internally consistent.

type WorkerSnapshot

type WorkerSnapshot struct {
	WorkerID            string
	InstanceID          string
	LastHeartbeat       int64 // unix seconds of the most recent inbound frame
	InFlight            int   // count of server-side dispatched jobs currently running
	PtyCapable          bool
	Labels              []string
	Projects            []string
	InteractiveProjects []string
	// Agents is the bare agent-key list (validation / selector, back-compat);
	// AgentCaps carries the typed detail (type/interactive) the UI cascade needs.
	// Both come straight from the worker's register frame (authoritative, P1).
	Agents    []string
	AgentCaps []wsproto.AgentBrief
	// Tools are the worker's declared external tools (CFG-16) — display only.
	Tools []wsproto.ToolBrief
	// Node info reported on register (P1) — surfaced for the P4 runners panel.
	OS           string
	Arch         string
	Hostname     string // self-reported machine hostname (register node info)
	RemoteAddr   string // conn's remote addr as seen at accept (may be NAT/bridge)
	GoferVersion string
	StartedAt    int64 // worker process start, unix seconds
	// ProtocolVersion is the wire version this connection registered with
	// (wc.meta.ProtocolVersion, immutable per-connection — see protocolVersion()).
	// Surfaced so an operator can spot a too-old worker (reload/policy gated by
	// wsproto.SupportsReload/SupportsPolicy) before a reload/policy push 409s.
	ProtocolVersion int
	MessengerStatus string
	// Messenger / Dirs come from the worker's heartbeat (protocol v16); nil = the
	// worker never reported them (an older build, or no ping yet).
	Messenger *wsproto.MessengerSnapshot
	Dirs      *wsproto.WorkDirs
	// Draining is true while the worker refuses new jobs because it is upgrading.
	Draining bool
	// Policy-push diagnostic state (P3 T4). PolicyPending is true while the worker has
	// negotiated policy support and the hub pushed a rev it has not yet reported applied;
	// a pre-policy (v3) worker is never marked pending. PolicyRev is the highest rev
	// pushed to it, AppliedRev the highest it reported applying.
	PolicyPending  bool
	PolicyRev      int64
	AppliedRev     int64
	PolicyRejected []wsproto.AppliedRejection
	PolicyDegraded []wsproto.AppliedDegrade
}

WorkerSnapshot is a read-only view of one worker's live state, taken under the registry lock. It seeds the C6/P4 /v1/runners observability surface without leaking the internal workerConn. Every slice is a defensive copy; an offline worker has no snapshot (WorkerSnapshot returns ok=false).

Jump to

Keyboard shortcuts

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