client

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InitialBackoff = 5 * time.Second
	MaxBackoff     = 60 * time.Second
	BackoffFactor  = 2
)

Default backoff configuration

Variables

This section is empty.

Functions

func CalculateBackoff

func CalculateBackoff(attempt int) time.Duration

CalculateBackoff calculates the backoff duration for a given attempt number. The backoff follows: 5s, 10s, 20s, 40s, 60s (max)

Types

type Client

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

Client represents the QMux client

func New

func New(conf *config.Client) (*Client, error)

New creates a new client

func (*Client) ConnectionManager

func (c *Client) ConnectionManager() *ConnectionManager

ConnectionManager returns the underlying connection manager. This is useful for advanced use cases and testing.

func (*Client) HealthyConnectionCount

func (c *Client) HealthyConnectionCount() int

HealthyConnectionCount returns the number of healthy server connections.

func (*Client) Start

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

Start starts the client

func (*Client) Stop

func (c *Client) Stop() error

Stop stops the client

func (*Client) TotalConnectionCount

func (c *Client) TotalConnectionCount() int

TotalConnectionCount returns the total number of server connections.

type ConnectionManager

type ConnectionManager struct {

	// NewConns delivers newly established ServerConnections (initial + reconnected)
	// to the Client layer for stream acceptance and UDP handler setup.
	NewConns chan *ServerConnection
	// contains filtered or unexported fields
}

ConnectionManager manages connections to multiple servers. It orchestrates ServerConnection instances and handles lifecycle management.

func NewConnectionManager

func NewConnectionManager(cfg *config.Client, logger zerolog.Logger) (*ConnectionManager, error)

NewConnectionManager creates a new ConnectionManager instance.

func (*ConnectionManager) GetAllConnections

func (cm *ConnectionManager) GetAllConnections() []*ServerConnection

GetAllConnections returns all server connections.

func (*ConnectionManager) GetConnection

func (cm *ConnectionManager) GetConnection(serverAddr string) *ServerConnection

GetConnection returns the connection for a specific server address.

func (*ConnectionManager) HealthyCount

func (cm *ConnectionManager) HealthyCount() int

HealthyCount returns the number of healthy connections.

func (*ConnectionManager) SessionCacheManager

func (cm *ConnectionManager) SessionCacheManager() *SessionCacheManager

SessionCacheManager returns the session cache manager. This is useful for testing session cache persistence.

func (*ConnectionManager) Start

func (cm *ConnectionManager) Start(ctx context.Context) error

Start initiates connections to all configured servers concurrently. It uses goroutines for each server and waits for all connection attempts. Partial failures are handled - the manager continues with successful connections.

func (*ConnectionManager) Stop

func (cm *ConnectionManager) Stop() error

Stop gracefully shuts down all connections. It cancels the context to stop heartbeat and reconnection goroutines, then closes all server connections. Active streams can complete naturally.

func (*ConnectionManager) TotalCount

func (cm *ConnectionManager) TotalCount() int

TotalCount returns the total number of connections.

type ConnectionState

type ConnectionState int

ConnectionState represents the state of a server connection

const (
	StateDisconnected ConnectionState = iota
	StateConnecting
	StateConnected
	StateUnhealthy
)

func (ConnectionState) String

func (s ConnectionState) String() string

String returns a string representation of the connection state

type NonHeartbeatHandler added in v1.1.0

type NonHeartbeatHandler func(msgType byte, payload []byte) error

NonHeartbeatHandler is a function type for handling non-heartbeat messages received on the control stream. It receives the message type and payload, and returns an error if handling fails.

type ReconnectionCallback added in v1.1.0

type ReconnectionCallback func(serverAddr string)

ReconnectionCallback is a function type for signaling that reconnection is needed. It receives the server address that needs reconnection.

type ServerConnection

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

ServerConnection represents a connection to a single server instance. Each ServerConnection maintains its own TLS session cache to ensure session tickets are isolated between different servers.

func NewServerConnection

func NewServerConnection(serverAddr, serverName string, sessionCache tls.ClientSessionCache, logger zerolog.Logger) *ServerConnection

NewServerConnection creates a new ServerConnection instance. The sessionCache should be obtained from SessionCacheManager to ensure proper isolation between different servers.

func (*ServerConnection) AcceptStream

func (sc *ServerConnection) AcceptStream(ctx context.Context) (*quic.Stream, error)

AcceptStream accepts an incoming stream from this server. This blocks until a stream is available or the context is cancelled.

func (*ServerConnection) CheckHealth

func (sc *ServerConnection) CheckHealth(timeout time.Duration) bool

CheckHealth checks if the connection is healthy based on the heartbeat timeout. If the time since the last heartbeat exceeds the timeout, the connection is marked unhealthy.

func (*ServerConnection) CheckReceivedHealth added in v1.1.0

func (sc *ServerConnection) CheckReceivedHealth() bool

CheckReceivedHealth checks if the connection is healthy based on received heartbeats. Returns true if a heartbeat has been received within the configured healthTimeout. Returns false if no heartbeat has been received or if the timeout has been exceeded.

func (*ServerConnection) Close

func (sc *ServerConnection) Close() error

Close gracefully closes the connection. Active streams can continue until they complete or fail naturally.

func (*ServerConnection) Connect

func (sc *ServerConnection) Connect(ctx context.Context, baseTLSConfig *tls.Config, quicConfig *quic.Config) error

Connect establishes the QUIC connection using the isolated session cache. The baseTLSConfig should contain certificates and CA pool, but the session cache will be overridden with this connection's isolated cache.

func (*ServerConnection) Connection

func (sc *ServerConnection) Connection() *quic.Conn

Connection returns the underlying QUIC connection. Returns nil if not connected.

func (*ServerConnection) Info

Info returns current connection status information.

func (*ServerConnection) IsHealthy

func (sc *ServerConnection) IsHealthy() bool

IsHealthy returns the current health status of the connection. A connection is healthy if it has successfully sent heartbeats within the configured timeout.

func (*ServerConnection) LastHeartbeat

func (sc *ServerConnection) LastHeartbeat() time.Time

LastHeartbeat returns the timestamp of the last successful heartbeat. Returns zero time if no heartbeat has been sent.

func (*ServerConnection) LastReceivedFromServer added in v1.1.0

func (sc *ServerConnection) LastReceivedFromServer() time.Time

LastReceivedFromServer returns the timestamp of when the last heartbeat was received from the server. Returns zero time if no heartbeat has been received yet.

func (*ServerConnection) MarkHealthy

func (sc *ServerConnection) MarkHealthy()

MarkHealthy marks the connection as healthy and updates the last heartbeat timestamp.

func (*ServerConnection) MarkUnhealthy

func (sc *ServerConnection) MarkUnhealthy()

MarkUnhealthy marks the connection as unhealthy.

func (*ServerConnection) Register

func (sc *ServerConnection) Register(clientID string) error

Register sends a registration message to the server and waits for acknowledgment. This should be called after Connect() succeeds.

func (*ServerConnection) SendHeartbeat

func (sc *ServerConnection) SendHeartbeat() error

SendHeartbeat sends a heartbeat message on the control stream. This is a non-blocking operation that does not wait for any response. On success, the connection is marked healthy. On failure, it's marked unhealthy and reconnection is triggered if a callback is set.

func (*ServerConnection) ServerAddr

func (sc *ServerConnection) ServerAddr() string

ServerAddr returns the server address this connection is for.

func (*ServerConnection) ServerName

func (sc *ServerConnection) ServerName() string

ServerName returns the TLS server name for this connection.

func (*ServerConnection) SetHealthConfig added in v1.1.0

func (sc *ServerConnection) SetHealthConfig(healthTimeout time.Duration)

SetHealthConfig configures the health check parameters for the connection. healthTimeout is the maximum duration allowed between received heartbeats before marking unhealthy.

func (*ServerConnection) SetNonHeartbeatHandler added in v1.1.0

func (sc *ServerConnection) SetNonHeartbeatHandler(handler NonHeartbeatHandler)

SetNonHeartbeatHandler sets the handler for non-heartbeat messages received on the control stream. This allows routing of non-heartbeat messages to appropriate handlers without blocking heartbeat processing.

func (*ServerConnection) SetReconnectCallback added in v1.1.0

func (sc *ServerConnection) SetReconnectCallback(callback ReconnectionCallback)

SetReconnectCallback sets the callback function to be called when reconnection is needed. This is called when the health check detects a timeout.

func (*ServerConnection) StartHeartbeatLoops added in v1.1.0

func (sc *ServerConnection) StartHeartbeatLoops(heartbeatInterval time.Duration)

StartHeartbeatLoops starts the unified heartbeat loop for this connection. The loop handles sending heartbeats, receiving heartbeats, and health checking all in a single goroutine (similar to server-side implementation).

All operations use the same connection context for coordinated shutdown.

func (*ServerConnection) State

func (sc *ServerConnection) State() ConnectionState

State returns the current connection state.

func (*ServerConnection) UpdateLastReceivedFromServer added in v1.1.0

func (sc *ServerConnection) UpdateLastReceivedFromServer()

UpdateLastReceivedFromServer updates the timestamp of when a heartbeat was received from the server. This method is thread-safe using atomic operations.

type ServerConnectionInfo

type ServerConnectionInfo struct {
	Address                string
	ServerName             string
	State                  ConnectionState
	Healthy                bool
	LastHeartbeat          time.Time
	LastReceivedFromServer time.Time
	ConnectedAt            time.Time
}

ServerConnectionInfo provides connection status information for monitoring.

type SessionCacheManager

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

SessionCacheManager manages TLS session caches per server address. Each server gets its own isolated session cache to ensure session tickets encrypted by one server's STEK are not incorrectly used with another server.

func NewSessionCacheManager

func NewSessionCacheManager() *SessionCacheManager

NewSessionCacheManager creates a new SessionCacheManager instance.

func (*SessionCacheManager) Addresses

func (m *SessionCacheManager) Addresses() []string

Addresses returns all server addresses that have session caches. This is primarily useful for testing and debugging.

func (*SessionCacheManager) Clear

func (m *SessionCacheManager) Clear(serverAddr string)

Clear removes the session cache for a server. This should be used when a server's session cache needs to be invalidated, such as when session cache corruption is detected.

func (*SessionCacheManager) Count

func (m *SessionCacheManager) Count() int

Count returns the number of session caches currently managed. This is primarily useful for testing.

func (*SessionCacheManager) Get

func (m *SessionCacheManager) Get(serverAddr string) tls.ClientSessionCache

Get returns the session cache for a server, or nil if not exists. This is useful for checking if a cache exists without creating one.

func (*SessionCacheManager) GetOrCreate

func (m *SessionCacheManager) GetOrCreate(serverAddr string) tls.ClientSessionCache

GetOrCreate returns the session cache for a server, creating one if needed. The cache is keyed by the server's address (host:port combination). Calling this method multiple times with the same address returns the same cache instance.

type UDPHandler added in v1.0.5

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

UDPHandler handles UDP datagram forwarding on the client side

func NewUDPHandler added in v1.0.5

func NewUDPHandler(localHost string, localPort int, enableFragmentation bool, logger zerolog.Logger) *UDPHandler

NewUDPHandler creates a new UDP handler

func (*UDPHandler) Start added in v1.0.5

func (h *UDPHandler) Start(ctx context.Context, quicConn quic.Conn)

Start starts the UDP handler for a QUIC connection

func (*UDPHandler) Stop added in v1.0.5

func (h *UDPHandler) Stop()

Stop stops the UDP handler

type UDPSession added in v1.0.5

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

UDPSession represents a client-side UDP session

Jump to

Keyboard shortcuts

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