priorate

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2022 License: MIT Imports: 3 Imported by: 1

README

priorate

Apache License GoDoc Go Report Card Releases

priorate provides rate limiter with priority using golang.org/x/time/rate.
Priority can be defined as a ratio from 0.01 to 0.99, and rate limit can be performed according to priority on a given limit.
Fairly gets limit according to priority.

Installation

go get github.com/octu0/priorate

Example

Here's a quick example for using priorate.NewLimiter.

import(
	"fmt"
	"time"

	"github.com/octu0/priorate"
)

func main() {
	limit := priorate.NewLimiter(100,
		priorate.Priority(priorate.High, 0.7),
		priorate.Priority(priorate.Low, 0.3),
	)
	for i := 0; i < 10; i += 1 {
		if i < 5 {
			high := limit.ReserveN(priorate.High, time.Now(), 30)
			printDelay(high.Delay())
		} else {
			low := limit.ReserveN(priorate.Low, time.Now(), 30)
			printDelay(low.Delay())
		}
	}

	// Output:
	// 0s
	// 0s
	// 299ms
	// 1.099s
	// 1.899s
	// 1.199s
	// 1.966s
	// 3.233s
	// 4.499s
	// 5.766s
}

func printDelay(d time.Duration) {
	fmt.Println(d.Truncate(time.Millisecond))
}

License

MIT, see LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	Version string = "1.0.0"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Level

type Level uint8
const (
	Low Level
	High
)

type Limiter

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

func InfLimiter added in v1.0.0

func InfLimiter() *Limiter

func NewLimiter

func NewLimiter(limit int, funcs ...PriorityFunc) *Limiter

func (*Limiter) Limit

func (lim *Limiter) Limit() int

func (*Limiter) Reserve

func (lim *Limiter) Reserve(lv Level) *Reservation

func (*Limiter) ReserveN

func (lim *Limiter) ReserveN(lv Level, now time.Time, n int) *Reservation

type PriorityFunc

type PriorityFunc func(map[Level]float64)

func Priority

func Priority(p Level, rate float64) PriorityFunc

type Reservation

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

func (*Reservation) Cancel

func (r *Reservation) Cancel()

func (*Reservation) CancelAt

func (r *Reservation) CancelAt(now time.Time)

func (*Reservation) Delay

func (r *Reservation) Delay() time.Duration

func (*Reservation) DelayFrom

func (r *Reservation) DelayFrom(now time.Time) time.Duration

func (*Reservation) OK

func (r *Reservation) OK() bool

Jump to

Keyboard shortcuts

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