tripper

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2024 License: MIT Imports: 3 Imported by: 0

README

Tripper

Tripper is a circuit breaker package for Go that allows you to circuit and control the status of circuits.

Tripper

Coverage Status Go Reference

Installation

To install Tripper, use go get:

go get github.com/rajnandan1/go-tripper

Usage

Import the Tripper package in your Go code:

import "github.com/rajnandan1/go-tripper"
Adding a Circuit

To add a circuit to the Tripper, use the ConfigureCircuit function:

Circuit With Count
//Adding a circuit that will trip the circuit if count of failure is more than 10 in 1 minute
//for a minimum of 100 count
circuitOptions := tripper.CircuitOptions{
    Name:              "example-circuit",
    Threshold:         10,
    ThresholdType:     tripper.ThresholdCount,
    MinimumCount:      100,
    IntervalInSeconds: 60,
    OnCircuitOpen:     onCircuitOpenCallback,
    OnCircuitClosed:   onCircuitClosedCallback,
}

circuit, err := tripper.ConfigureCircuit(circuitOptions)
if err != nil {
    fmt.Println("Failed to add circuit:", err)
    return
}
Circuit With Percentage
//Adding a circuit that will trip the circuit if count of failure is more than 10% in 1 minute
//for a minimum of 100 count
circuitOptions := tripper.CircuitOptions{
    Name:              "example-circuit",
    Threshold:         10,
    ThresholdType:     tripper.ThresholdPercentage,
    MinimumCount:      100,
    IntervalInSeconds: 60,
    OnCircuitOpen:     onCircuitOpenCallback,
    OnCircuitClosed:   onCircuitClosedCallback,
}

circuit, err := tripper.ConfigureCircuit(circuitOptions)
if err != nil {
    fmt.Println("Failed to add circuit:", err)
    return
}
Circuit With Consecutive Errors
//Adding a circuit that will trip the circuit if 10 consecutive erros occur in 1 minute
//for a minimum of 100 count
circuitOptions := tripper.CircuitOptions{
    Name:              "example-circuit",
    Threshold:         10,
    ThresholdType:     tripper.ThresholdConsecutive,
    MinimumCount:      100,
    IntervalInSeconds: 60,
    OnCircuitOpen:     onCircuitOpenCallback,
    OnCircuitClosed:   onCircuitClosedCallback,
}

circuit, err := tripper.ConfigureCircuit(circuitOptions)
if err != nil {
    fmt.Println("Failed to add circuit:", err)
    return
}
Circuit with Callbacks
func onCircuitOpenCallback(x tripper.CallbackEvent){
    fmt.Println("Callback OPEN")
	fmt.Println(x.FailureCount)
	fmt.Println(x.SuccessCount)
	fmt.Println(x.Timestamp)
}
func onCircuitClosedCallback(x tripper.CallbackEvent){
    fmt.Println("Callback Closed")
	fmt.Println(x.FailureCount)
	fmt.Println(x.SuccessCount)
	fmt.Println(x.Timestamp)
}
circuitOptions := tripper.CircuitOptions{
    Name:              "example-circuit",
    Threshold:         10,
    ThresholdType:     tripper.ThresholdCount,
    MinimumCount:      100,
    IntervalInSeconds: 60,
    OnCircuitOpen:     onCircuitOpenCallback,
    OnCircuitClosed:   onCircuitClosedCallback,
}

circuit, err := tripper.ConfigureCircuit(circuitOptions)
if err != nil {
    fmt.Println("Failed to add circuit:", err)
    return
}
Circuit Options
Option Description Required Type
Name The name of the circuit. Required string
Threshold The threshold value for the circuit. Required float32
ThresholdType The type of threshold (ThresholdCount or ThresholdPercentageor ThresholdConsecutive). Required string
MinimumCount The minimum number of events required for monitoring. Required int64
IntervalInSeconds The time interval for monitoring in seconds. Required int
OnCircuitOpen Callback function called when the circuit opens. Optional func()
OnCircuitClosed Callback function called when the circuit closes. Optional func()

Circuits are reset after IntervalInSeconds

Updating Circuit Status

To update the status of a circuit based on the success of an event, use the UpdateStatus function:

circuit.UpdateStatus(true)  // Success event
circuit.UpdateStatus(false) // Failure event
Checking Circuit Status

To check if a circuit is open or closed, use the IsCircuitOpen function:

isOpen := circuit.IsCircuitOpen()
if isOpen {
    fmt.Println("Circuit is open")
} else {
    fmt.Println("Circuit is closed")
}
Example: HTTP Request with Circuit Breaker

Here's an example of using Tripper to handle HTTP requests with a circuit breaker:

package main

import (
    "fmt"
    "time"

    "github.com/rajnandan1/go-tripper"
)

func main() {
    // Configure the circuit options
    circuitOptions := tripper.CircuitOptions{
        Name:              "MyServiceMonitor",
        Threshold:         50, // Threshold for triggering circuit open (percentage)
        ThresholdType:     tripper.ThresholdPercentage,
        MinimumCount:      10,  // Minimum number of events required for monitoring
        IntervalInSeconds: 60,  // Interval in seconds for monitoring
        OnCircuitOpen: func(event tripper.CallbackEvent) {
            fmt.Println("Circuit opened:", event)
        },
        OnCircuitClosed: func(event tripper.CallbackEvent) {
            fmt.Println("Circuit closed:", event)
        },
    }

    // Create a new circuit
    circuit, err := tripper.ConfigureCircuit(circuitOptions)
    if err != nil {
        fmt.Println("Error creating circuit:", err)
        return
    }

    // Simulate calling a service
    for i := 0; i < 20; i++ {
        success := i%2 == 0 // Simulate failures every other call
        circuit.UpdateStatus(success)
        time.Sleep(time.Second)
    }

    // Check if the circuit is open
    if circuit.IsCircuitOpen() {
        fmt.Println("Circuit is open!")
    } else {
        fmt.Println("Circuit is closed.")
    }
}

License

This project is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	ThresholdCount       = "COUNT"
	ThresholdPercentage  = "PERCENTAGE"
	ThresholdConsecutive = "CONSECUTIVE"
)

threshold type can be only COUNT or PERCENTAGE ThresholdCount represents a threshold type based on count.

Variables

This section is empty.

Functions

This section is empty.

Types

type CallbackEvent added in v1.0.3

type CallbackEvent struct {
	Timestamp    int64
	SuccessCount int64
	FailureCount int64
}

CallbackEvent represents an event callback for the circuit.

type Circuit added in v1.0.3

type Circuit interface {
	UpdateStatus(success bool)
	IsCircuitOpen() bool
	Data() CircuitData
}

Circuit represents a monitoring entity that tracks the status of a circuit.

func ConfigureCircuit added in v1.0.3

func ConfigureCircuit(monitorOptions CircuitOptions) (Circuit, error)

ConfigureCircuit creates and configures a new Circuit with the provided options.

type CircuitData added in v1.0.3

type CircuitData struct {
	SuccessCount       int64
	FailureCount       int64
	IsCircuitOpen      bool
	CircuitOpenedSince int64
}

type CircuitImplementation added in v1.0.3

type CircuitImplementation struct {
	Options            CircuitOptions
	FailureCount       int64 // Number of failures recorded
	SuccessCount       int64 // Number of successes recorded
	CircuitOpen        bool  // Indicates whether the circuit is open or closed
	LastCapturedAt     int64 // Timestamp of the last captured event
	CircuitOpenedSince int64 // Timestamp when the circuit was opened
	ConsecutiveCounter int64
	Ticker             *time.Ticker
	Mutex              sync.Mutex
	XMutex             sync.Mutex
}

CircuitImplementation represents the implementation of the Circuit interface.

func (*CircuitImplementation) Data added in v1.0.3

func (*CircuitImplementation) IsCircuitOpen added in v1.0.3

func (m *CircuitImplementation) IsCircuitOpen() bool

IsCircuitOpen returns true if the circuit is open, false otherwise.

func (*CircuitImplementation) UpdateStatus added in v1.0.3

func (m *CircuitImplementation) UpdateStatus(success bool)

UpdateStatus updates the status of the Circuit based on the success of the event.

type CircuitOptions added in v1.0.3

type CircuitOptions struct {
	Name              string  // Name of the circuit
	Threshold         float32 // Threshold value for triggering circuit open
	ThresholdType     string  // Type of threshold (e.g., percentage, count)
	MinimumCount      int64   // Minimum number of events required for monitoring
	IntervalInSeconds int     // Interval in seconds for monitoring (should be non-zero and multiple of 60)
	OnCircuitOpen     func(t CallbackEvent)
	OnCircuitClosed   func(t CallbackEvent)
}

CircuitOptions represents options for configuring a Circuit.

Jump to

Keyboard shortcuts

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