go-circuitbreaker: github.com/mercari/go-circuitbreaker Index | Examples | Files

package circuitbreaker

import "github.com/mercari/go-circuitbreaker"

Index

Examples

Package Files

breaker.go state.go

Constants

const (
    DefaultInterval             = 1 * time.Second
    DefaultHalfOpenMaxSuccesses = 4
)

Default setting parameters.

Variables

var (
    // ErrOpen is an error to signify that the CB is open and executing
    // operatins are not allowed.
    ErrOpen = errors.New("circuit breaker open")

    // DefaultTripFunc is used when Options.ShouldTrip is nil.
    DefaultTripFunc = NewTripFuncThreshold(10)
)

func DefaultOpenBackOff Uses

func DefaultOpenBackOff() backoff.BackOff

DefaultOpenBackOff returns defaultly used BackOff.

func Ignore Uses

func Ignore(err error) error

Ignore wraps the given err in a *IgnorableError.

func MarkAsSuccess Uses

func MarkAsSuccess(err error) error

MarkAsSuccess wraps the given err in a *SuccessMarkableError.

type CircuitBreaker Uses

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

CircuitBreaker provides circuit breaker pattern.

Code:

cb := circuitbreaker.New(nil)
ctx := context.Background()

data, err := cb.Do(context.Background(), func() (interface{}, error) {
    user, err := fetchUserInfo(ctx, "太郎")
    if err != nil && err.Error() == "UserNoFound" {
        // If you received a application level error, wrap it with Ignore to
        // avoid false-positive circuit open.
        return nil, circuitbreaker.Ignore(err)
    }
    return user, err
})

if err != nil {
    log.Fatalf("failed to fetch user:%s\n", err.Error())
}
log.Printf("fetched user:%+v\n", data.(*user))

func New Uses

func New(opts *Options) *CircuitBreaker

New returns a new CircuitBreaker with *Options. If opts is nil, default configurations are used.

func (*CircuitBreaker) Counters Uses

func (cb *CircuitBreaker) Counters() Counters

Counters returns internal counters. If current status is not StateClosed, returns zero value.

func (*CircuitBreaker) Do Uses

func (cb *CircuitBreaker) Do(ctx context.Context, o Operation) (interface{}, error)

Do executes the Operation o and returns the return values if cb.Ready() is true. If not ready, cb doesn't execute f and returns ErrOpen.

If o returns a nil-error, cb counts the execution of Operation as a success. Otherwise, cb count it as a failure.

If o returns a *IgnorableError, Do() ignores the result of operation and returns the wrapped error.

If o returns a *SuccessMarkableError, Do() count it as a success and returns the wrapped error.

If given Options' FailOnContextCancel is false (default), cb.Do doesn't mark the Operation's error as a failure if ctx.Err() returns context.Canceled.

If given Options' FailOnContextDeadline is false (default), cb.Do doesn't mark the Operation's error as a failure if ctx.Err() returns context.DeadlineExceeded.

func (*CircuitBreaker) Done Uses

func (cb *CircuitBreaker) Done(ctx context.Context, err error) error

Done is a helper function to finish the protected operation. If err is nil, Done calls Success and returns nil. If err is a SuccessMarkableError or IgnorableError, Done returns wrapped error. Otherwise, Done calls FailWithContext internally.

func (*CircuitBreaker) Fail Uses

func (cb *CircuitBreaker) Fail()

Fail signals that an execution of operation has been failed to cb.

func (*CircuitBreaker) FailWithContext Uses

func (cb *CircuitBreaker) FailWithContext(ctx context.Context)

FailWithContext calls Fail internally. But if FailOnContextCancel is false and ctx is done with context.Canceled error, no Fail() called. Similarly, if FailOnContextDeadline is false and ctx is done with context.DeadlineExceeded error, no Fail() called.

func (*CircuitBreaker) Ready Uses

func (cb *CircuitBreaker) Ready() bool

Ready reports if cb is ready to execute an operation. Ready does not give any change to cb.

func (*CircuitBreaker) Reset Uses

func (cb *CircuitBreaker) Reset()

Reset resets cb's state with StateClosed.

func (*CircuitBreaker) SetState Uses

func (cb *CircuitBreaker) SetState(st State)

SetState set state of cb to st.

func (*CircuitBreaker) State Uses

func (cb *CircuitBreaker) State() State

State reports the curent State of cb.

func (*CircuitBreaker) Success Uses

func (cb *CircuitBreaker) Success()

Success signals that an execution of operation has been completed successfully to cb.

type Counters Uses

type Counters struct {
    Successes            int64
    Failures             int64
    ConsecutiveSuccesses int64
    ConsecutiveFailures  int64
}

Counters holds internal counter(s) of CircuitBreaker.

type IgnorableError Uses

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

IgnorableError signals that the operation should not be marked as a failure.

func (*IgnorableError) Error Uses

func (e *IgnorableError) Error() string

func (*IgnorableError) Unwrap Uses

func (e *IgnorableError) Unwrap() error

Unwrap unwaps e.

type Operation Uses

type Operation func() (interface{}, error)

An Operation is executed by Do().

type Options Uses

type Options struct {
    // Clock to be used by CircuitBreaker. If nil, real-time clock is
    // used.
    Clock clock.Clock

    // Interval is the cyclic time period to reset the internal counters
    // during state is in StateClosed.
    //
    // If zero, DefaultInterval is used. If Interval < 0, No interval will
    // be triggered.
    Interval time.Duration

    // OpenTimeout is the period of StateOpened. After OpenTimeout,
    // CircuitBreaker's state will be changed to StateHalfOpened. If OpenBackOff
    // is not nil, OpenTimeout is ignored.
    OpenTimeout time.Duration

    // OpenBackOff is a Backoff to determine the period of StateOpened. Every
    // time the state transitions to StateOpened, OpenBackOff.NextBackOff()
    // recalculates the period. When the state transitions to StateClosed,
    // OpenBackOff is reset to the initial state. If both OpenTimeout is zero
    // value and OpenBackOff is empty, return value of DefaultOpenBackOff() is
    // used.
    //
    // NOTE: Please make sure not to set the ExponentialBackOff.MaxElapsedTime >
    // 0 for OpenBackOff. If so, your CB don't close after your period of the
    // StateOpened gets longer than the MaxElapsedTime.
    OpenBackOff backoff.BackOff

    // HalfOpenMaxSuccesses is max count of successive successes during the state
    // is in StateHalfOpened. If the state is StateHalfOpened and the successive
    // successes reaches this threashold, the state of CircuitBreaker changes
    // into StateClosed. If zero, DefaultHalfOpenMaxSuccesses is used.
    HalfOpenMaxSuccesses int64

    // ShouldTrips is a function to determine if the CircuitBreaker should
    // trip. If the state is StateClosed and ShouldTrip returns true,
    // the state will be changed to StateOpened.
    // If nil, DefaultTripFunc is used.
    ShouldTrip TripFunc

    // FailOnContextCancel controls if CircuitBreaker mark an error when the
    // passed context.Done() is context.Canceled as a fail.
    FailOnContextCancel bool

    // FailOnContextDeadline controls if CircuitBreaker mark an error when the
    // passed context.Done() is context.DeadlineExceeded as a fail.
    FailOnContextDeadline bool
}

Options holds CircuitBreaker configuration options.

type State Uses

type State string

State represents the internal state of CB.

const (
    StateClosed   State = "closed"
    StateOpen     State = "open"
    StateHalfOpen State = "half-open"
)

State constants.

type SuccessMarkableError Uses

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

SuccessMarkableError signals that the operation should be mark as success.

func (*SuccessMarkableError) Error Uses

func (e *SuccessMarkableError) Error() string

func (*SuccessMarkableError) Unwrap Uses

func (e *SuccessMarkableError) Unwrap() error

Unwrap unwaps e.

type TripFunc Uses

type TripFunc func(*Counters) bool

TripFunc is a function to determine if CircuitBreaker should open (trip) or not. TripFunc is called when cb.Fail was called and the state was StateClosed. If TripFunc returns true, the cb's state goes to StateOpen.

func NewTripFuncConsecutiveFailures Uses

func NewTripFuncConsecutiveFailures(threshold int64) TripFunc

NewTripFuncConsecutiveFailures provides a TripFunc that returns true if the consecutive failures is larger than or equals to threshold.

func NewTripFuncFailureRate Uses

func NewTripFuncFailureRate(min int64, rate float64) TripFunc

NewTripFuncFailureRate provides a TripFunc that returns true if the failure rate is higher or equals to rate. If the samples are fewer than min, always returns false.

func NewTripFuncThreshold Uses

func NewTripFuncThreshold(threshold int64) TripFunc

NewTripFuncThreshold provides a TripFunc. It returns true if the Failures counter is larger than or equals to threshold.

Package circuitbreaker imports 7 packages (graph). Updated 2020-01-07. Refresh now. Tools for package owners.