transport

package
v0.0.14-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 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

Overview

Package transport carries proto.Envelope frames between the daemon and the server-side agentdaemon gateway:

  1. Bootstrap — one-shot HTTP POST asking the server for the WS URL and heartbeat cadence; validates credential before WS handshake.
  2. Dial / Conn — the live WebSocket. Single send goroutine (gorilla requires single writer) and a bounded recv channel.
  3. Reconnect — exponential-backoff loop the caller drives.

Wire-only: nothing here knows about agent kinds.

Index

Constants

View Source
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

View Source
var DefaultBackoff = BackoffPolicy{
	Initial:        1 * time.Second,
	Max:            30 * time.Second,
	Factor:         2.0,
	JitterFraction: 0.2,
}

DefaultBackoff is the production policy.

View Source
var ErrConnClosed = errors.New("transport: connection closed")

ErrConnClosed is returned by Send on clean shutdown.

View Source
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.

View Source
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 Bootstrap

func Bootstrap(ctx context.Context, serverURL, deviceID, credential, daemonVersion string) (*machineapi.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) (*machineapi.BootstrapResponse, error)

BootstrapWithClient lets a connection entry point enforce its redirect policy.

func DeriveWSURL

func DeriveWSURL(boot machineapi.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.

func Sleep

func Sleep(ctx context.Context, d time.Duration) error

Sleep blocks for d unless ctx fires first. Returns ctx.Err() on cancellation so callers can decide whether to bail out of the reconnect loop. Returns nil on normal expiry.

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.

func (BackoffPolicy) Delay

func (p BackoffPolicy) Delay(attempt int) time.Duration

Delay returns the delay before attempt n (1-indexed: attempt 1 = the FIRST retry after the initial failure). The result is jittered and clamped to [0, Max].

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

func (c *Conn) Close() error

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) DeviceID

func (c *Conn) DeviceID() string

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done closes when the connection has shut down.

func (*Conn) Err

func (c *Conn) Err() error

Err returns the first fatal error from either loop, or nil on clean shutdown via Close.

func (*Conn) Recv

func (c *Conn) Recv() <-chan proto.Envelope

Recv returns the inbound envelope channel. Closes when the connection terminates; Err() returns the cause after.

func (*Conn) Send

func (c *Conn) Send(ctx context.Context, env proto.Envelope) error

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 (supported_agent_kinds) only the agent layer knows. Nil logger falls back to log.Bg().

type DialFn

type DialFn func(ctx context.Context) (*Conn, error)

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 from the daemon credential. 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
}

DialOptions is the input to Dial.

Jump to

Keyboard shortcuts

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