transport

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 48 Imported by: 0

Documentation

Overview

Package transport provides mutually authenticated, multiplexed peer sessions over WebRTC data channels or the gateway's WebSocket relay.

Index

Constants

View Source
const DuplexVersion = 1
View Source
const LogStreamVersion = "task-logs-v1"
View Source
const MaxLogChunk = 64 * 1024
View Source
const MaxTCPListenerConnections = 128
View Source
const TCPListenerProtocol = "tcp-listen-v1"

Variables

View Source
var ErrHalfCloseUnsupported = errors.New("connection does not support write-side EOF")
View Source
var ErrTransientSetup = errors.New("transient peer setup failure")

ErrTransientSetup matches peer setup failures that left the request unsent and are expected to clear when the gateway relay, the network path, or the remote peer recovers: relay maintenance drains, network changes during setup, peer sessions closed during setup, gateway reconnects, and setup timeouts while the caller is still waiting. It is a classification for idempotent observation only; it never authorizes replaying effects.

Functions

func Bridge

func Bridge(ctx context.Context, a, b net.Conn)

Bridge preserves the opposite direction after graceful EOF when the destination supports CloseWrite. Errors, cancellation, and legacy full-close streams end both directions. Every copy goroutine is joined before return.

func CloseWrite

func CloseWrite(conn net.Conn) error

func NewTCPListener

func NewTCPListener(ctx context.Context, conn net.Conn, address string) (net.Listener, error)

NewTCPListener receives sockets multiplexed within an authorized tcp.listen stream. EOF records preserve TCP half-close independently of yamux FIN.

func ReadMachineState

func ReadMachineState(ctx context.Context, base string, route gatewayroute.Route, id *identity.Identity, revision uint64, inspectOnly bool) (model.MachineState, bool, error)

ReadMachineState reads only the signing identity's policy, even after its bearer credential has been revoked. The bool reports gateway lifecycle support. A proxied route keeps signed retirement reads working without direct access.

func RetryableDelivery added in v0.9.0

func RetryableDelivery(err error) bool

RetryableDelivery reports whether err is a local delivery failure that may clear on reconnect: a transient setup failure, a stream or multiplexer that broke, or a network timeout. Callers must pass only locally produced causes, never errors decoded from a remote reply, and must check their own context first. Use it only to repeat idempotent reads to a target that has already authenticated and accepted the related request; it is not permission to resend anything with effects.

Context errors (other than a setup timeout already classified at its source), TLS and certificate failures, oversized frames, and gateway authentication or protocol errors are not retryable.

func ServeConnectionTest

func ServeConnectionTest(conn net.Conn, q model.ConnectionTestOptions) error

ServeConnectionTest runs only after the node checks membership, instruction authority, method permissions, concurrency, and maintenance admission.

func ServeTCPListener

func ServeTCPListener(ctx context.Context, stream net.Conn, listener net.Listener, wrap func(net.Conn) net.Conn) error

ServeTCPListener owns the bound listener and all of its sockets. Losing the requesting stream closes them even while no TCP connections are active.

func ValidateLogChunk

func ValidateLogChunk(chunk model.TaskLogChunk, offset int64) error

func WaitForGateway

func WaitForGateway(ctx context.Context, operation string, call func(context.Context) error) error

WaitForGateway retries transient connection and policy-query failures during node startup. It must not be used to replay execution or other side effects. Authentication, protocol, TLS validation, and local persistence errors fail immediately. The caller's context owns the entire wait.

Types

type Config

type Config struct {
	Client            bool
	Gateway           string
	Token             string
	Identity          *identity.Identity
	ClientOwner       *identity.Identity
	Node              model.Node
	RelayOnly         bool
	ICEServers        []webrtc.ICEServer
	DirectTimeout     time.Duration
	RequireDelegation bool
	// Route carries every gateway request: authentication, WebSocket,
	// directory, policy, and placement reads. The zero value is direct.
	Route gatewayroute.Route
	// NameHints optionally remembers routing-name identities across short-lived
	// clients so a name lookup can read one gateway record, not the directory.
	NameHints NameHints
}

type DuplexConn

type DuplexConn struct {
	net.Conn
	// contains filtered or unexported fields
}

DuplexConn adds bounded data records and a write-side EOF record to a byte stream. This keeps TCP half-close independent of yamux and WebSocket Close.

func NewDuplexConn

func NewDuplexConn(conn net.Conn) *DuplexConn

func (*DuplexConn) Close

func (c *DuplexConn) Close() error

func (*DuplexConn) CloseWrite

func (c *DuplexConn) CloseWrite() error

func (*DuplexConn) Read

func (c *DuplexConn) Read(b []byte) (int, error)

func (*DuplexConn) Write

func (c *DuplexConn) Write(b []byte) (int, error)

type Lane

type Lane string

Lanes isolate long-lived and bulk traffic from short control RPCs. Each lane has its own authenticated TLS/yamux session, including on legacy receivers.

const (
	ControlLane     Lane = "control"
	BulkLane        Lane = "bulk"
	InteractiveLane Lane = "interactive"
	IncomingLane    Lane = "incoming"
)

type NameHints added in v0.10.2

type NameHints interface {
	Hint(name string) string
	Remember(nodes []model.Node)
}

NameHints suggests the stable identity last seen for a routing name. A hint is never authority: lookups accept it only when the gateway's current record for that identity still carries the requested name.

type Options added in v0.6.3

type Options struct {
	// ConfigureWebRTC customizes each peer's legacy and trickle setting engines
	// after the transport defaults are applied and before its APIs are created.
	ConfigureWebRTC func(*webrtc.SettingEngine) `json:"-"`
}

Options supplies per-peer construction settings, not serialized node or wire configuration. The zero value retains the production networking defaults.

type Peer

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

func New

func New(cfg Config, handler func(string, net.Conn), options ...Options) *Peer

func (*Peer) Close

func (p *Peer) Close() error

func (*Peer) ConnectionRoutes added in v0.2.0

func (p *Peer) ConnectionRoutes() model.ConnectionRouteCounts

ConnectionRoutes separates direct ICE paths, TURN, and the gateway relay. Like Connections, it counts each usable peer once and prefers WebRTC over gateway relay sessions, including relays draining after a direct re-probe.

func (*Peer) Connections

func (p *Peer) Connections() map[string]string

func (*Peer) FollowTaskLogs

func (p *Peer) FollowTaskLogs(ctx context.Context, target, id string, offset int64, emit func(model.TaskLogChunk) error) error

FollowTaskLogs uses one stream on upgraded receivers, or read-only polling on older ones. It never reconnects a broken stream or resubmits the task.

func (*Peer) GatewayConnected added in v0.9.1

func (p *Peer) GatewayConnected() <-chan struct{}

GatewayConnected signals successful registration and reconnections. Unread signals coalesce; receiving one does not prove ongoing connection health.

func (*Peer) GatewaySession added in v0.10.5

func (p *Peer) GatewaySession() uint64

GatewaySession changes after each successful gateway connection. Telemetry that suppresses unchanged reports must send them again to a new connection.

func (*Peer) IdentityID

func (p *Peer) IdentityID() string

func (*Peer) IsMember

func (p *Peer) IsMember(id string) bool

IsMember only accepts identities attested by this gateway's scoped directory. Identity ownership is immutable, so established direct sessions can remain usable during a gateway outage without crossing fleet boundaries.

func (*Peer) Lookup

func (p *Peer) Lookup(ctx context.Context, name string) (model.Node, error)

Lookup separates fleet-machine discovery from identity checks for live clients. Online results are reused briefly; the gateway's offline notification for an identity, a directory change, or a reconnect evicts them early.

func (*Peer) MachineState

func (p *Peer) MachineState(ctx context.Context, revision uint64) (model.MachineState, bool, error)

func (*Peer) MachineStatePushed added in v0.5.7

func (p *Peer) MachineStatePushed() bool

MachineStatePushed reports whether a live gateway connection will hint at policy changes, so the node can rely on a slower poll as its fallback.

func (*Peer) MachineStateWake added in v0.5.7

func (p *Peer) MachineStateWake() <-chan struct{}

MachineStateWake signals that this node should read its policy now.

func (*Peer) Nodes

func (p *Peer) Nodes(ctx context.Context) ([]model.Node, error)

func (*Peer) Open

func (p *Peer) Open(ctx context.Context, target string) (net.Conn, error)

func (*Peer) OpenLane

func (p *Peer) OpenLane(ctx context.Context, target string, lane Lane) (net.Conn, error)

func (*Peer) OpenRPC

func (p *Peer) OpenRPC(ctx context.Context, target, method string, params any) (net.Conn, json.RawMessage, error)

OpenRPC sends one request. The returned stream may contain a bulk payload. It never replays a request after writing application bytes.

func (*Peer) OpenRPCWithReceipt added in v0.8.5

func (p *Peer) OpenRPCWithReceipt(ctx context.Context, target, method string, params any) (net.Conn, json.RawMessage, *model.TaskSubmissionReceipt, error)

OpenRPCWithReceipt also returns a stream-bound task acceptance receipt, when supported. Lost or legacy replies never imply that authority was unused.

func (*Peer) OpenTCP

func (p *Peer) OpenTCP(ctx context.Context, target, address string) (net.Conn, error)

OpenTCP negotiates duplex records. Older receivers return a raw stream.

func (*Peer) OpenTCPListener

func (p *Peer) OpenTCPListener(ctx context.Context, target, listen string) (net.Conn, string, error)

OpenTCPListener binds a remote port without granting the receiver access to arbitrary services on the caller. Only sockets on this stream are forwarded.

func (*Peer) Owner

func (p *Peer) Owner(id string) string

Owner is derived only from authenticated gateway metadata, never from an RPC. Transport identities still identify artifact-grant recipients and TLS peers.

func (*Peer) ParkGateway added in v0.9.2

func (p *Peer) ParkGateway(until time.Time) bool

ParkGateway is used only after the node has durably reserved idle admission. No relay, pending connection setup, or admitted HTTP request may be severed. The ordinary reconnect loop wakes at the bounded route deadline.

func (*Peer) Prepare added in v0.10.2

func (p *Peer) Prepare(ctx context.Context, target string, lane Lane) error

Prepare establishes or reuses a lane session without opening a stream or sending a request, so callers can overlap connection setup with other work.

func (*Peer) Resolve

func (p *Peer) Resolve(ctx context.Context, name string) (model.Node, error)

func (*Peer) Select

func (p *Peer) Select(ctx context.Context, args json.RawMessage) (model.Node, error)

Select uses the same admission filters for node and standalone callers. Among matching machines it prefers the one reporting the fewest active operations, choosing randomly among ties or when load is not visible.

func (*Peer) SendControl

func (p *Peer) SendControl(ctx context.Context, kind string, data []byte) error

func (*Peer) SessionStats

func (p *Peer) SessionStats() []model.PeerSession

func (*Peer) SetCapabilities

func (p *Peer) SetCapabilities(capabilities []model.Capability)

SetCapabilities updates registration metadata before Start.

func (*Peer) SetControlHandler

func (p *Peer) SetControlHandler(handler func(string, []byte))

func (*Peer) SetProxyEndpoints added in v0.9.1

func (p *Peer) SetProxyEndpoints(endpoints []model.ProxyEndpoint)

SetProxyEndpoints updates future registration without reconnecting peers.

func (*Peer) SetProxyManagementHandler added in v0.9.1

func (p *Peer) SetProxyManagementHandler(handler func([]byte))

SetProxyManagementHandler installs the fixed owner-management handler.

func (*Peer) SetSecretsHandler added in v0.6.0

func (p *Peer) SetSecretsHandler(key []byte, handler func([]byte))

SetSecretsHandler installs a bounded, gateway-only management handler before Start.

func (*Peer) SetSoftware

func (p *Peer) SetSoftware(info buildinfo.Info)

func (*Peer) SetStartupHandler added in v0.5.0

func (p *Peer) SetStartupHandler(handler func([]byte))

SetStartupHandler is configured before Start by an installed node only.

func (*Peer) SetSystemInfo

func (p *Peer) SetSystemInfo(info model.SystemInfo)

SetSystemInfo attaches an initial hardware/resource snapshot before Start.

func (*Peer) SetWakeHandler added in v0.5.0

func (p *Peer) SetWakeHandler(handler func([]byte))

SetWakeHandler receives wake requests the gateway relays for the fleet owner.

func (*Peer) Start

func (p *Peer) Start(ctx context.Context) error

func (*Peer) Stats

func (p *Peer) Stats() model.TransportStats

Stats reports cumulative transport counters for local diagnostics.

func (*Peer) SupportsNodeHealth

func (p *Peer) SupportsNodeHealth() bool

SupportsNodeHealth prevents new reports from disconnecting older gateways.

func (*Peer) TelemetryLiveness added in v0.10.5

func (p *Peer) TelemetryLiveness() bool

TelemetryLiveness reports whether the current gateway keeps unchanged health and update status fresh through heartbeat echoes.

func (*Peer) TestConnection

func (p *Peer) TestConnection(ctx context.Context, target string, options model.ConnectionTestOptions) (model.ConnectionTestResult, error)

TestConnection measures one authenticated bulk stream, without disk staging or replay. Upload/download are sequential and relative to the initiating peer.

Directories

Path Synopsis
Package transporttest supplies isolated transport construction for local tests.
Package transporttest supplies isolated transport construction for local tests.

Jump to

Keyboard shortcuts

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