connection

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Connected indicates that the connection to the service is currently established.
	Connected = 1.0
	// Disconnected indicates that the connection to the service is currently not established.
	Disconnected = 0
)
View Source
const (
	UnmentionedTLSMode = ""
	NoneTLSMode        = "none"
	OneSideTLSMode     = "tls"
	MutualTLSMode      = "mtls"
	DefaultTLSMode     = NoneTLSMode

	// DefaultTLSMinVersion is the minimum version required to achieve secure connections.
	DefaultTLSMinVersion = tls.VersionTLS12
)

usage: TLS configuration modes.

Variables

This section is empty.

Functions

func AddressString

func AddressString[T WithAddress](addresses ...T) string

AddressString returns the addresses as a string with comma as a separator between them.

func CalcMaxAttempts added in v0.2.0

func CalcMaxAttempts(initialInterval, maxInterval, multiplier, maxElapsedTime float64) int

CalcMaxAttempts calculates the number of attempts given the following parameters: - initialInterval > 0 - maxInterval >= i - multiplier > 1 - maxElapsedTime > i.

func CloseConnections

func CloseConnections[T io.Closer](connections ...T) error

CloseConnections calls [closer.Close()] for all the given connections and return the close errors.

func CloseConnectionsLog

func CloseConnectionsLog[T io.Closer](connections ...T)

CloseConnectionsLog calls [closer.Close()] for all the given connections and log the close errors.

func DefaultHealthCheckService added in v0.1.5

func DefaultHealthCheckService() *health.Server

DefaultHealthCheckService returns a health-check service that returns SERVING for all services.

func FilterStreamRPCError

func FilterStreamRPCError(rpcErr error) error

FilterStreamRPCError filters RPC errors that caused due to ending stream.

func ListenRetryExecute added in v0.2.0

func ListenRetryExecute(ctx context.Context, f func() error) error

ListenRetryExecute executes the provided function with retry logic for port binding conflicts. It automatically retries when port conflicts are detected (e.g., "address already in use"), using exponential backoff. Non-port-conflict errors are treated as permanent failures and will not be retried. The retry behavior is controlled by the listenRetry profile.

func MakeGrpcRetryPolicyJSON added in v0.2.0

func MakeGrpcRetryPolicyJSON(p *retry.Profile) string

MakeGrpcRetryPolicyJSON defines the retry policy for a gRPC client connection. The retry policy applies to all subsequent gRPC calls made through the client connection. Our GRPC retry policy is applicable only for the following status codes:

(1) UNAVAILABLE	The service is currently unavailable (e.g., transient network issue, server down).
(2) DEADLINE_EXCEEDED	Operation took too long (deadline passed).
(3) RESOURCE_EXHAUSTED	Some resource (e.g., quota) has been exhausted; the operation cannot proceed.

func NewClientCredentialsFromMaterial added in v0.1.8

func NewClientCredentialsFromMaterial(c *TLSMaterials) (credentials.TransportCredentials, error)

NewClientCredentialsFromMaterial returns the gRPC transport credentials to be used by a client, based on the provided TLS configuration.

func NewConcurrencyLimit added in v0.2.0

func NewConcurrencyLimit(maxConcurrentStreams int) *semaphore.Weighted

NewConcurrencyLimit creates a weighted semaphore for limiting concurrent streams.

func NewConnection added in v0.1.7

func NewConnection(p ClientParameters) (*grpc.ClientConn, error)

NewConnection creates a connection with the given parameters. It will not attempt to create a connection with the remote.

func NewConnectionPerEndpoint added in v0.1.7

func NewConnectionPerEndpoint(config *MultiClientConfig) ([]*grpc.ClientConn, error)

NewConnectionPerEndpoint creates a list of connections; one for each endpoint in the given config.

func NewLoadBalancedConnection added in v0.1.7

func NewLoadBalancedConnection(config *MultiClientConfig) (*grpc.ClientConn, error)

NewLoadBalancedConnection creates a connection with load balancing between the endpoints in the given config.

func NewRateLimiter added in v0.1.8

func NewRateLimiter(config *RateLimitConfig) *rate.Limiter

NewRateLimiter creates a rate limiter based on the configuration.

func NewServerCredentialsFromMaterial added in v0.1.8

func NewServerCredentialsFromMaterial(c *TLSMaterials) (credentials.TransportCredentials, error)

NewServerCredentialsFromMaterial returns the gRPC transport credentials to be used by a client, based on the provided TLS configuration.

func NewSingleConnection added in v0.1.7

func NewSingleConnection(config *ClientConfig) (*grpc.ClientConn, error)

NewSingleConnection creates a single connection given a client config.

func RateLimitInterceptor added in v0.1.8

func RateLimitInterceptor(limiter *rate.Limiter) grpc.UnaryServerInterceptor

RateLimitInterceptor returns a UnaryServerInterceptor that implements rate limiting using a token bucket algorithm.

func RunHealthCheck added in v0.2.0

func RunHealthCheck(ctx context.Context, endpoint Endpoint, tlsConfig TLSConfig) error

RunHealthCheck dials the given endpoint and performs a gRPC health check. Returns nil if the service reports SERVING, otherwise returns an error.

func StreamConcurrencyInterceptor added in v0.2.0

func StreamConcurrencyInterceptor(sem *semaphore.Weighted) grpc.StreamServerInterceptor

StreamConcurrencyInterceptor returns a gRPC StreamServerInterceptor that limits the number of concurrently active streaming RPCs using a weighted semaphore.

Types

type ClientConfig

type ClientConfig struct {
	Endpoint *Endpoint      `mapstructure:"endpoint"  yaml:"endpoint"`
	TLS      TLSConfig      `mapstructure:"tls"       yaml:"tls"`
	Retry    *retry.Profile `mapstructure:"reconnect" yaml:"reconnect"`
}

ClientConfig contains a single endpoint, TLS config, and retry profile.

type ClientMaterial added in v0.2.0

type ClientMaterial struct {
	Endpoints []*Endpoint
	TLS       TLSMaterials
	Retry     *retry.Profile
}

ClientMaterial contains the parameters to create a connection.

func NewClientMaterial added in v0.2.0

func NewClientMaterial(config *MultiClientConfig) (*ClientMaterial, error)

NewClientMaterial creates a connection material from a client config.

func (*ClientMaterial) NewConnectionPerEndpoint added in v0.2.0

func (m *ClientMaterial) NewConnectionPerEndpoint() ([]*grpc.ClientConn, error)

NewConnectionPerEndpoint creates a list of connections; one for each endpoint.

func (*ClientMaterial) NewLoadBalancedConnection added in v0.2.0

func (m *ClientMaterial) NewLoadBalancedConnection() (*grpc.ClientConn, error)

NewLoadBalancedConnection creates a connection with load balancing between the endpoints.

type ClientParameters added in v0.1.9

type ClientParameters struct {
	Address        string
	Creds          credentials.TransportCredentials
	Retry          *retry.Profile
	AdditionalOpts []grpc.DialOption
}

ClientParameters contain connection parameters.

type Endpoint

type Endpoint struct {
	Host string `mapstructure:"host" json:"host,omitempty" yaml:"host,omitempty"`
	Port int    `mapstructure:"port" json:"port,omitempty" yaml:"port,omitempty"`
}

Endpoint describes a remote endpoint.

func (*Endpoint) Address

func (e *Endpoint) Address() string

Address returns a string representation of the endpoint's address.

func (*Endpoint) Empty

func (e *Endpoint) Empty() bool

Empty returns true if no host and no port are assigned.

func (*Endpoint) String

func (e *Endpoint) String() string

String returns a string representation of the endpoint.

type MultiClientConfig added in v0.1.7

type MultiClientConfig struct {
	Endpoints []*Endpoint    `mapstructure:"endpoints" yaml:"endpoints"`
	TLS       TLSConfig      `mapstructure:"tls"       yaml:"tls"`
	Retry     *retry.Profile `mapstructure:"reconnect" yaml:"reconnect"`
}

MultiClientConfig contains the endpoints, TLS config, and retry profile. This config allows the support of number of different endpoints to multiple service instances.

type RateLimitConfig added in v0.1.8

type RateLimitConfig struct {
	// RequestsPerSecond is the maximum number of requests per second allowed.
	// Set to 0 or negative to disable rate limiting.
	RequestsPerSecond int `mapstructure:"requests-per-second"`
	// Burst is the maximum number of requests allowed in a single burst.
	// This allows handling sudden spikes of concurrent requests from multiple clients.
	// Must be greater than 0 and less than or equal to RequestsPerSecond when rate limiting is enabled.
	Burst int `mapstructure:"burst"`
}

RateLimitConfig describes the rate limiting configuration for unary gRPC endpoints.

func (*RateLimitConfig) Validate added in v0.1.8

func (c *RateLimitConfig) Validate() error

Validate checks that the rate limit configuration is valid.

type ServerConfig

type ServerConfig struct {
	Endpoint             Endpoint               `mapstructure:"endpoint"`
	TLS                  TLSConfig              `mapstructure:"tls"`
	KeepAlive            *ServerKeepAliveConfig `mapstructure:"keep-alive"`
	RateLimit            RateLimitConfig        `mapstructure:"rate-limit"`
	MaxConcurrentStreams int                    `mapstructure:"max-concurrent-streams"`
	// contains filtered or unexported fields
}

ServerConfig describes the connection parameter for a server.

func (*ServerConfig) ClosePreAllocatedListener added in v0.2.0

func (c *ServerConfig) ClosePreAllocatedListener() error

ClosePreAllocatedListener closed the pre allocated listener if exists.

func (*ServerConfig) GrpcServer

func (c *ServerConfig) GrpcServer() (*grpc.Server, error)

GrpcServer instantiate a grpc.Server.

func (*ServerConfig) Listener

func (c *ServerConfig) Listener(ctx context.Context) (net.Listener, error)

Listener instantiate a net.Listener and updates the config port with the effective port. If the port is predefined, it will retry to bind to the port until successful or until the context ends.

func (*ServerConfig) PreAllocateListener

func (c *ServerConfig) PreAllocateListener(ctx context.Context) (net.Listener, error)

PreAllocateListener is used to allocate a port and bind to ahead of the server initialization. It stores the listener object internally to be reused on subsequent calls to Listener().

type ServerKeepAliveConfig

type ServerKeepAliveConfig struct {
	Params            *ServerKeepAliveParamsConfig            `mapstructure:"params"`
	EnforcementPolicy *ServerKeepAliveEnforcementPolicyConfig `mapstructure:"enforcement-policy"`
}

ServerKeepAliveConfig describes the keep alive parameters.

type ServerKeepAliveEnforcementPolicyConfig

type ServerKeepAliveEnforcementPolicyConfig struct {
	MinTime             time.Duration `mapstructure:"min-time"`
	PermitWithoutStream bool          `mapstructure:"permit-without-stream"`
}

ServerKeepAliveEnforcementPolicyConfig describes the keep alive enforcement policy.

type ServerKeepAliveParamsConfig

type ServerKeepAliveParamsConfig struct {
	MaxConnectionIdle     time.Duration `mapstructure:"max-connection-idle"`
	MaxConnectionAge      time.Duration `mapstructure:"max-connection-age"`
	MaxConnectionAgeGrace time.Duration `mapstructure:"max-connection-age-grace"`
	Time                  time.Duration `mapstructure:"time"`
	Timeout               time.Duration `mapstructure:"timeout"`
}

ServerKeepAliveParamsConfig describes the keep alive policy.

type TLSConfig added in v0.1.7

type TLSConfig struct {
	Mode string `mapstructure:"mode"`
	// CertPath is the path to the certificate file (public key).
	CertPath string `mapstructure:"cert-path"`
	// KeyPath is the path to the key file (private key).
	KeyPath     string   `mapstructure:"key-path"`
	CACertPaths []string `mapstructure:"ca-cert-paths"`
}

TLSConfig holds the TLS options and certificate paths used for secure communication between servers and clients. Credentials are built based on the configuration mode. For example, If only server-side TLS is required, the certificate pool (certPool) is not built (for a server), since the relevant certificates paths are defined in the YAML according to the selected mode.

func (TLSConfig) ClientCredentials added in v0.1.7

func (c TLSConfig) ClientCredentials() (credentials.TransportCredentials, error)

ClientCredentials converts TLSConfig into a TLSMaterials struct and generates client creds.

func (TLSConfig) ServerCredentials added in v0.1.7

func (c TLSConfig) ServerCredentials() (credentials.TransportCredentials, error)

ServerCredentials converts TLSConfig into a TLSMaterials struct and generates server creds.

type TLSMaterials added in v0.1.8

type TLSMaterials struct {
	Mode    string
	Cert    []byte
	Key     []byte
	CACerts [][]byte
}

TLSMaterials holds the loaded runtime TLS material (certificate, key, CA certs).

func NewClientTLSMaterials added in v0.2.0

func NewClientTLSMaterials(c TLSConfig) (*TLSMaterials, error)

NewClientTLSMaterials converts a client TLSConfig with path fields into a struct that holds the actual bytes of the certificates.

Certificate loading behavior by mode:

  • none/unmentioned: No certificates loaded
  • tls (one-way): Loads CA certs only for server verification (client cert + key NOT loaded)
  • mtls (mutual): Loads CA certs + client cert + key for mutual authentication

func NewServerTLSMaterials added in v0.2.0

func NewServerTLSMaterials(c TLSConfig) (*TLSMaterials, error)

NewServerTLSMaterials converts a server TLSConfig with path fields into a struct that holds the actual bytes of the certificates.

Certificate loading behavior by mode:

  • none/unmentioned: No certificates loaded
  • tls (one-way): Loads server cert + key only (CA certs NOT loaded)
  • mtls (mutual): Loads server cert + key + CA certs for client verification

func (*TLSMaterials) CreateClientTLSConfig added in v0.1.8

func (c *TLSMaterials) CreateClientTLSConfig() (*tls.Config, error)

CreateClientTLSConfig returns a TLS config to be used by a server.

func (*TLSMaterials) CreateServerTLSConfig added in v0.1.8

func (c *TLSMaterials) CreateServerTLSConfig() (*tls.Config, error)

CreateServerTLSConfig returns a TLS config to be used by a server.

type WithAddress

type WithAddress interface {
	Address() string
}

WithAddress represents any type that can generate an address.

Jump to

Keyboard shortcuts

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