clients

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 7 Imported by: 1

README

Clients

The clients package provides utility features for building robust and resilient client implementations in Go. This package includes support for retry handling and circuit breaker patterns, which are essential for creating fault-tolerant applications.

Index

Installation

To install the package, use the following command:

go get github.com/nandlabs/golly/clients

Features

RetryHandler

The RetryHandler feature allows you to configure retry logic for your client operations. This is useful for handling transient errors and ensuring that your client can recover from temporary failures.

Usage

To use the RetryHandler, you need to define the retry configuration using the RetryInfo struct.

package main

import (
    "fmt"
    "time"
    "github.com/nandlabs/golly/clients"
)

func main() {
    retryInfo := clients.RetryInfo{
        MaxRetries: 3,
        Wait:       1000, // Wait time in milliseconds
    }

    for i := 0; i < retryInfo.MaxRetries; i++ {
        err := performOperation()
        if err == nil {
            fmt.Println("Operation succeeded")
            break
        }
        fmt.Printf("Operation failed: %v. Retrying...\n", err)
        time.Sleep(time.Duration(retryInfo.Wait) * time.Millisecond)
    }
}

func performOperation() error {
    // Simulate an operation that may fail
    return fmt.Errorf("simulated error")
}
CircuitBreaker

The CircuitBreaker feature helps you to prevent cascading failures and improve the resilience of your client by stopping requests to a failing service. It transitions between different states (closed, open, half-open) based on the success or failure of requests.

Usage

To use the CircuitBreaker, you need to create an instance of the CircuitBreaker struct with the desired configuration.

package main

import (
    "fmt"
    "github.com/nandlabs/golly/clients"
)

func main() {
    breakerInfo := &clients.BreakerInfo{
        FailureThreshold: 3,
        SuccessThreshold: 3,
        MaxHalfOpen:      5,
        Timeout:          300, // Timeout in seconds
    }

    cb := clients.NewCB(breakerInfo)

    for i := 0; i < 10; i++ {
        err := cb.CanExecute()
        if err != nil {
            fmt.Println("Circuit breaker is open. Cannot execute operation.")
            continue
        }

        err = performOperation()
        cb.OnExecution(err == nil)
        if err != nil {
            fmt.Printf("Operation failed: %v\n", err)
        } else {
            fmt.Println("Operation succeeded")
        }
    }
}

func performOperation() error {
    // Simulate an operation that may fail
    return fmt.Errorf("simulated error")
}
CircuitBreaker States
  • circuitClosed: The circuit is closed, and requests can flow through.
  • circuitHalfOpen: The circuit is partially open and allows limited requests for testing.
  • circuitOpen: The circuit is open, and requests are blocked.
Configuration Parameters
  • FailureThreshold: Number of consecutive failures required to open the circuit.
  • SuccessThreshold: Number of consecutive successes required to close the circuit.
  • MaxHalfOpen: Maximum number of requests allowed in the half-open state.
  • Timeout: Timeout duration for the circuit to transition from open to half-open state.

Documentation

Overview

Package clients provides a collection of client libraries for various services. It offers a set of reusable and easy-to-use client implementations that can be used to interact with different services. These client libraries are designed to simplify the process of making requests, handling responses, and managing authentication for the respective services. The package includes clients for services such as HTTP, database, messaging, storage, and more. Each client library is organized into its own subpackage, making it easy to import and use only the necessary clients. Additionally, the package provides a consistent and unified interface for all the client libraries, allowing developers to switch between different services seamlessly. By using the clients package, developers can save time and effort by leveraging pre-built client implementations and focusing on the core logic of their applications. For more information and usage examples, refer to the documentation of each individual client library. These clients can be used to interact with the corresponding services and perform operations such as making API calls, retrieving data, and more.

Index

Constants

This section is empty.

Variables

View Source
var ErrCBOpen = errors.New("the Circuit breaker is open and unable to process request")

ErrCBOpen is the error returned when the circuit breaker is open and unable to process requests.

Functions

This section is empty.

Types

type APIKeyAuth added in v1.3.0

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

APIKeyAuth represents API key authentication where the key is sent as a custom header (e.g., X-API-Key, api-key). This is commonly used by OpenAI-compatible providers like Azure OpenAI.

func (*APIKeyAuth) HeaderName added in v1.3.0

func (a *APIKeyAuth) HeaderName() string

HeaderName returns the HTTP header name used to send the API key.

func (*APIKeyAuth) Pass added in v1.3.0

func (a *APIKeyAuth) Pass() (string, error)

Pass returns an empty string. APIKeyAuth does not use password credentials.

func (*APIKeyAuth) Token added in v1.3.0

func (a *APIKeyAuth) Token() (string, error)

Token returns the API key value.

func (*APIKeyAuth) Type added in v1.3.0

func (a *APIKeyAuth) Type() AuthType

Type returns the authentication type for APIKeyAuth, which is AuthTypeAPIKey.

func (*APIKeyAuth) User added in v1.3.0

func (a *APIKeyAuth) User() (string, error)

User returns an empty string. APIKeyAuth does not use username credentials.

type AuthProvider added in v1.2.6

type AuthProvider interface {
	Type() AuthType
	User() (string, error)
	Pass() (string, error)
	Token() (string, error)
}

AuthProvider defines an interface for authentication mechanisms. It provides methods to retrieve the type of authentication, user credentials, and token. All credential-fetching methods return errors to support implementations backed by external stores (e.g., Vault, AWS Secrets Manager).

Methods:

  • Type() AuthType: Returns the type of authentication.
  • User() (string, error): Returns the username or an error if retrieval fails.
  • Pass() (string, error): Returns the password or an error if retrieval fails.
  • Token() (string, error): Returns the authentication token or an error if token acquisition fails.

func NewAPIKeyAuth added in v1.3.0

func NewAPIKeyAuth(headerName, apiKey string) AuthProvider

NewAPIKeyAuth creates a new APIKeyAuth instance. Parameters:

headerName (string): The HTTP header name (e.g., "X-API-Key", "api-key").
apiKey (string): The API key value.

Returns:

AuthProvider: The APIKeyAuth instance.

func NewBasicAuth added in v1.2.6

func NewBasicAuth(user, pass string) AuthProvider

NewBasicAuth creates a new BasicAuth instance with the provided username and password. Parameters:

user (string): The username.
pass (string): The password.

Returns:

*BasicAuth: The BasicAuth instance.

func NewBearerAuth added in v1.2.6

func NewBearerAuth(token string) AuthProvider

NewBearerAuth creates a new BearerAuth instance with the provided token. Parameters:

token (string): The token.

Returns:

*BearerAuth: The BearerAuth instance.

type AuthType added in v1.2.6

type AuthType string
const (
	AuthTypeBasic  AuthType = "Basic"
	AuthTypeBearer AuthType = "Token"
	AuthTypeAPIKey AuthType = "APIKey"
)

type Authenticatable added in v1.2.6

type Authenticatable interface {
	Apply(AuthProvider)
}

Authenticatable represents an interface that requires the implementation of the Apply method. The Apply method takes an Authenticator as a parameter and applies it to the implementing type.

type BasicAuth added in v1.2.6

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

BasicAuth represents basic authentication credentials with a username and password.

func (*BasicAuth) Pass added in v1.2.6

func (b *BasicAuth) Pass() (string, error)

Pass returns the password associated with the BasicAuth instance. Returns:

string: The password.
error: Always nil for in-memory credentials.

func (*BasicAuth) Refresh added in v1.2.6

func (b *BasicAuth) Refresh() error

Refresh refreshes the authentication credentials. It currently does not perform any operations and always returns nil.

Returns:

error: Always returns nil.

func (*BasicAuth) Token added in v1.2.6

func (b *BasicAuth) Token() (string, error)

Token returns an empty string as the token. BasicAuth does not use tokens. Returns:

string: An empty string.
error: Always nil.

func (*BasicAuth) Type added in v1.2.6

func (b *BasicAuth) Type() AuthType

Type returns the authentication type for BasicAuth, which is AuthTypeBasic. This is used to determine the type of authentication to be used. Returns:

AuthType: The authentication type. (AuthTypeBasic)

func (*BasicAuth) User added in v1.2.6

func (b *BasicAuth) User() (string, error)

User returns the username associated with the BasicAuth instance. Returns:

string: The username.
error: Always nil for in-memory credentials.

type BreakerInfo

type BreakerInfo struct {
	FailureThreshold uint64 // Number of consecutive failures required to open the circuit
	SuccessThreshold uint64 // Number of consecutive successes required to close the circuit
	MaxHalfOpen      uint32 // Maximum number of requests allowed in the half-open state
	Timeout          uint32 // Timeout duration for the circuit to transition from open to half-open state
}

BreakerInfo holds the configuration parameters for the CircuitBreaker.

type CircuitBreaker

type CircuitBreaker struct {
	*BreakerInfo
	// contains filtered or unexported fields
}

CircuitBreaker is a struct that represents a circuit breaker.

func NewCircuitBreaker added in v1.2.6

func NewCircuitBreaker(info *BreakerInfo) (cb *CircuitBreaker)

NewCircuitBreaker creates a new CircuitBreaker instance with the provided BreakerInfo. If no BreakerInfo is provided, default values will be used.

func (*CircuitBreaker) CanExecute

func (cb *CircuitBreaker) CanExecute() (err error)

CanExecute checks if a request can be executed based on the current state of the circuit breaker. It returns an error if the circuit is open or if the maximum number of requests in the half-open state is reached.

func (*CircuitBreaker) OnExecution

func (cb *CircuitBreaker) OnExecution(success bool)

OnExecution is called after a request is executed. It updates the success or failure counters based on the result of the request. It also checks if the circuit needs to transition to a different state based on the counters and thresholds.

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker to its initial state.

type Client added in v1.2.6

type Client[RQ any, RS any] interface {
	SetOptions(options *ClientOptions)
	Execute(req RQ) (RS, error)
}

type ClientOptions added in v1.2.6

type ClientOptions struct {
	// Attributes
	Attributes config.Attributes
	// RetryPolicy holds the retry configuration for the client
	RetryPolicy *RetryPolicy
	// CircuitBreaker holds the circuit breaker configuration for the client
	CircuitBreaker *CircuitBreaker
	// Auth holds the authentication configuration for the client
	Auth AuthProvider
}

type OptionsBuilder added in v1.2.6

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

func NewOptionsBuilder added in v1.2.6

func NewOptionsBuilder() *OptionsBuilder

func (*OptionsBuilder) BasicAuth added in v1.2.6

func (b *OptionsBuilder) BasicAuth(user, pass string) *OptionsBuilder

AddBasicAuth adds basic authentication to the client. This method will override any existing authentication configuration. Parameters:

  • user: The username.
  • pass: The password.

func (*OptionsBuilder) Build added in v1.2.6

func (b *OptionsBuilder) Build() *ClientOptions

Build creates a new ClientOptions with the provided configuration. Returns:

*ClientOptions: The client.

func (*OptionsBuilder) CircuitBreaker added in v1.2.6

func (b *OptionsBuilder) CircuitBreaker(failureThreshold uint64, successThreshold uint64, maxHalfOpen uint32, timeout uint32) *OptionsBuilder

AddCircuitBreaker adds a circuit breaker to the client. Parameters:

  • failureThreshold: The number of consecutive failures required to open the circuit.
  • successThreshold: The number of consecutive successes required to close the circuit.
  • maxHalfOpen: The maximum number of requests allowed in the half-open state.
  • timeout: The timeout duration for the circuit to transition from open to half-open state.

func (*OptionsBuilder) RetryPolicy added in v1.2.6

func (b *OptionsBuilder) RetryPolicy(maxRetries int, backoffIntervalMs int, exponential bool, maxBackoffInMs int) *OptionsBuilder

func (*OptionsBuilder) TokenBearerAuth added in v1.2.6

func (b *OptionsBuilder) TokenBearerAuth(token string) *OptionsBuilder

AddTokenAuth adds token authentication to the client. This method will override any existing authentication configuration. Parameters:

  • token: The token.

func (*OptionsBuilder) WithAttributes added in v1.2.6

func (b *OptionsBuilder) WithAttributes(attributes config.Attributes) *OptionsBuilder

WithAtributes sets the attributes for the client. Parameters:

  • attributes: The attributes to set.

Returns:

*OptionsBuilder: The options builder.

func (*OptionsBuilder) WithAuth added in v1.2.6

func (b *OptionsBuilder) WithAuth(authenticator AuthProvider) *OptionsBuilder

WithAuth sets the authenticator for the client. Parameters:

  • authenticator: The authenticator to set.

Returns:

*OptionsBuilder: The options builder.

func (*OptionsBuilder) WithCircuitBreaker added in v1.2.6

func (b *OptionsBuilder) WithCircuitBreaker(circuitBreaker *CircuitBreaker) *OptionsBuilder

func (*OptionsBuilder) WithRetryPolicy added in v1.2.6

func (b *OptionsBuilder) WithRetryPolicy(retryPolicy *RetryPolicy) *OptionsBuilder

type RetryInfo

type RetryInfo struct {
	MaxRetries int // Maximum number of retries allowed.
	Wait       int // Base wait time in milliseconds between retries.

	// Exponential enables exponential backoff when true.
	// The wait time is multiplied by Multiplier^retryCount on each attempt.
	Exponential bool

	// Multiplier is the factor by which the wait time is multiplied on each
	// successive retry. Defaults to 2 if set to <= 0 when Exponential is true.
	Multiplier float64

	// MaxWait is the upper bound for the wait time in milliseconds.
	// When set to > 0, the computed backoff will never exceed this value.
	MaxWait int

	// Jitter adds randomized jitter to the wait time when true.
	// A random duration between 0 and the computed backoff is added,
	// which helps prevent thundering-herd problems.
	Jitter bool
}

RetryInfo represents the retry configuration for a client. It supports fixed, exponential, and jittered backoff strategies.

func (*RetryInfo) WaitTime added in v1.3.0

func (r *RetryInfo) WaitTime(retryCount int) time.Duration

WaitTime calculates the wait duration for the given retry attempt (0-indexed).

With Exponential=false, it returns a fixed duration of Wait milliseconds.

With Exponential=true, the backoff is computed as:

backoff = Wait * Multiplier^retryCount

The result is capped at MaxWait (if > 0) and optionally jittered.

type RetryPolicy added in v1.2.6

type RetryPolicy struct {
	MaxRetries      int
	BackoffInterval time.Duration
	MaxBackoff      time.Duration
	Exponential     bool
}

func (*RetryPolicy) WaitTime added in v1.2.6

func (r *RetryPolicy) WaitTime(retryCount int) time.Duration

type TokenBearerAuth added in v1.2.6

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

TokenBearerAuth represents bearer token authentication credentials.

func (*TokenBearerAuth) Pass added in v1.2.6

func (b *TokenBearerAuth) Pass() (string, error)

Pass returns an empty string as the password. TokenBearerAuth does not use password credentials. Returns:

string: An empty string.
error: Always nil.

func (*TokenBearerAuth) Refresh added in v1.2.6

func (b *TokenBearerAuth) Refresh() error

Refresh refreshes the authentication token. It currently does not perform any operations and always returns nil.

Returns:

error: Always returns nil.

func (*TokenBearerAuth) Token added in v1.2.6

func (b *TokenBearerAuth) Token() (string, error)

Token returns the token associated with the BearerAuth instance. Returns:

string: The token.
error: Always nil for static bearer tokens.

func (*TokenBearerAuth) Type added in v1.2.6

func (b *TokenBearerAuth) Type() AuthType

Type returns the authentication type for BearerAuth, which is AuthTypeBearer. This is used to determine the type of authentication to be used. Returns:

AuthType: The authentication type. (AuthTypeBearer)

func (*TokenBearerAuth) User added in v1.2.6

func (b *TokenBearerAuth) User() (string, error)

User returns an empty string as the username. TokenBearerAuth does not use username credentials. Returns:

string: An empty string.
error: Always nil.

Jump to

Keyboard shortcuts

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