transport

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 9 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 provides a long-lived WSS client with automatic reconnect, exponential backoff with jitter, and native ping/pong heartbeat. It is the binary's outbound network primitive to the relay.

The package is generic over frame payload. It accepts and emits []byte and knows nothing about pyrycode's protocol envelope, handshake, or routing. Protocol semantics live in internal/dispatch (future ticket); the wire-format types live in internal/protocol.

The single source of truth for the reconnect cadence and heartbeat constants is docs/protocol-mobile.md (§ Heartbeat, § Reconnect). When that document changes, this package changes.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotConnected is returned by Send when there is no live conn.
	ErrNotConnected = errors.New("transport: not connected")

	// ErrClosed is returned by Send and Receive after Close (or the
	// parent context cancellation) has shut the client down.
	ErrClosed = errors.New("transport: client closed")

	// ErrDisconnected is returned by Receive when the underlying conn
	// dropped while Receive was blocked, or when no conn is currently
	// live. Callers observing this should NOT treat it as a re-handshake
	// trigger directly — observe Connected() for that. ErrDisconnected
	// means "your current Receive call returned because the wire dropped,
	// not because data arrived."
	ErrDisconnected = errors.New("transport: connection lost")

	// ErrFatalClose wraps a websocket close error whose status is in
	// Config.FatalCloseCodes. Returned by Connect; the underlying status
	// is recoverable via websocket.CloseStatus(err).
	ErrFatalClose = errors.New("transport: fatal close code")

	// ErrUpgradeRejected wraps a dial error where the relay returned a
	// non-101 HTTP response to the WebSocket upgrade (e.g. 404 on a wrong
	// URL path), as distinct from a network-level dial failure (DNS,
	// connection refused, TLS). Connect surfaces it loudly (WARN) on the
	// first failed upgrade per outage; the HTTP status is in the wrapped
	// error string. It is NOT a fatal close — the loop keeps retrying.
	ErrUpgradeRejected = errors.New("transport: websocket upgrade rejected")
)

Sentinel errors.

Functions

This section is empty.

Types

type Client

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

Client maintains a single long-lived WSS connection with auto-reconnect. Methods are concurrency-safe. The zero value is not usable — call New.

func New

func New(cfg Config) *Client

New returns a Client. The Client is not yet connected; call Connect.

func (*Client) Close

func (c *Client) Close() error

Close shuts the client down. Idempotent.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect runs the dial-and-serve lifecycle until ctx is cancelled or Close is called. It returns ctx.Err() on shutdown or ErrClosed if Close was called; it never returns nil. Callers run it in its own goroutine.

Reconnect mechanics:

  • On each failed dial, sleep backoff(attempt) (1s/2s/4s/8s/16s/30s cap, ±20% jitter). Attempt counter increments per attempt.
  • On each successful dial, serve the conn (pump send/recv, ping every 30s). When the conn drops, record uptime; if uptime ≥ 60s reset the attempt counter to 1, otherwise increment.
  • ctx cancellation breaks out of any sleep, any dial, any pump.

func (*Client) Connected

func (c *Client) Connected() <-chan struct{}

Connected returns a channel that emits a value on every successful underlying conn. Buffer is 1 with drop-on-full semantics: a slow observer sees the most recent connect event, not every connect since boot. Multiple observers are NOT supported.

func (*Client) DropConn

func (c *Client) DropConn()

DropConn force-closes the live conn (if any) abruptly (1006-like), without sending a close frame. The serve loop sees the closed conn, returns to the dial loop, and reconnects via backoff. DropConn does NOT halt the dial loop. Idempotent (safe to call when no conn is live).

CloseNow is used in preference to Close(status, reason) so the caller is not blocked for up to 10s waiting on a close handshake when the only purpose is to recycle the conn. Callers wishing to communicate a status to the peer should use Close on the application channel before invoking DropConn.

func (*Client) IsConnected added in v0.16.0

func (c *Client) IsConnected() bool

IsConnected reports whether a live conn exists AND the client is not closed — a cheap synchronous level poll for callers deciding BEFORE a side-effecting op (contrast Connected() <-chan struct{}, the edge-triggered connect signal used to re-run the application handshake). It agrees with Send's own predicate: false ⇒ Send would return ErrClosed/ErrNotConnected; true ⇒ Send has a live conn at poll time — though the conn may still drop before the next Send, so a true result is best-effort while a false result reliably means "would drop".

Gates on closeCh as well as c.conn because Close closes closeCh but does not nil c.conn, so a closed client must still read down. Used by the v2 push drain's pre-seal transport probe (#874).

func (*Client) Receive

func (c *Client) Receive(ctx context.Context) ([]byte, error)

Receive blocks until the next frame arrives, ctx is cancelled, the client is closed, or the underlying conn drops. Returns ErrDisconnected when the conn drops (or when no conn is currently live); the caller observes Connected() to learn when a fresh conn becomes available and re-runs any application-layer handshake on it.

func (*Client) Send

func (c *Client) Send(frame []byte) error

Send writes a single frame to the relay. Returns ErrNotConnected if no live conn at call time, ErrClosed if Close was called, or ErrDisconnected if the live conn drops while Send is blocked enqueuing the frame. A nil return means the frame was queued for the send pump, not that it has hit the wire.

type Config

type Config struct {
	URL     string
	Headers http.Header

	// WriteTimeout bounds per-frame send I/O — it is NOT an inactivity
	// timeout; the inactivity contract is the ping/pong heartbeat. When
	// left unset (non-positive), New substitutes defaultWriteTimeout (10s)
	// so a zero-value config does not produce an instantly-expired write
	// context that fails every send.
	WriteTimeout time.Duration

	// Logger receives structured lifecycle logs (dial, reconnect, ping
	// timeout). Required; nil panics at New() time.
	Logger *slog.Logger

	// FatalCloseCodes lists WS close codes that terminate Connect's
	// reconnect loop with ErrFatalClose. Empty (default) preserves the
	// generic "reconnect on every drop" behaviour. The relay layer (#248)
	// passes []websocket.StatusCode{4409} so a server-id conflict halts
	// rather than spinning in backoff forever.
	FatalCloseCodes []websocket.StatusCode

	// FatalCloseThreshold is the number of CONSECUTIVE fatal-close
	// observations required before Connect returns ErrFatalClose. Below
	// the threshold the loop logs a WARN and retries through the standard
	// backoff ladder; any cycle that ends without a fatal close resets
	// the consecutive counter. Zero or one means a single fatal close
	// terminates immediately (the pre-#1072 behaviour).
	//
	// Rationale (#1072, incident 2026-07-16): after a drop the loop
	// re-dials with no delay, but the relay releases a dead connection's
	// server-id claim only once IT observes the disconnect — worst case
	// ~60s on a silently dead path (30s ping interval + 30s pong wait).
	// A reconnect inside that blind window collides with the daemon's own
	// stale claim and draws a transient 4409. The relay layer passes 8:
	// the intervening backoff sleeps (1+2+4+8+16+30+30s, ±20% jitter)
	// span ≥ ~73s even at minimum jitter, so a self-race always clears
	// before the threshold, while a genuine duplicate keeps conflicting,
	// exhausts the window in ~90s, and still halts.
	FatalCloseThreshold int
}

Config carries the static configuration for a Client. The caller supplies the relay URL and any request headers (server-id, binary-version, protocol-versions); this package does not construct headers.

Jump to

Keyboard shortcuts

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