clients

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2025 License: MIT Imports: 3 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 CBOpenErr = errors.New("the Circuit breaker is open and unable to process request")

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

Functions

This section is empty.

Types

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 NewCB

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

NewCB 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 RetryInfo

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

RetryInfo represents the retry configuration for a client.

Jump to

Keyboard shortcuts

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