rate

package
v0.0.0-...-bc49051 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrRateCheckFailure errutil.Class = "rate check failure"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Bulkhead

type Bulkhead[A, B any] struct {
	Action func(context.Context, A) (B, error)
}

type RateChecker

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

RateChecker is a simple queue based rate measurer that will return an error if `Check` is called too often.

func NewRateChecker

func NewRateChecker(numActions int, quantum time.Duration) *RateChecker

NewRateChecker returns a new rate checker.

func (*RateChecker) Check

func (rc *RateChecker) Check() error

Check returns an error if it is called more than numActions times in quantum duration.

type Wait

type Wait struct {
	NumberOfActions int64
	Quantum         time.Duration
}

Wait is a type that allows you to throttle actions with sleeps based on a desired rate.

The effect is that each call will incur a small duration tax per call to stay beneath the rate formed by `NumberOfActions` and `Quantum`.

func (Wait) Calculate

func (w Wait) Calculate(actions int64, quantum time.Duration) time.Duration

Calculate takes the observed rate and the desired rate, and returns a quantum to sleep for that adjusts the observed rate to match the desired rate.

If the observed rate is _lower_ than the desired rate, the returned value will be negative and you're free to ignore it.

If the observed rate is _higher_ than the desired rate, a positive duration will be returned which you can pass to a `time.Sleep(...)` or similar.

The wait quantum is derrived from the following algebraic steps (where ? is what we're solving for):

pb/(pq+?) = rb/rq
1/(pq+?) = rb/pb*rq
pq+? = (pb*rq)/rb
? = ((pb*rq)/rb) - pq

func (Wait) Wait

func (w Wait) Wait(ctx context.Context, actions int64, quantum time.Duration) error

Wait waits for a calculated throttling time based on the input options.

func (Wait) WaitTimer

func (w Wait) WaitTimer(ctx context.Context, actions int64, quantum time.Duration, after *time.Timer) error

WaitTimer waits with a given (re-used) timer reference.

Jump to

Keyboard shortcuts

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