throttled

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2024 License: BSD-3-Clause Imports: 10 Imported by: 0

README

Throttled build status GoDoc

Package throttled implements rate limiting using the generic cell rate algorithm to limit access to resources such as HTTP endpoints.

The 2.0.0 release made some major changes to the throttled API. If this change broke your code in problematic ways or you wish a feature of the old API had been retained, please open an issue. We don't guarantee any particular changes but would like to hear more about what our users need. Thanks!

Installation

go get -u github.com/throttled/throttled

Documentation

API documentation is available on godoc.org. The following example demonstrates the usage of HTTPLimiter for rate-limiting access to an http.Handler to 20 requests per path per minute with bursts of up to 5 additional requests:

store, err := memstore.New(65536)
if err != nil {
	log.Fatal(err)
}

quota := throttled.RateQuota{throttled.PerMin(20), 5}
rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
if err != nil {
	log.Fatal(err)
}

httpRateLimiter := throttled.HTTPRateLimiter{
	RateLimiter: rateLimiter,
	VaryBy:      &throttled.VaryBy{Path: true},
}

http.ListenAndServe(":8080", httpRateLimiter.RateLimit(myHandler))

See throttled/gcra for a list of other projects related to rate limiting and GCRA.

Release

  1. Update CHANGELOG.md. Please use semantic versioning and the existing conventions established in the file. Commit the changes with a message like Bump version to 2.2.0.
  2. Tag master with a new version prefixed with v. For example, v2.2.0.
  3. git push origin master --tags.
  4. Publish a new release on the releases page. Copy the body from the contents of CHANGELOG.md for the version and follow other conventions from previous releases.

License

The BSD 3-clause license. Copyright (c) 2014 Martin Angers and contributors.

Documentation

Overview

Package throttled implements rate limiting access to resources such as HTTP endpoints.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultDeniedHandler is the default DeniedHandler for an
	// HTTPRateLimiter. It returns a 429 status code with a generic
	// message.
	DefaultDeniedHandler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "limit exceeded", 429)
	}))

	// DefaultError is the default Error function for an HTTPRateLimiter.
	// It returns a 500 status code with a generic message.
	DefaultError = func(w http.ResponseWriter, r *http.Request, err error) {
		http.Error(w, "internal error", http.StatusInternalServerError)
	}
)

Functions

This section is empty.

Types

type Clock

type Clock interface {
	Now() time.Time
}

Clock provides the current time right now.

type ClockFunc

type ClockFunc func() time.Time

ClockFunc is a wrapper for functions that provide the current time right now.

func (ClockFunc) Now

func (cf ClockFunc) Now() time.Time

Now provides the current time right now as defined by the function wrapped in ClockFunc.

type GCRARateLimiter

type GCRARateLimiter struct {
	Clock Clock

	sync.Mutex
	// contains filtered or unexported fields
}

GCRARateLimiter is a RateLimiter that users the generic cell-rate algorithm. The algorithm has been slightly modified from its usual form to support limiting with an additional quantity parameter, such as for limiting the number of bytes uploaded.

func NewGCRARateLimiter

func NewGCRARateLimiter(maxKeys int, quota RateQuota) (*GCRARateLimiter, error)

NewGCRARateLimiter creates a GCRARateLimiter. quota.Count defines the maximum number of requests permitted in an instantaneous burst and quota.Count / quota.Period defines the maximum sustained rate. For example, PerMin(60) permits 60 requests instantly per key followed by one request per second indefinitely whereas PerSec(1) only permits one request per second with no tolerance for bursts.

func (*GCRARateLimiter) RateLimit

func (g *GCRARateLimiter) RateLimit(key string, quantity int) (bool, RateLimitResult, error)

RateLimit checks whether a particular key has exceeded a rate limit. It also returns a RateLimitResult to provide additional information about the state of the RateLimiter.

If the rate limit has not been exceeded, the underlying storage is updated by the supplied quantity. For example, a quantity of 1 might be used to rate limit a single request while a greater quantity could rate limit based on the size of a file upload in megabytes. If quantity is 0, no update is performed allowing you to "peek" at the state of the RateLimiter for a given key.

type HTTPRateLimiter

type HTTPRateLimiter struct {
	// DeniedHandler is called if the request is disallowed. If it is
	// nil, the DefaultDeniedHandler variable is used.
	DeniedHandler http.Handler

	// Error is called if the RateLimiter returns an error. If it is
	// nil, the DefaultErrorFunc is used.
	Error func(w http.ResponseWriter, r *http.Request, err error)

	// Limiter is call for each request to determine whether the
	// request is permitted and update internal state. It must be set.
	RateLimiter RateLimiter

	// VaryBy is called for each request to generate a key for the
	// limiter. If it is nil, all requests use an empty string key.
	VaryBy interface {
		Key(*http.Request) string
	}
}

HTTPRateLimiter faciliates using a Limiter to limit HTTP requests.

func (*HTTPRateLimiter) RateLimit

func (t *HTTPRateLimiter) RateLimit(h http.Handler) http.Handler

RateLimit wraps an http.Handler to limit incoming requests. Requests that are not limited will be passed to the handler unchanged. Limited requests will be passed to the DeniedHandler. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset and Retry-After headers will be written to the response based on the values in the RateLimitResult.

type Rate

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

Rate describes a frequency of an activity such as the number of requests allowed per minute.

func PerDay

func PerDay(n int) Rate

PerDay represents a number of requests per day.

func PerHour

func PerHour(n int) Rate

PerHour represents a number of requests per hour.

func PerMin

func PerMin(n int) Rate

PerMin represents a number of requests per minute.

func PerSec

func PerSec(n int) Rate

PerSec represents a number of requests per second.

type RateLimitResult

type RateLimitResult struct {
	// Limit is the maximum number of requests that could be permitted
	// instantaneously for this key starting from an empty state. For
	// example, if a rate limiter allows 10 requests per second per
	// key, Limit would always be 10.
	Limit int

	// Remaining is the maximum number of requests that could be
	// permitted instantaneously for this key given the current
	// state. For example, if a rate limiter allows 10 requests per
	// second and has already received 6 requests for this key this
	// second, Remaining would be 4.
	Remaining int

	// ResetAfter is the time until the RateLimiter returns to its
	// initial state for a given key. For example, if a rate limiter
	// manages requests per second and received one request 200ms ago,
	// Reset would return 800ms. You can also think of this as the time
	// until Limit and Remaining will be equal.
	ResetAfter time.Duration

	// RetryAfter is the time until the next request will be permitted.
	// It should be -1 unless the rate limit has been exceeded.
	RetryAfter time.Duration
}

RateLimitResult represents the state of the RateLimiter for a given key at the time of the query. This state can be used, for example, to communicate information to the client via HTTP headers. Negative values indicate that the attribute is not relevant to the implementation or state.

type RateLimiter

type RateLimiter interface {
	// RateLimit checks whether a particular key has exceeded a rate
	// limit. It also returns a RateLimitResult to provide additional
	// information about the state of the RateLimiter.
	//
	// If the rate limit has not been exceeded, the underlying storage
	// is updated by the supplied quantity. For example, a quantity of
	// 1 might be used to rate limit a single request while a greater
	// quantity could rate limit based on the size of a file upload in
	// megabytes. If quantity is 0, no update is performed allowing
	// you to "peek" at the state of the RateLimiter for a given key.
	RateLimit(key string, quantity int) (bool, RateLimitResult, error)
}

A RateLimiter manages limiting the rate of actions by key.

type RateQuota

type RateQuota struct {
	MaxRate  Rate
	MaxBurst int
}

RateQuota describes the number of requests allowed per time period. MaxRate specified the maximum sustained rate of requests and must be greater than zero. MaxBurst defines the number of requests that will be allowed to exceed the rate in a single burst and must be greater than or equal to zero.

Rate{PerSec(1), 0} would mean that after each request, no more requests will be permitted for that client for one second. Rate{PerSec(2), 0} permits one request per 0.5 seconds rather than two requests in one second. In practice, you probably want to set MaxBurst >0 to provide some flexibility to clients that only need to make a handful of requests. In fact a MaxBurst of zero will *never* permit a request with a quantity greater than one because it will immediately exceed the limit.

type VaryBy

type VaryBy struct {
	// Vary by the RemoteAddr as specified by the net/http.Request field.
	RemoteAddr bool

	// Vary by the HTTP Method as specified by the net/http.Request field.
	Method bool

	// Vary by the URL's Path as specified by the Path field of the net/http.Request
	// URL field.
	Path bool

	// Vary by this list of header names, read from the net/http.Request Header field.
	Headers []string

	// Vary by this list of parameters, read from the net/http.Request FormValue method.
	Params []string

	// Vary by this list of cookie names, read from the net/http.Request Cookie method.
	Cookies []string

	// Use this separator string to concatenate the various criteria of the VaryBy struct.
	// Defaults to a newline character if empty (\n).
	Separator string

	// DEPRECATED. Custom specifies the custom-generated key to use for this request.
	// If not nil, the value returned by this function is used instead of any
	// VaryBy criteria.
	Custom func(r *http.Request) string
}

VaryBy defines the criteria to use to group requests.

func (*VaryBy) Key

func (vb *VaryBy) Key(r *http.Request) string

Key returns the key for this request based on the criteria defined by the VaryBy struct.

Jump to

Keyboard shortcuts

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