rate5

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2024 License: MIT Imports: 5 Imported by: 4

README

Rate5

GoDoc Go Report Card Go codecov five

A performant and generic ratelimitter for any golang project.

See the docs and the unit tests as well as the below example for more details.

Basic Example

import rate5 "github.com/yunginnanet/rate5"

var Rater *rate5.Limiter

// [...]
type Client struct {
        ID   string
        Conn net.Conn

        loggedin  bool
}

// Rate5 doesn't care where you derive the string used for ratelimiting
func (c Client) UniqueKey() string {
        if !c.loggedin {
                host, _, _ := net.SplitHostPort(c.Conn.RemoteAddr().String())
                return host
        }
        return c.ID
}

func (s *Server) handleTCP(c *Client) {
	// Returns true if ratelimited
	if Rater.Check(c) {
		c.Conn.Write([]byte("too many connections"))
		c.Conn.Close()
		return
	}
// [...]
}

License

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// DefaultWindow is the standard window of time ratelimit triggers are observed in seconds.
	DefaultWindow = 25
	// DefaultBurst is the standard amount of triggers observed within Window before ratelimiting occurs.
	DefaultBurst = 25
)
View Source
const (
	DebugDisabled uint32 = iota
	DebugEnabled
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Identity

type Identity interface {
	UniqueKey() string
}

Identity is an interface that allows any arbitrary type to be used for a unique key in ratelimit checks when implemented.

type IdentityStringer added in v1.2.0

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

IdentityStringer is an implentation of Identity that acts as a shim for types that implement fmt.Stringer.

func (IdentityStringer) UniqueKey added in v1.2.0

func (i IdentityStringer) UniqueKey() string

type Limiter

type Limiter struct {
	// Patrons gives access to the underlying cache type that powers the ratelimiter.
	// It is exposed for testing purposes.
	Patrons *cache.Cache

	// Ruleset determines the Policy which is used to determine whether or not to ratelimit.
	// It consists of a Window and Burst, see Policy for more details.
	Ruleset Policy

	*sync.RWMutex
	// contains filtered or unexported fields
}

Limiter implements an Enforcer to create an arbitrary ratelimiter.

func NewCustomLimiter

func NewCustomLimiter(policy Policy) *Limiter

NewCustomLimiter returns a ratelimiter with the given Policy applied as the Ruleset.

func NewDefaultLimiter

func NewDefaultLimiter() *Limiter

NewDefaultLimiter returns a ratelimiter with default settings without Strict mode.

  • Default window: 25 seconds
  • Default burst: 25 requests

func NewDefaultStrictLimiter

func NewDefaultStrictLimiter() *Limiter

NewDefaultStrictLimiter returns a ratelimiter with default settings with Strict mode.

  • Default window: 25 seconds
  • Default burst: 25 requests

func NewHardcoreLimiter added in v1.1.0

func NewHardcoreLimiter(window int, burst int) *Limiter

NewHardcoreLimiter returns a custom limiter with Strict + Hardcore modes enabled.

Hardcore mode causes the time limited to be multiplied by the number of hits. This differs from strict mode which is only using addition instead of multiplication.

func NewLimiter

func NewLimiter(window int, burst int) *Limiter

NewLimiter returns a custom limiter witout Strict mode.

  • Window is the time in seconds that the limiter will cache requests.
  • Burst is the number of requests that can be made in the window.

func NewStrictLimiter

func NewStrictLimiter(window int, burst int) *Limiter

NewStrictLimiter returns a custom limiter with Strict mode enabled.

  • Window is the time in seconds that the limiter will cache requests.
  • Burst is the number of requests that can be made in the window.

func (*Limiter) Check

func (q *Limiter) Check(from Identity) (limited bool)

Check checks and increments an Identities UniqueKey() output against a list of cached strings to determine and raise it's ratelimitting status.

func (*Limiter) CheckStringer added in v1.2.0

func (q *Limiter) CheckStringer(from fmt.Stringer) bool

func (*Limiter) DebugChannel

func (q *Limiter) DebugChannel() chan string

DebugChannel enables debug mode and returns a channel where debug messages are sent.

NOTE: If you do not read from this channel, the debug messages will eventually be lost. If this happens,

func (*Limiter) Peek

func (q *Limiter) Peek(from Identity) bool

Peek checks an Identities UniqueKey() output against a list of cached strings to determine ratelimitting status without adding to its request count.

func (*Limiter) PeekStringer added in v1.2.0

func (q *Limiter) PeekStringer(from fmt.Stringer) bool

func (*Limiter) ResetItem added in v1.1.0

func (q *Limiter) ResetItem(from Identity)

func (*Limiter) SetDebug added in v0.4.4

func (q *Limiter) SetDebug(on bool)

type Policy

type Policy struct {
	// Window defines the duration in seconds that we should keep track of ratelimit triggers,
	Window int64
	// Burst is the amount of times that Check will not trigger a limit within the duration defined by Window.
	Burst int64
	// Strict mode punishes triggers of the ratelimitter by increasing the wait time upon every trigger of the limiter.
	Strict bool
	// Hardcore mode implies strict mode but instead of using addition when adding to the wait time, it uses multiplication.
	// This will cause exponential ratelimiting.
	Hardcore bool
}

Policy defines the mechanics of our ratelimiter.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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