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
- Variables
- func Endpoint(base, path string) string
- func IntervalFromSeconds(secs float64) time.Duration
- func NewHTTPClient(o TLSOptions) (*http.Client, error)
- func Offer(ch chan Schedule, s Schedule)
- func RetryAfter(resp *http.Response) time.Duration
- func Run(ctx context.Context, o Options) error
- func RunPusher(ctx context.Context, o PushOptions)
- func WebSocketURL(base, path string) (string, error)
- type Backoff
- type Options
- type PushOptions
- type Schedule
- type Session
- func (s *Session) Call(ctx context.Context, method string, params, result any) error
- func (s *Session) Close(code websocket.StatusCode, reason string)
- func (s *Session) Context() context.Context
- func (s *Session) Notify(method string, params any) error
- func (s *Session) NotifyRaw(method string, params json.RawMessage) error
- func (s *Session) Subprotocol() string
- type StatusError
- type TLSOptions
Constants ¶
const ( MinPushInterval = time.Second MaxPushInterval = time.Hour )
Push interval bounds for IntervalFromSeconds.
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.
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 ¶
var ErrClosed = errors.New("link: session closed")
ErrClosed is returned by calls on a session that has ended.
Functions ¶
func IntervalFromSeconds ¶
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 ¶
Offer puts s on ch, replacing whatever schedule is still waiting there: only the newest one matters. It never blocks.
func RetryAfter ¶
RetryAfter reads a Retry-After header in seconds; 0 when absent.
func Run ¶
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 ¶
WebSocketURL maps the controller's base URL plus an API path to the ws:// or wss:// URL of that endpoint.
Types ¶
type Backoff ¶
Backoff is the reconnect delay: Min, doubling up to Max, with ±10 % jitter so a fleet of agents does not reconnect in lockstep.
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 ¶
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 ¶
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) 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 ¶
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 ¶
TLSOptions are the knobs an agent exposes for reaching its controller over https: a self-signed certificate (Insecure) or a private CA (CAFile).