Documentation
¶
Overview ¶
Package transport carries proto.Envelope frames between the daemon and the server-side agentdaemon gateway:
- Bootstrap — one-shot HTTP POST asking the server for the WS URL and heartbeat cadence; validates credential before WS handshake.
- Dial / Conn — the live WebSocket. Single send goroutine (gorilla requires single writer) and a bounded recv channel.
- Reconnect — exponential-backoff loop the caller drives.
Wire-only: nothing here knows about agent kinds.
Index ¶
- Constants
- Variables
- func DeriveWSURL(boot BootstrapResponse, serverBase string) (string, error)
- func Sleep(ctx context.Context, d time.Duration) error
- type BackoffPolicy
- type BootstrapResponse
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) DeviceID() string
- func (c *Conn) Done() <-chan struct{}
- func (c *Conn) Err() error
- func (c *Conn) Recv() <-chan proto.Envelope
- func (c *Conn) Send(ctx context.Context, env proto.Envelope) error
- func (c *Conn) StartHeartbeats(parentCtx context.Context, interval time.Duration, ...)
- type DialFn
- type DialOptions
Constants ¶
const CloseRuntimeDeleted = 4001
CloseRuntimeDeleted is the custom WS close code the server sends when the runtime has been deleted by an admin — permanent error.
Variables ¶
var DefaultBackoff = BackoffPolicy{ Initial: 1 * time.Second, Max: 30 * time.Second, Factor: 2.0, JitterFraction: 0.2, }
DefaultBackoff is the production policy.
var ErrConnClosed = errors.New("transport: connection closed")
ErrConnClosed is returned by Send on clean shutdown.
var ErrIncompatibleVersion = errors.New("transport: incompatible daemon version")
ErrIncompatibleVersion accompanies ErrPermanent when the gateway refuses the daemon's wire-protocol version (HTTP 426) rather than its credential.
var ErrPermanent = errors.New("transport: permanent error (do not retry)")
ErrPermanent is returned by a DialFn when the error must NOT be retried — e.g. 401 bad_credential or 426 incompatible_version.
Functions ¶
func DeriveWSURL ¶
func DeriveWSURL(boot BootstrapResponse, serverBase string) (string, error)
DeriveWSURL turns a Bootstrap response's ws_url into the absolute URL to dial. Empty ws_url (dev mode without a separate public hostname) is derived from serverBase by swapping http→ws / https→wss. Non- absolute ws_url is rejected — the server-side handler is the only component that knows the externally-reachable host.
Types ¶
type BackoffPolicy ¶
type BackoffPolicy struct {
// Initial is the first delay after attempt 1 fails. Zero → 1s.
Initial time.Duration
// Max caps any single delay. Zero → 30s.
Max time.Duration
// Factor is the multiplier between delays. ≤1 → 2.0.
Factor float64
// JitterFraction is ±range as a fraction of the unjittered delay.
// Zero disables jitter; default 0.2 gives ±20%.
JitterFraction float64
}
BackoffPolicy is the exponential-backoff schedule for redialing. Defaults: 1s → 2s → 4s → ... capped at 30s, with ±20% jitter so a fleet of restarting daemons doesn't thunder onto the gateway.
type BootstrapResponse ¶
type BootstrapResponse struct {
DeviceID string `json:"device_id"`
WorkspaceID string `json:"workspace_id"`
WSURL string `json:"ws_url"`
HeartbeatSeconds int `json:"heartbeat_seconds"`
ProtocolVersion string `json:"protocol_version"`
}
BootstrapResponse mirrors gateway/handler.go's Bootstrap response.
func Bootstrap ¶
func Bootstrap(ctx context.Context, serverURL, deviceID, credential, daemonVersion string) (*BootstrapResponse, error)
Bootstrap calls POST <serverURL>/agent-daemon/bootstrap with the device's runner_credential as a bearer token.
func BootstrapWithClient ¶
func BootstrapWithClient(ctx context.Context, client *http.Client, serverURL, deviceID, credential, daemonVersion string) (*BootstrapResponse, error)
BootstrapWithClient lets a connection entry point enforce its redirect policy.
func (BootstrapResponse) HeartbeatInterval ¶
func (b BootstrapResponse) HeartbeatInterval() time.Duration
HeartbeatInterval defends against the server returning 0 — a zero heartbeat means "never ping" which guarantees a 60s timeout, so we fall back to 15s instead of silently breaking liveness.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is the daemon-side WebSocket. One read goroutine + one write goroutine; callers Send synchronously and Recv off a channel.
Conn does NOT own the heartbeat loop — call StartHeartbeats once Dial returns. Splitting keeps transport free of "what's a live request count" knowledge.
func Dial ¶
func Dial(ctx context.Context, opts DialOptions) (*Conn, error)
Dial opens the reverse WebSocket. Read/write goroutines are live on return; caller MUST eventually Close to avoid goroutine leaks.
func Reconnect ¶
func Reconnect(ctx context.Context, dial DialFn, policy BackoffPolicy, onAttempt func(attempt int, lastDelay time.Duration, lastErr error)) (*Conn, error)
Reconnect loops on dial calls with exponential backoff. First attempt has no warm-up delay. onAttempt (if non-nil) is invoked before each attempt with the attempt index, last delay slept, and the previous dial error — surfacing lastErr lets the caller log root causes instead of hiding them behind retry bookkeeping.
func (*Conn) Close ¶
Close tears down the conn. Safe to call concurrently; idempotent. The courteous CloseMessage frame is NOT written from here — writeLoop owns single-writer access and emits it from its defer.
func (*Conn) Done ¶
func (c *Conn) Done() <-chan struct{}
Done closes when the connection has shut down.
func (*Conn) Err ¶
Err returns the first fatal error from either loop, or nil on clean shutdown via Close.
func (*Conn) Recv ¶
Recv returns the inbound envelope channel. Closes when the connection terminates; Err() returns the cause after.
func (*Conn) Send ¶
Send marshals env, queues it, and blocks until written (or ctx fires / conn closes). Safe for concurrent callers — the write goroutine is the only thing touching the underlying ws write path.
func (*Conn) StartHeartbeats ¶
func (c *Conn) StartHeartbeats(parentCtx context.Context, interval time.Duration, payloadFn func() proto.HeartbeatPayload, logger *slog.Logger)
StartHeartbeats kicks off a ticker that calls payloadFn every interval and Sends the resulting HeartbeatPayload. Returns immediately. Caller-controlled because the heartbeat carries fields (active_requests, supported_agent_kinds) only the agent layer knows. Nil logger falls back to log.Bg().
type DialFn ¶
DialFn is invoked once per attempt. Wrap with ErrPermanent on auth/ protocol fatalities; any other error triggers backoff + retry.
type DialOptions ¶
type DialOptions struct {
// WSURL is the absolute ws://... or wss://... URL.
WSURL string
// DeviceID is the runtime row id stamped at pair time. Sent as
// device_id query param; the gateway uses it as the session key.
DeviceID string
// Credential is the bearer compared against runner_credential_hash.
// Sent only as an Authorization bearer header.
Credential string
// DaemonVersion is the X.Y.Z string used for
// proto.VersionCompatible. Mismatches reject the HTTP upgrade with 426.
DaemonVersion string
// HandshakeTimeout caps WS upgrade wait. Zero → 10s.
HandshakeTimeout time.Duration
// HTTPHeader is appended to the upgrade request. Useful in tests.
HTTPHeader http.Header
}
DialOptions is the input to Dial. HTTPHeader is optional.