client

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNoRoute = errors.New("client: no route configured")

ErrNoRoute is returned by connect handlers to indicate that the request should fall back to the default configuration-based routing.

Functions

This section is empty.

Types

type AttestationConfig added in v0.2.0

type AttestationConfig struct {
	Command                    string            `yaml:"command"`
	Args                       []string          `yaml:"args"`
	Env                        map[string]string `yaml:"env"`
	TimeoutSeconds             int               `yaml:"timeoutSeconds"`
	CacheHandshakeSeconds      int               `yaml:"cacheHandshakeSeconds"`
	HMACSecret                 string            `yaml:"hmacSecret"`
	HMACSecretFile             string            `yaml:"hmacSecretFile"`
	TokenTTLSeconds            int               `yaml:"tokenTTLSeconds"`
	HandshakeMaxAgeSeconds     int               `yaml:"handshakeMaxAgeSeconds"`
	ReauthIntervalSeconds      int               `yaml:"reauthIntervalSeconds"`
	ReauthGraceSeconds         int               `yaml:"reauthGraceSeconds"`
	MaintenanceGraceCapSeconds int               `yaml:"maintenanceGraceCapSeconds"`
	AuthorizerStatusURI        string            `yaml:"authorizerStatusUri"`
	PolicyVersion              string            `yaml:"policyVersion"`
}

type AttestationOptions added in v0.2.0

type AttestationOptions struct {
	Command                    string
	Args                       []string
	Env                        map[string]string
	Timeout                    time.Duration
	CacheHandshake             time.Duration
	HMACSecret                 string
	HMACSecretFile             string
	TokenTTL                   time.Duration
	HandshakeMaxAgeSeconds     int
	ReauthIntervalSeconds      int
	ReauthGraceSeconds         int
	MaintenanceGraceCapSeconds int
	AuthorizerStatusURI        string
	PolicyVersion              string
}

AttestationOptions contains configuration for generating attestation tokens.

type BackendConfig

type BackendConfig struct {
	Name           string              `yaml:"name"`
	Hostname       string              `yaml:"hostname"`
	Hostnames      []string            `yaml:"hostnames"`
	TCPPorts       []int               `yaml:"tcpPorts,omitempty"`
	UDPRoutes      []UDPRouteConfig    `yaml:"udpRoutes,omitempty"`
	NexusAddresses []string            `yaml:"nexusAddresses"`
	Weight         int                 `yaml:"weight"`
	Attestation    AttestationConfig   `yaml:"attestation"`
	PortMappings   map[int]PortMapping `yaml:"portMappings"`
	HealthChecks   HealthCheckConfig   `yaml:"healthChecks"`
	FlowControl    FlowControlConfig   `yaml:"flowControl"`
}

type CategorizedError added in v0.2.3

type CategorizedError struct {
	Err      error
	Category ErrorCategory
	Reason   string // Machine-readable reason code
}

type Client

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

Client manages the full lifecycle for one configured backend service.

func New

func New(cfg ClientBackendConfig, opts ...Option) (*Client, error)

New creates a new Client instance for a specific backend configuration.

func (*Client) Start

func (c *Client) Start(ctx context.Context)

Start initiates the client's connection loop.

func (*Client) Stats added in v0.2.3

func (c *Client) Stats() Stats

Stats returns a snapshot of current client statistics. This is a lightweight operation that reads atomic counters.

func (*Client) StatsDetailed added in v0.2.3

func (c *Client) StatsDetailed() Stats

StatsDetailed returns stats including per-connection details. This is a more expensive operation that iterates over all connections. Results are cached for 1 second to prevent excessive CPU usage.

func (*Client) Stop

func (c *Client) Stop()

Stop gracefully shuts down the client and its connections.

type ClientBackendConfig

type ClientBackendConfig struct {
	Name         string
	Hostnames    []string
	TCPPorts     []int
	UDPRoutes    []UDPRouteConfig
	NexusAddress string
	Weight       int
	Attestation  AttestationOptions
	PortMappings map[int]PortMapping
	HealthChecks HealthCheckConfig
	FlowControl  FlowControlConfig
}

type CommandTokenProvider added in v0.2.0

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

CommandTokenProvider implements TokenProvider by invoking an external command.

func NewCommandTokenProvider added in v0.2.0

func NewCommandTokenProvider(cfg AttestationOptions) (*CommandTokenProvider, error)

NewCommandTokenProvider returns a TokenProvider backed by an external command.

func (*CommandTokenProvider) IssueToken added in v0.2.0

func (c *CommandTokenProvider) IssueToken(ctx context.Context, req TokenRequest) (Token, error)

IssueToken invokes the configured command to retrieve an attestation token.

type Config

type Config struct {
	Backends []BackendConfig `yaml:"backends"`
}

func LoadConfig

func LoadConfig(path string) (*Config, error)

type ConnState added in v0.2.3

type ConnState uint32
const (
	ConnStatePending  ConnState = iota // Dial in progress
	ConnStateActive                    // Connected, relaying data
	ConnStateDraining                  // Graceful shutdown, no new data
	ConnStateClosed                    // Terminal state
)

type ConnectHandler

type ConnectHandler func(ctx context.Context, req ConnectRequest) (net.Conn, error)

ConnectHandler is invoked whenever the proxy asks us to establish a new local connection. Returning ErrNoRoute will defer to the default port-mapping behaviour. Any other error is treated as fatal for that request.

type ConnectRequest

type ConnectRequest struct {
	BackendName      string
	ClientID         uuid.UUID
	Hostname         string
	OriginalHostname string
	Port             int
	ClientIP         string
	IsTLS            bool
	Transport        Transport // "tcp" or "udp" (defaults to "tcp" if empty)
}

ConnectRequest provides context about a client connection request coming from the Nexus proxy.

type ConnectionStats added in v0.2.3

type ConnectionStats struct {
	ClientID     string
	Hostname     string
	State        ConnState
	BytesIn      int64
	BytesOut     int64
	BufferLevel  int
	Paused       bool
	ConnectedAt  time.Time
	LastActivity time.Time
	IsUDP        bool
}

ConnectionStats provides per-connection statistics.

type DisconnectReason added in v0.2.3

type DisconnectReason string

DisconnectReason provides machine-readable reason codes for disconnect messages.

const (
	DisconnectNormal        DisconnectReason = "normal"
	DisconnectBufferFull    DisconnectReason = "buffer_full"
	DisconnectDialFailed    DisconnectReason = "dial_failed"
	DisconnectTimeout       DisconnectReason = "timeout"
	DisconnectLocalError    DisconnectReason = "local_error"
	DisconnectShutdown      DisconnectReason = "shutdown"
	DisconnectSessionEnded  DisconnectReason = "session_ended"
	DisconnectPauseViolated DisconnectReason = "pause_violated"
	DisconnectUnknown       DisconnectReason = "unknown"
)

type ErrorCategory added in v0.2.3

type ErrorCategory int
const (
	ErrorTransient ErrorCategory = iota // Retry with backoff
	ErrorPermanent                      // Don't retry, surface to user
	ErrorRateLimit                      // Retry with longer backoff
)

type Event added in v0.2.3

type Event struct {
	Type      EventType
	Timestamp time.Time

	// Connection context (if applicable)
	ClientID string
	Hostname string

	// Error context (if applicable)
	Error  error
	Reason string
}

Event represents a client lifecycle event.

type EventHandler added in v0.2.3

type EventHandler func(Event)

EventHandler is a callback function for client events.

type EventType added in v0.2.3

type EventType int

EventType represents the type of client event.

const (
	EventConnected EventType = iota
	EventDisconnected
	EventConnectionOpened
	EventConnectionClosed
	EventPaused
	EventResumed
	EventError
	EventReauthStarted
	EventReauthCompleted
)

func (EventType) String added in v0.2.3

func (e EventType) String() string

type FlowControlConfig added in v0.2.3

type FlowControlConfig struct {
	// HighWaterMark is the buffer level at which we send pause_stream (default: 48)
	HighWaterMark int `yaml:"highWaterMark"`
	// LowWaterMark is the buffer level at which we send resume_stream (default: 16)
	LowWaterMark int `yaml:"lowWaterMark"`
	// MaxBuffer is the hard limit on buffered messages before closing connection (default: 64)
	MaxBuffer int `yaml:"maxBuffer"`
}

FlowControlConfig configures per-connection flow control parameters. These control when pause/resume messages are sent to Nexus.

type HMACTokenProvider added in v0.2.0

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

HMACTokenProvider produces tokens signed with a shared secret.

func NewHMACTokenProvider added in v0.2.0

func NewHMACTokenProvider(opts AttestationOptions, backendName string, hostnames []string, tcpPorts []int, udpRoutes []UDPRouteConfig, weight int) (*HMACTokenProvider, error)

NewHMACTokenProvider returns a TokenProvider that signs JWTs locally using HS256.

func (*HMACTokenProvider) IssueToken added in v0.2.0

func (h *HMACTokenProvider) IssueToken(ctx context.Context, req TokenRequest) (Token, error)

IssueToken signs a JWT that encodes the attestation claims expected by Nexus.

type HealthCheckConfig

type HealthCheckConfig struct {
	Enabled           bool `yaml:"enabled"`
	InactivityTimeout int  `yaml:"inactivityTimeout"`
	PongTimeout       int  `yaml:"pongTimeout"`
}

type Option

type Option func(*Client)

Option mutates a Client during construction.

func WithConnectHandler

func WithConnectHandler(handler ConnectHandler) Option

WithConnectHandler registers a custom connect handler. The handler is invoked before the default port-mapping logic. Returning ErrNoRoute (or a nil connection) will fall back to the default handler.

func WithEventHandler added in v0.2.3

func WithEventHandler(handler EventHandler) Option

WithEventHandler registers a callback for client lifecycle events. Events are delivered asynchronously in order via a dedicated goroutine. The handler should not block for extended periods as this can cause events to be dropped. Passing nil disables event delivery.

func WithTokenProvider added in v0.1.2

func WithTokenProvider(provider TokenProvider) Option

WithTokenProvider installs a TokenProvider that is consulted for handshake, attestation, and re-auth tokens. Passing nil restores the default provider.

type PortMapping

type PortMapping struct {
	Default string            `yaml:"default"`
	Hosts   map[string]string `yaml:"hosts"`
	// contains filtered or unexported fields
}

func (PortMapping) Resolve

func (pm PortMapping) Resolve(hostname string) (string, bool)

type Stats added in v0.2.3

type Stats struct {
	// Connection metrics
	ActiveConnections  int64
	TotalConnections   int64
	PendingConnections int64

	// Data transfer
	BytesSentTotal        int64
	BytesReceivedTotal    int64
	MessagesSentTotal     int64
	MessagesReceivedTotal int64

	// Queue metrics
	ControlQueueDepth int
	DataQueueDepth    int // Number of connections with pending data

	// Error metrics
	DroppedConnections int64
	TransientErrors    int64
	PermanentErrors    int64
	RateLimitHits      int64
	EnqueueTimeouts    int64

	// Flow control
	PausedConnections int64
	PauseViolations   int64

	// Event metrics
	DroppedEvents int64

	// UDP metrics
	UDPDroppedPackets int64

	// Session metrics
	SessionUptime   time.Duration
	LastUpdated     time.Time
	ReconnectCount  int64
	LastConnectedAt time.Time

	// Per-connection stats (optional, can be expensive)
	ConnectionStats map[string]ConnectionStats
}

Stats provides a snapshot of client statistics.

type Token added in v0.1.2

type Token struct {
	Value  string
	Expiry time.Time
}

Token encapsulates the token value and an optional expiry.

type TokenProvider added in v0.1.2

type TokenProvider interface {
	IssueToken(ctx context.Context, req TokenRequest) (Token, error)
}

TokenProvider issues attestation tokens for a given request.

type TokenRequest added in v0.2.0

type TokenRequest struct {
	Stage        TokenStage
	SessionNonce string
	BackendName  string
	Hostnames    []string
	TCPPorts     []int
	UDPRoutes    []UDPRouteConfig
	Weight       int
}

TokenRequest conveys the contextual information for issuing a token. Note: TCPPorts and UDPRoutes are used by CommandTokenProvider (passed as env vars) but HMACTokenProvider uses its own stored config values for these fields.

type TokenStage added in v0.2.0

type TokenStage string

TokenStage identifies which step of the attestation workflow is requesting a token.

const (
	StageHandshake TokenStage = "handshake"
	StageAttest    TokenStage = "attest"
	StageReauth    TokenStage = "reauth"
)

type Transport added in v0.2.2

type Transport string

Transport represents the network protocol for a connection. Valid values are "tcp" and "udp". The server sends this field in connect messages to indicate whether the client should dial a TCP or UDP connection to the local backend service.

const (
	TransportTCP Transport = "tcp"
	TransportUDP Transport = "udp"
)

type UDPRouteConfig added in v0.2.2

type UDPRouteConfig struct {
	Port                   int  `yaml:"port"`
	FlowIdleTimeoutSeconds *int `yaml:"flowIdleTimeoutSeconds,omitempty"`
}

UDPRouteConfig defines a UDP port claim with optional flow idle timeout. FlowIdleTimeoutSeconds specifies how long the server waits before cleaning up an idle UDP flow. If nil, the server uses its default timeout. If set to 0, behavior depends on server implementation (typically uses default or no timeout).

func CopyUDPRoutes added in v0.2.2

func CopyUDPRoutes(in []UDPRouteConfig) []UDPRouteConfig

CopyUDPRoutes creates a deep copy of UDPRouteConfig slice.

Jump to

Keyboard shortcuts

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