Documentation
¶
Overview ¶
Package grpchelper implements helpers to access gRPC services.
Index ¶
- Constants
- Variables
- func Conn(addr string, healthCheckTimeout time.Duration, opts ...grpc.DialOption) (*grpc.ClientConn, error)
- func ConnWithAuth(addr string, healthCheckTimeout time.Duration, username, password string, ...) (*grpc.ClientConn, error)
- func IsFailoverError(err error) bool
- func IsInternalError(err error) bool
- func IsTransientError(err error) bool
- func JitteredBackoff(baseBackoff, maxBackoff time.Duration, attempt int, jitterFactor float64) time.Duration
- func Request(ctx context.Context, rpcTimeout time.Duration, ...) error
- func SecureOptions(dest []grpc.DialOption, enabled, insecure bool, cert string) ([]grpc.DialOption, error)
- type CircuitState
- type Client
- type ConnManager
- func (m *ConnManager[C]) ActiveCount() int
- func (m *ConnManager[C]) ActiveNames() []string
- func (m *ConnManager[C]) ActiveRegisteredNodes() []*databasev1.Node
- func (m *ConnManager[C]) EvictableCount() int
- func (m *ConnManager[C]) Execute(node string, fn func(C) error) error
- func (m *ConnManager[C]) FailoverNode(node string)
- func (m *ConnManager[C]) GetClient(name string) (C, bool)
- func (m *ConnManager[C]) GetRouteTable() *databasev1.RouteTable
- func (m *ConnManager[C]) GracefulStop()
- func (m *ConnManager[C]) IsRequestAllowed(node string) bool
- func (m *ConnManager[C]) OnAddOrUpdate(node *databasev1.Node)
- func (m *ConnManager[C]) OnDelete(node *databasev1.Node)
- func (m *ConnManager[C]) ReconnectAll()
- func (m *ConnManager[C]) RecordFailure(node string, err error)
- func (m *ConnManager[C]) RecordSuccess(node string)
- type ConnManagerConfig
- type ConnectionHandler
Constants ¶
const DefaultJitterFactor = 0.2
DefaultJitterFactor is the default jitter factor for backoff calculations.
Variables ¶
var ( // ErrCircuitBreakerOpen is returned when the circuit breaker is open for a node. ErrCircuitBreakerOpen = errors.New("circuit breaker open") // ErrClientNotFound is returned when no active client exists for a node. ErrClientNotFound = errors.New("client not found") )
var ( // InitBackoff is the initial backoff duration for health check retries. InitBackoff = time.Second // MaxBackoff is the maximum backoff duration for health check retries. MaxBackoff = 20 * time.Second )
Functions ¶
func Conn ¶
func Conn(addr string, healthCheckTimeout time.Duration, opts ...grpc.DialOption) (*grpc.ClientConn, error)
Conn returns a gRPC client connection once connecting the server.
func ConnWithAuth ¶ added in v0.9.0
func ConnWithAuth(addr string, healthCheckTimeout time.Duration, username, password string, opts ...grpc.DialOption) (*grpc.ClientConn, error)
ConnWithAuth returns a gRPC client connection once connecting the server with Auth.
func IsFailoverError ¶ added in v0.10.0
IsFailoverError checks if the error indicates the node should be failed over.
func IsInternalError ¶ added in v0.10.0
IsInternalError checks if the error is an internal server error.
func IsTransientError ¶ added in v0.10.0
IsTransientError checks if the error is considered transient and retryable.
func JitteredBackoff ¶ added in v0.10.0
func JitteredBackoff(baseBackoff, maxBackoff time.Duration, attempt int, jitterFactor float64) time.Duration
JitteredBackoff calculates backoff duration with jitter to avoid thundering herds. Uses bounded symmetric jitter: backoff * (1 + jitter * (rand() - 0.5) * 2).
func Request ¶
func Request(ctx context.Context, rpcTimeout time.Duration, fn func(rpcCtx context.Context) error) error
Request execute a input closure to send traffics. It provides common features like timeout, error handling, and etc.
func SecureOptions ¶ added in v0.8.0
func SecureOptions(dest []grpc.DialOption, enabled, insecure bool, cert string) ([]grpc.DialOption, error)
SecureOptions returns gRPC dial options with secure connection settings.
Types ¶
type CircuitState ¶ added in v0.10.0
type CircuitState int
CircuitState defines the circuit breaker states.
const ( StateClosed CircuitState = iota // Normal operation StateOpen // Reject requests until cooldown expires StateHalfOpen // Allow a single probe )
CircuitState defines the circuit breaker states.
type Client ¶ added in v0.10.0
type Client interface {
Close() error
}
Client is the minimal interface for a managed gRPC client.
type ConnManager ¶ added in v0.10.0
type ConnManager[C Client] struct { // contains filtered or unexported fields }
ConnManager manages gRPC connections with health checking, circuit breaking, and eviction.
func NewConnManager ¶ added in v0.10.0
func NewConnManager[C Client](cfg ConnManagerConfig[C]) *ConnManager[C]
NewConnManager creates a new ConnManager.
func (*ConnManager[C]) ActiveCount ¶ added in v0.10.0
func (m *ConnManager[C]) ActiveCount() int
ActiveCount returns the number of active nodes.
func (*ConnManager[C]) ActiveNames ¶ added in v0.10.0
func (m *ConnManager[C]) ActiveNames() []string
ActiveNames returns the names of all active nodes.
func (*ConnManager[C]) ActiveRegisteredNodes ¶ added in v0.10.0
func (m *ConnManager[C]) ActiveRegisteredNodes() []*databasev1.Node
ActiveRegisteredNodes returns the registered node info for all active nodes.
func (*ConnManager[C]) EvictableCount ¶ added in v0.10.0
func (m *ConnManager[C]) EvictableCount() int
EvictableCount returns the number of evictable nodes.
func (*ConnManager[C]) Execute ¶ added in v0.10.0
func (m *ConnManager[C]) Execute(node string, fn func(C) error) error
Execute checks the circuit breaker, gets the client, calls fn, and records success or failure.
func (*ConnManager[C]) FailoverNode ¶ added in v0.10.0
func (m *ConnManager[C]) FailoverNode(node string)
FailoverNode checks health for a node and moves it to evictable if unhealthy.
func (*ConnManager[C]) GetClient ¶ added in v0.10.0
func (m *ConnManager[C]) GetClient(name string) (C, bool)
GetClient returns the client for the given node name.
func (*ConnManager[C]) GetRouteTable ¶ added in v0.10.0
func (m *ConnManager[C]) GetRouteTable() *databasev1.RouteTable
GetRouteTable returns a snapshot of registered, active, and evictable node info.
func (*ConnManager[C]) GracefulStop ¶ added in v0.10.0
func (m *ConnManager[C]) GracefulStop()
GracefulStop closes all connections and stops background goroutines.
func (*ConnManager[C]) IsRequestAllowed ¶ added in v0.10.0
func (m *ConnManager[C]) IsRequestAllowed(node string) bool
IsRequestAllowed checks if a request to the given node is allowed based on circuit breaker state. It also handles state transitions from Open to Half-Open when cooldown expires.
func (*ConnManager[C]) OnAddOrUpdate ¶ added in v0.10.0
func (m *ConnManager[C]) OnAddOrUpdate(node *databasev1.Node)
OnAddOrUpdate registers or updates a node and manages its connection.
func (*ConnManager[C]) OnDelete ¶ added in v0.10.0
func (m *ConnManager[C]) OnDelete(node *databasev1.Node)
OnDelete removes a node and its connection.
func (*ConnManager[C]) ReconnectAll ¶ added in v0.10.0
func (m *ConnManager[C]) ReconnectAll()
ReconnectAll closes all active and evictable connections and re-registers all nodes.
func (*ConnManager[C]) RecordFailure ¶ added in v0.10.0
func (m *ConnManager[C]) RecordFailure(node string, err error)
RecordFailure updates the circuit breaker state on failed operation. Only records failures for transient/internal errors that should count toward opening the circuit.
func (*ConnManager[C]) RecordSuccess ¶ added in v0.10.0
func (m *ConnManager[C]) RecordSuccess(node string)
RecordSuccess resets the circuit breaker state to Closed on successful operation. This handles Half-Open -> Closed transitions.
type ConnManagerConfig ¶ added in v0.10.0
type ConnManagerConfig[C Client] struct { Handler ConnectionHandler[C] Logger *logger.Logger RetryPolicy string ExtraDialOpts []grpc.DialOption MaxRecvMsgSize int HealthCheckTimeout time.Duration }
ConnManagerConfig holds configuration for ConnManager.
type ConnectionHandler ¶ added in v0.10.0
type ConnectionHandler[C Client] interface { // AddressOf extracts the gRPC address from a node. AddressOf(node *databasev1.Node) string // GetDialOptions returns gRPC dial options for the given address. GetDialOptions() ([]grpc.DialOption, error) // NewClient creates a client from a gRPC connection and node. NewClient(conn *grpc.ClientConn, node *databasev1.Node) (C, error) // OnActive is called when a node transitions to active. OnActive(name string, client C) // OnInactive is called when a node leaves active. OnInactive(name string, client C) }
ConnectionHandler provides upper-layer callbacks for connection lifecycle.