summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/throttled
diff options
context:
space:
mode:
authorChristopher Speller <crspeller@gmail.com>2018-06-21 13:10:40 -0700
committerHarrison Healey <harrisonmhealey@gmail.com>2018-06-21 16:10:40 -0400
commit8526739066ccb00ccd24b74650a7d7b284442985 (patch)
tree282512ae2ad95c98a9ca82de304a410b6b56685c /vendor/github.com/throttled
parenta59ccaa8b3844895dde3980e6224fef46ff4a1c8 (diff)
downloadchat-8526739066ccb00ccd24b74650a7d7b284442985.tar.gz
chat-8526739066ccb00ccd24b74650a7d7b284442985.tar.bz2
chat-8526739066ccb00ccd24b74650a7d7b284442985.zip
MM-10934 Update server dependencies. (#8981)
* Changing throttled import path. * Upgrading dependencies.
Diffstat (limited to 'vendor/github.com/throttled')
-rw-r--r--vendor/github.com/throttled/throttled/.gitignore5
-rw-r--r--vendor/github.com/throttled/throttled/.travis.yml23
-rw-r--r--vendor/github.com/throttled/throttled/CHANGELOG.md31
-rw-r--r--vendor/github.com/throttled/throttled/LICENSE12
-rw-r--r--vendor/github.com/throttled/throttled/Makefile30
-rw-r--r--vendor/github.com/throttled/throttled/README.md76
-rw-r--r--vendor/github.com/throttled/throttled/deprecated.go73
-rw-r--r--vendor/github.com/throttled/throttled/doc.go3
-rw-r--r--vendor/github.com/throttled/throttled/http.go110
-rw-r--r--vendor/github.com/throttled/throttled/rate.go242
-rw-r--r--vendor/github.com/throttled/throttled/store.go34
-rw-r--r--vendor/github.com/throttled/throttled/store/memstore/memstore.go127
-rw-r--r--vendor/github.com/throttled/throttled/varyby.go78
13 files changed, 844 insertions, 0 deletions
diff --git a/vendor/github.com/throttled/throttled/.gitignore b/vendor/github.com/throttled/throttled/.gitignore
new file mode 100644
index 000000000..96c4e10b7
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/.gitignore
@@ -0,0 +1,5 @@
+.DS_Store
+*.swp
+*.swo
+*.test
+*.out
diff --git a/vendor/github.com/throttled/throttled/.travis.yml b/vendor/github.com/throttled/throttled/.travis.yml
new file mode 100644
index 000000000..4f90ff6f0
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/.travis.yml
@@ -0,0 +1,23 @@
+sudo: false
+
+language: go
+
+go:
+ - 1.7
+ - 1.8
+ - 1.9
+ - "1.10"
+ # 1.x builds the latest in that series. Also try to add other versions here
+ # as they come up so that we're pretty sure that we're maintaining
+ # backwards compatibility.
+ - 1.x
+
+notifications:
+ email: false
+
+services:
+ - redis-server
+
+install: make get-deps
+
+script: make
diff --git a/vendor/github.com/throttled/throttled/CHANGELOG.md b/vendor/github.com/throttled/throttled/CHANGELOG.md
new file mode 100644
index 000000000..3173d1938
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/CHANGELOG.md
@@ -0,0 +1,31 @@
+# Changelog
+
+## Unreleased
+
+## 2.2.1 - 2018-03-21
+* [#40](https://github.com/throttled/throttled/pull/40) Replace unmaintained `garyburd/redigo` with `gomodule/redigo`
+
+## 2.2.0 - 2018-03-19
+* [#37](https://github.com/throttled/throttled/pull/37) Add `go-redis` support
+
+## 2.1.0 - 2017-10-23
+* [#27](https://github.com/throttled/throttled/pull/27) Never assign a Redis key's TTL to zero
+* [#32](https://github.com/throttled/throttled/pull/32) Stop using `gopkg.in`
+
+## 2.0.3 - 2015-09-09
+* [#15](https://github.com/throttled/throttled/pull/15) Use non-HTTP example for `GCRARateLimiter`
+
+## 2.0.2 - 2015-09-07
+* [#14](https://github.com/throttled/throttled/pull/14) Add example demonstrating granular use of `RateLimit`
+
+## 2.0.1 - 2015-09-01
+* [#12](https://github.com/throttled/throttled/pull/12) Fix parsing of `TIME` in `redigostore`
+
+## 2.0.0 - 2015-08-28
+* [#9](https://github.com/throttled/throttled/pull/9) Substantially rebuild the APIs and implementation of the `throttled` package (wholly not backwards compatible)
+
+(There are other versions, but this is the beginning of `CHANGELOG.md`.)
+
+<!--
+# vim: set tw=0:
+-->
diff --git a/vendor/github.com/throttled/throttled/LICENSE b/vendor/github.com/throttled/throttled/LICENSE
new file mode 100644
index 000000000..f9616483e
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/LICENSE
@@ -0,0 +1,12 @@
+Copyright (c) 2014, Martin Angers and Contributors.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/throttled/throttled/Makefile b/vendor/github.com/throttled/throttled/Makefile
new file mode 100644
index 000000000..75df21ed3
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/Makefile
@@ -0,0 +1,30 @@
+
+
+.PHONY: test test-cover bench lint get-deps .go-test .go-test-cover
+
+test: .go-test bench lint
+
+test-cover: .go-test-cover bench lint
+
+bench:
+ go test -race -bench=. -cpu=1,2,4
+
+lint:
+ gofmt -l .
+ go vet ./...
+ which golint # Fail if golint doesn't exist
+ -golint . # Don't fail on golint warnings themselves
+ -golint store # Don't fail on golint warnings themselves
+
+get-deps:
+ go get github.com/gomodule/redigo/redis
+ go get github.com/hashicorp/golang-lru
+ go get github.com/golang/lint/golint
+ go get github.com/go-redis/redis
+
+.go-test:
+ go test ./...
+
+.go-test-cover:
+ go test -coverprofile=throttled.coverage.out .
+ go test -coverprofile=store.coverage.out ./store
diff --git a/vendor/github.com/throttled/throttled/README.md b/vendor/github.com/throttled/throttled/README.md
new file mode 100644
index 000000000..484a049a9
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/README.md
@@ -0,0 +1,76 @@
+# Throttled [![build status](https://secure.travis-ci.org/throttled/throttled.svg)](https://travis-ci.org/throttled/throttled) [![GoDoc](https://godoc.org/github.com/throttled/throttled?status.svg)](https://godoc.org/github.com/throttled/throttled)
+
+Package throttled implements rate limiting using the [generic cell rate
+algorithm][gcra] 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
+
+```sh
+go get -u github.com/throttled/throttled
+```
+
+## Documentation
+
+API documentation is available on [godoc.org][doc]. 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:
+
+```go
+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))
+```
+
+## Related Projects
+
+See [throttled/gcra][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][bsd]. Copyright (c) 2014 Martin Angers and contributors.
+
+[blog]: http://0value.com/throttled--guardian-of-the-web-server
+[bsd]: https://opensource.org/licenses/BSD-3-Clause
+[doc]: https://godoc.org/github.com/throttled/throttled
+[gcra]: https://en.wikipedia.org/wiki/Generic_cell_rate_algorithm
+[puerkitobio]: https://github.com/puerkitobio/
+[pr]: https://github.com/throttled/throttled/compare
+[releases]: https://github.com/throttled/throttled/releases
+[throttled-gcra]: https://github.com/throttled/gcra
+
+<!--
+# vim: set tw=79:
+-->
diff --git a/vendor/github.com/throttled/throttled/deprecated.go b/vendor/github.com/throttled/throttled/deprecated.go
new file mode 100644
index 000000000..f2c648a3e
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/deprecated.go
@@ -0,0 +1,73 @@
+package throttled
+
+import (
+ "net/http"
+ "time"
+)
+
+// DEPRECATED. Quota returns the number of requests allowed and the custom time window.
+func (q Rate) Quota() (int, time.Duration) {
+ return q.count, q.period * time.Duration(q.count)
+}
+
+// DEPRECATED. Q represents a custom quota.
+type Q struct {
+ Requests int
+ Window time.Duration
+}
+
+// DEPRECATED. Quota returns the number of requests allowed and the custom time window.
+func (q Q) Quota() (int, time.Duration) {
+ return q.Requests, q.Window
+}
+
+// DEPRECATED. The Quota interface defines the method to implement to describe
+// a time-window quota, as required by the RateLimit throttler.
+type Quota interface {
+ // Quota returns a number of requests allowed, and a duration.
+ Quota() (int, time.Duration)
+}
+
+// DEPRECATED. Throttler is a backwards-compatible alias for HTTPLimiter.
+type Throttler struct {
+ HTTPRateLimiter
+}
+
+// DEPRECATED. Throttle is an alias for HTTPLimiter#Limit
+func (t *Throttler) Throttle(h http.Handler) http.Handler {
+ return t.RateLimit(h)
+}
+
+// DEPRECATED. RateLimit creates a Throttler that conforms to the given
+// rate limits
+func RateLimit(q Quota, vary *VaryBy, store GCRAStore) *Throttler {
+ count, period := q.Quota()
+
+ if count < 1 {
+ count = 1
+ }
+ if period <= 0 {
+ period = time.Second
+ }
+
+ rate := Rate{period: period / time.Duration(count)}
+ limiter, err := NewGCRARateLimiter(store, RateQuota{rate, count - 1})
+
+ // This panic in unavoidable because the original interface does
+ // not support returning an error.
+ if err != nil {
+ panic(err)
+ }
+
+ return &Throttler{
+ HTTPRateLimiter{
+ RateLimiter: limiter,
+ VaryBy: vary,
+ },
+ }
+}
+
+// DEPRECATED. Store is an alias for GCRAStore
+type Store interface {
+ GCRAStore
+}
diff --git a/vendor/github.com/throttled/throttled/doc.go b/vendor/github.com/throttled/throttled/doc.go
new file mode 100644
index 000000000..cb14a65a6
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/doc.go
@@ -0,0 +1,3 @@
+// Package throttled implements rate limiting access to resources such
+// as HTTP endpoints.
+package throttled // import "github.com/throttled/throttled"
diff --git a/vendor/github.com/throttled/throttled/http.go b/vendor/github.com/throttled/throttled/http.go
new file mode 100644
index 000000000..4c513a81d
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/http.go
@@ -0,0 +1,110 @@
+package throttled
+
+import (
+ "errors"
+ "math"
+ "net/http"
+ "strconv"
+)
+
+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)
+ }
+)
+
+// HTTPRateLimiter faciliates using a Limiter to limit HTTP requests.
+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
+ }
+}
+
+// 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.
+func (t *HTTPRateLimiter) RateLimit(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if t.RateLimiter == nil {
+ t.error(w, r, errors.New("You must set a RateLimiter on HTTPRateLimiter"))
+ }
+
+ var k string
+ if t.VaryBy != nil {
+ k = t.VaryBy.Key(r)
+ }
+
+ limited, context, err := t.RateLimiter.RateLimit(k, 1)
+
+ if err != nil {
+ t.error(w, r, err)
+ return
+ }
+
+ setRateLimitHeaders(w, context)
+
+ if !limited {
+ h.ServeHTTP(w, r)
+ } else {
+ dh := t.DeniedHandler
+ if dh == nil {
+ dh = DefaultDeniedHandler
+ }
+ dh.ServeHTTP(w, r)
+ }
+ })
+}
+
+func (t *HTTPRateLimiter) error(w http.ResponseWriter, r *http.Request, err error) {
+ e := t.Error
+ if e == nil {
+ e = DefaultError
+ }
+ e(w, r, err)
+}
+
+func setRateLimitHeaders(w http.ResponseWriter, context RateLimitResult) {
+ if v := context.Limit; v >= 0 {
+ w.Header().Add("X-RateLimit-Limit", strconv.Itoa(v))
+ }
+
+ if v := context.Remaining; v >= 0 {
+ w.Header().Add("X-RateLimit-Remaining", strconv.Itoa(v))
+ }
+
+ if v := context.ResetAfter; v >= 0 {
+ vi := int(math.Ceil(v.Seconds()))
+ w.Header().Add("X-RateLimit-Reset", strconv.Itoa(vi))
+ }
+
+ if v := context.RetryAfter; v >= 0 {
+ vi := int(math.Ceil(v.Seconds()))
+ w.Header().Add("Retry-After", strconv.Itoa(vi))
+ }
+}
diff --git a/vendor/github.com/throttled/throttled/rate.go b/vendor/github.com/throttled/throttled/rate.go
new file mode 100644
index 000000000..649287beb
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/rate.go
@@ -0,0 +1,242 @@
+package throttled
+
+import (
+ "fmt"
+ "time"
+)
+
+const (
+ // Maximum number of times to retry SetIfNotExists/CompareAndSwap operations
+ // before returning an error.
+ maxCASAttempts = 10
+)
+
+// A RateLimiter manages limiting the rate of actions by key.
+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)
+}
+
+// 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 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
+}
+
+type limitResult struct {
+ limited bool
+}
+
+func (r *limitResult) Limited() bool { return r.limited }
+
+type rateLimitResult struct {
+ limitResult
+
+ limit, remaining int
+ reset, retryAfter time.Duration
+}
+
+func (r *rateLimitResult) Limit() int { return r.limit }
+func (r *rateLimitResult) Remaining() int { return r.remaining }
+func (r *rateLimitResult) Reset() time.Duration { return r.reset }
+func (r *rateLimitResult) RetryAfter() time.Duration { return r.retryAfter }
+
+// Rate describes a frequency of an activity such as the number of requests
+// allowed per minute.
+type Rate struct {
+ period time.Duration // Time between equally spaced requests at the rate
+ count int // Used internally for deprecated `RateLimit` interface only
+}
+
+// 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 RateQuota struct {
+ MaxRate Rate
+ MaxBurst int
+}
+
+// PerSec represents a number of requests per second.
+func PerSec(n int) Rate { return Rate{time.Second / time.Duration(n), n} }
+
+// PerMin represents a number of requests per minute.
+func PerMin(n int) Rate { return Rate{time.Minute / time.Duration(n), n} }
+
+// PerHour represents a number of requests per hour.
+func PerHour(n int) Rate { return Rate{time.Hour / time.Duration(n), n} }
+
+// PerDay represents a number of requests per day.
+func PerDay(n int) Rate { return Rate{24 * time.Hour / time.Duration(n), n} }
+
+// 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.
+type GCRARateLimiter struct {
+ limit int
+
+ // Think of the DVT as our flexibility:
+ // How far can you deviate from the nominal equally spaced schedule?
+ // If you like leaky buckets, think about it as the size of your bucket.
+ delayVariationTolerance time.Duration
+
+ // Think of the emission interval as the time between events
+ // in the nominal equally spaced schedule. If you like leaky buckets,
+ // think of it as how frequently the bucket leaks one unit.
+ emissionInterval time.Duration
+
+ store GCRAStore
+}
+
+// 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 NewGCRARateLimiter(st GCRAStore, quota RateQuota) (*GCRARateLimiter, error) {
+ if quota.MaxBurst < 0 {
+ return nil, fmt.Errorf("Invalid RateQuota %#v. MaxBurst must be greater than zero.", quota)
+ }
+ if quota.MaxRate.period <= 0 {
+ return nil, fmt.Errorf("Invalid RateQuota %#v. MaxRate must be greater than zero.", quota)
+ }
+
+ return &GCRARateLimiter{
+ delayVariationTolerance: quota.MaxRate.period * (time.Duration(quota.MaxBurst) + 1),
+ emissionInterval: quota.MaxRate.period,
+ limit: quota.MaxBurst + 1,
+ store: st,
+ }, nil
+}
+
+// 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.
+func (g *GCRARateLimiter) RateLimit(key string, quantity int) (bool, RateLimitResult, error) {
+ var tat, newTat, now time.Time
+ var ttl time.Duration
+ rlc := RateLimitResult{Limit: g.limit, RetryAfter: -1}
+ limited := false
+
+ i := 0
+ for {
+ var err error
+ var tatVal int64
+ var updated bool
+
+ // tat refers to the theoretical arrival time that would be expected
+ // from equally spaced requests at exactly the rate limit.
+ tatVal, now, err = g.store.GetWithTime(key)
+ if err != nil {
+ return false, rlc, err
+ }
+
+ if tatVal == -1 {
+ tat = now
+ } else {
+ tat = time.Unix(0, tatVal)
+ }
+
+ increment := time.Duration(quantity) * g.emissionInterval
+ if now.After(tat) {
+ newTat = now.Add(increment)
+ } else {
+ newTat = tat.Add(increment)
+ }
+
+ // Block the request if the next permitted time is in the future
+ allowAt := newTat.Add(-(g.delayVariationTolerance))
+ if diff := now.Sub(allowAt); diff < 0 {
+ if increment <= g.delayVariationTolerance {
+ rlc.RetryAfter = -diff
+ }
+ ttl = tat.Sub(now)
+ limited = true
+ break
+ }
+
+ ttl = newTat.Sub(now)
+
+ if tatVal == -1 {
+ updated, err = g.store.SetIfNotExistsWithTTL(key, newTat.UnixNano(), ttl)
+ } else {
+ updated, err = g.store.CompareAndSwapWithTTL(key, tatVal, newTat.UnixNano(), ttl)
+ }
+
+ if err != nil {
+ return false, rlc, err
+ }
+ if updated {
+ break
+ }
+
+ i++
+ if i > maxCASAttempts {
+ return false, rlc, fmt.Errorf(
+ "Failed to store updated rate limit data for key %s after %d attempts",
+ key, i,
+ )
+ }
+ }
+
+ next := g.delayVariationTolerance - ttl
+ if next > -g.emissionInterval {
+ rlc.Remaining = int(next / g.emissionInterval)
+ }
+ rlc.ResetAfter = ttl
+
+ return limited, rlc, nil
+}
diff --git a/vendor/github.com/throttled/throttled/store.go b/vendor/github.com/throttled/throttled/store.go
new file mode 100644
index 000000000..a26bbc2c5
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/store.go
@@ -0,0 +1,34 @@
+package throttled
+
+import (
+ "time"
+)
+
+// GCRAStore is the interface to implement to store state for a GCRA
+// rate limiter
+type GCRAStore interface {
+ // GetWithTime returns the value of the key if it is in the store
+ // or -1 if it does not exist. It also returns the current time at
+ // the Store. The time must be representable as a positive int64
+ // of nanoseconds since the epoch.
+ //
+ // GCRA assumes that all instances sharing the same Store also
+ // share the same clock. Using separate clocks will work if the
+ // skew is small but not recommended in practice unless you're
+ // lucky enough to be hooked up to GPS or atomic clocks.
+ GetWithTime(key string) (int64, time.Time, error)
+
+ // SetIfNotExistsWithTTL sets the value of key only if it is not
+ // already set in the store it returns whether a new value was
+ // set. If the store supports expiring keys and a new value was
+ // set, the key will expire after the provided ttl.
+ SetIfNotExistsWithTTL(key string, value int64, ttl time.Duration) (bool, error)
+
+ // CompareAndSwapWithTTL atomically compares the value at key to
+ // the old value. If it matches, it sets it to the new value and
+ // returns true. Otherwise, it returns false. If the key does not
+ // exist in the store, it returns false with no error. If the
+ // store supports expiring keys and the swap succeeded, the key
+ // will expire after the provided ttl.
+ CompareAndSwapWithTTL(key string, old, new int64, ttl time.Duration) (bool, error)
+}
diff --git a/vendor/github.com/throttled/throttled/store/memstore/memstore.go b/vendor/github.com/throttled/throttled/store/memstore/memstore.go
new file mode 100644
index 000000000..352232958
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/store/memstore/memstore.go
@@ -0,0 +1,127 @@
+// Package memstore offers an in-memory store implementation for throttled.
+package memstore // import "github.com/throttled/throttled/store/memstore"
+
+import (
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/hashicorp/golang-lru"
+)
+
+// MemStore is an in-memory store implementation for throttled. It
+// supports evicting the least recently used keys to control memory
+// usage. It is stored in memory in the current process and thus
+// doesn't share state with other rate limiters.
+type MemStore struct {
+ sync.RWMutex
+ keys *lru.Cache
+ m map[string]*int64
+}
+
+// New initializes a Store. If maxKeys > 0, the number of different
+// keys is restricted to the specified amount. In this case, it uses
+// an LRU algorithm to evict older keys to make room for newer
+// ones. If maxKeys <= 0, there is no limit on the number of keys,
+// which may use an unbounded amount of memory.
+func New(maxKeys int) (*MemStore, error) {
+ var m *MemStore
+
+ if maxKeys > 0 {
+ keys, err := lru.New(maxKeys)
+ if err != nil {
+ return nil, err
+ }
+
+ m = &MemStore{
+ keys: keys,
+ }
+ } else {
+ m = &MemStore{
+ m: make(map[string]*int64),
+ }
+ }
+ return m, nil
+}
+
+// GetWithTime returns the value of the key if it is in the store or
+// -1 if it does not exist. It also returns the current local time on
+// the machine.
+func (ms *MemStore) GetWithTime(key string) (int64, time.Time, error) {
+ now := time.Now()
+ valP, ok := ms.get(key, false)
+
+ if !ok {
+ return -1, now, nil
+ }
+
+ return atomic.LoadInt64(valP), now, nil
+}
+
+// SetIfNotExistsWithTTL sets the value of key only if it is not
+// already set in the store it returns whether a new value was set. It
+// ignores the ttl.
+func (ms *MemStore) SetIfNotExistsWithTTL(key string, value int64, _ time.Duration) (bool, error) {
+ _, ok := ms.get(key, false)
+
+ if ok {
+ return false, nil
+ }
+
+ ms.Lock()
+ defer ms.Unlock()
+
+ _, ok = ms.get(key, true)
+
+ if ok {
+ return false, nil
+ }
+
+ // Store a pointer to a new instance so that the caller
+ // can't mutate the value after setting
+ v := value
+
+ if ms.keys != nil {
+ ms.keys.Add(key, &v)
+ } else {
+ ms.m[key] = &v
+ }
+
+ return true, nil
+}
+
+// CompareAndSwapWithTTL atomically compares the value at key to the
+// old value. If it matches, it sets it to the new value and returns
+// true. Otherwise, it returns false. If the key does not exist in the
+// store, it returns false with no error. It ignores the ttl.
+func (ms *MemStore) CompareAndSwapWithTTL(key string, old, new int64, _ time.Duration) (bool, error) {
+ valP, ok := ms.get(key, false)
+
+ if !ok {
+ return false, nil
+ }
+
+ return atomic.CompareAndSwapInt64(valP, old, new), nil
+}
+
+func (ms *MemStore) get(key string, locked bool) (*int64, bool) {
+ var valP *int64
+ var ok bool
+
+ if ms.keys != nil {
+ var valI interface{}
+
+ valI, ok = ms.keys.Get(key)
+ if ok {
+ valP = valI.(*int64)
+ }
+ } else {
+ if !locked {
+ ms.RLock()
+ defer ms.RUnlock()
+ }
+ valP, ok = ms.m[key]
+ }
+
+ return valP, ok
+}
diff --git a/vendor/github.com/throttled/throttled/varyby.go b/vendor/github.com/throttled/throttled/varyby.go
new file mode 100644
index 000000000..dc6a01718
--- /dev/null
+++ b/vendor/github.com/throttled/throttled/varyby.go
@@ -0,0 +1,78 @@
+package throttled
+
+import (
+ "bytes"
+ "net/http"
+ "strings"
+)
+
+// VaryBy defines the criteria to use to group requests.
+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
+}
+
+// Key returns the key for this request based on the criteria defined by the VaryBy struct.
+func (vb *VaryBy) Key(r *http.Request) string {
+ var buf bytes.Buffer
+
+ if vb == nil {
+ return "" // Special case for no vary-by option
+ }
+ if vb.Custom != nil {
+ // A custom key generator is specified
+ return vb.Custom(r)
+ }
+ sep := vb.Separator
+ if sep == "" {
+ sep = "\n" // Separator defaults to newline
+ }
+ if vb.RemoteAddr {
+ buf.WriteString(strings.ToLower(r.RemoteAddr) + sep)
+ }
+ if vb.Method {
+ buf.WriteString(strings.ToLower(r.Method) + sep)
+ }
+ for _, h := range vb.Headers {
+ buf.WriteString(strings.ToLower(r.Header.Get(h)) + sep)
+ }
+ if vb.Path {
+ buf.WriteString(r.URL.Path + sep)
+ }
+ for _, p := range vb.Params {
+ buf.WriteString(r.FormValue(p) + sep)
+ }
+ for _, c := range vb.Cookies {
+ ck, err := r.Cookie(c)
+ if err == nil {
+ buf.WriteString(ck.Value)
+ }
+ buf.WriteString(sep) // Write the separator anyway, whether or not the cookie exists
+ }
+ return buf.String()
+}