link

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 20 Imported by: ? 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 link keeps an agent's WebSocket session to the Perch controller: dial with the agent's credentials, keep the connection alive with pings, serve the controller's JSON-RPC requests, route its notifications, make calls of the agent's own and push on the schedule the controller sets.

One Run is one session. Reconnecting, and what each way of ending means (revoked, replaced, dismissed, server restarting), is the daemon's policy: the AP daemon rejoins with a token, the collector waits for an admin.

Index

Constants

View Source
const (
	MinPushInterval = time.Second
	MaxPushInterval = time.Hour
)

Push interval bounds for IntervalFromSeconds.

View Source
const (
	// CloseRevoked: the credentials this session presented are no longer
	// valid (agent forgotten, collector deleted or re-keyed).
	CloseRevoked websocket.StatusCode = 4001
	// CloseReplaced: a newer session with the same identity took over.
	CloseReplaced websocket.StatusCode = 4002
	// CloseDismissed: an admin dismissed this collector.
	CloseDismissed websocket.StatusCode = 4003
)

Close codes shared by the Perch protocols.

View Source
const (
	DefaultDialTimeout  = 20 * time.Second
	DefaultPingInterval = 30 * time.Second
	DefaultPingTimeout  = 10 * time.Second
	DefaultWriteTimeout = 10 * time.Second
	DefaultReadLimit    = 4 << 20
	DefaultMaxInFlight  = 4
)

Defaults for the zero values of Options.

Variables

View Source
var ErrClosed = errors.New("link: session closed")

ErrClosed is returned by calls on a session that has ended.

Functions

func Endpoint

func Endpoint(base, path string) string

Endpoint joins the controller's base URL and an API path.

func IntervalFromSeconds

func IntervalFromSeconds(secs float64) time.Duration

IntervalFromSeconds turns agent.configure's seconds into an interval: 0 or less pauses, anything else is clamped to [MinPushInterval, MaxPushInterval].

func NewHTTPClient

func NewHTTPClient(o TLSOptions) (*http.Client, error)

NewHTTPClient builds the client for joins, announces and the WebSocket handshake. HTTP/1.1 only: an HTTP/2 connection cannot be upgraded.

func Offer

func Offer(ch chan Schedule, s Schedule)

Offer puts s on ch, replacing whatever schedule is still waiting there: only the newest one matters. It never blocks.

func RetryAfter

func RetryAfter(resp *http.Response) time.Duration

RetryAfter reads a Retry-After header in seconds; 0 when absent.

func Run

func Run(ctx context.Context, o Options) error

Run dials once and serves the session until it ends. It returns nil when ctx is done (after a 1001 close), a *StatusError when the controller refused the upgrade, and otherwise the error that ended the session: websocket.CloseStatus(err) is the controller's close code, -1 for a dropped connection or a missed pong.

func RunPusher

func RunPusher(ctx context.Context, o PushOptions)

RunPusher pushes on the controller's schedule until ctx is done: the first push right after the first schedule, then one per interval measured from the start of the previous push, so a slow collection does not drift the cadence. A later schedule keeps the cadence with the new interval; interval 0 pauses and the next non-zero schedule resumes it.

func WebSocketURL

func WebSocketURL(base, path string) (string, error)

WebSocketURL maps the controller's base URL plus an API path to the ws:// or wss:// URL of that endpoint.

Types

type Backoff

type Backoff struct {
	Min, Max time.Duration
	// contains filtered or unexported fields
}

Backoff is the reconnect delay: Min, doubling up to Max, with ±10 % jitter so a fleet of agents does not reconnect in lockstep.

func (*Backoff) Next

func (b *Backoff) Next() time.Duration

Next returns the next delay.

func (*Backoff) Reset

func (b *Backoff) Reset()

Reset starts the ladder over (after a session that lasted).

type Options

type Options struct {
	// URL is the ws:// or wss:// endpoint (see WebSocketURL).
	URL string
	// Subprotocol is offered and required ("perch-ap.v1", …); empty offers none.
	Subprotocol string
	// Header is sent with the upgrade request (credentials, User-Agent).
	Header http.Header
	// HTTPClient performs the handshake (see NewHTTPClient); nil = default.
	HTTPClient *http.Client
	// Compression offers permessage-deflate without context takeover.
	Compression bool
	// ReadLimit caps one message from the controller (default 4 MiB).
	ReadLimit int64
	// Log gets connection-level lines; nil = slog.Default().
	Log *slog.Logger
	// Dispatcher serves the controller's requests; nil answers -32601.
	Dispatcher *rpc.Dispatcher
	// OnNotification gets the controller's notifications in frame order, on
	// the read goroutine: keep it quick (hand work off to a channel).
	OnNotification func(ctx context.Context, s *Session, m *rpc.Message)
	// OnOpen runs in its own goroutine once the session is reading, so it may
	// Call the controller. Its ctx ends with the session, and Run waits for
	// it to return: it must not outlive ctx.
	OnOpen func(ctx context.Context, s *Session)

	DialTimeout  time.Duration // default 20 s
	PingInterval time.Duration // default 30 s
	PingTimeout  time.Duration // default 10 s
	WriteTimeout time.Duration // default 10 s, per message
	MaxInFlight  int           // concurrent controller requests, default 4
}

Options configure one session.

type PushOptions

type PushOptions struct {
	// Configs delivers the controller's schedules (see Offer).
	Configs <-chan Schedule
	// Fallback is used when no schedule arrives within FallbackWait (a
	// controller too old to send one). nil waits for a schedule forever.
	Fallback     *Schedule
	FallbackWait time.Duration
	// MinGap is the shortest wait between two pushes (default MinPushInterval).
	MinGap time.Duration
	// Push sends one push; seq counts from 1 within the session.
	Push func(ctx context.Context, seq uint64)
	Log  *slog.Logger
}

PushOptions configure RunPusher.

type Schedule

type Schedule struct {
	Interval time.Duration
}

Schedule is the push cadence the controller sets with agent.configure. Interval 0 pauses pushing.

type Session

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

Session is one open connection to the controller.

func (*Session) Call

func (s *Session) Call(ctx context.Context, method string, params, result any) error

Call sends a request and waits for the controller's answer. An error response comes back as *rpc.Error; result may be nil to ignore the result.

func (*Session) Close

func (s *Session) Close(code websocket.StatusCode, reason string)

Close ends the session with a close frame.

func (*Session) Context

func (s *Session) Context() context.Context

Context ends when the session does.

func (*Session) Notify

func (s *Session) Notify(method string, params any) error

Notify sends a notification.

func (*Session) NotifyRaw

func (s *Session) NotifyRaw(method string, params json.RawMessage) error

NotifyRaw sends a notification whose params are already encoded JSON, without decoding and re-encoding them (large pushes).

func (*Session) Subprotocol

func (s *Session) Subprotocol() string

Subprotocol is what the controller selected.

type StatusError

type StatusError struct {
	Status     int
	Code       string // `error` field of the body, when JSON
	Message    string
	RetryAfter time.Duration
}

StatusError is a non-success HTTP answer from the controller: a refused WebSocket upgrade, or a failed join or announce.

func ReadStatusError

func ReadStatusError(resp *http.Response) *StatusError

ReadStatusError describes a non-success response. It understands the controller's error bodies ({error, message}, validation {errors: [...]}, retryAfterSeconds) and the Retry-After header, and reads at most 4 KiB.

func (*StatusError) Error

func (e *StatusError) Error() string

type TLSOptions

type TLSOptions struct {
	Insecure bool
	CAFile   string
}

TLSOptions are the knobs an agent exposes for reaching its controller over https: a self-signed certificate (Insecure) or a private CA (CAFile).

Jump to

Keyboard shortcuts

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