// new Throttler that will tell you to limit or not based
// on given @max events @per duration
191176
func NewThrottler(max int, per time.Duration) *Throttler {
	return &Throttler{
		maxPer:    float64(max),
		allowance: float64(max),
		count:     int32(0),
		last:      time.Now(),
		per:       per.Seconds(),
	}
}
462334
func (_m *DBClient) IntervalActionsWithLimit(limit int) ([]models.IntervalAction, error) {
	ret := _m.Called(limit)

	var r0 []models.IntervalAction
	if rf, ok := ret.Get(0).(func(int) []models.IntervalAction); ok {
		r0 = rf(limit)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.IntervalAction)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(int) error); ok {
		r1 = rf(limit)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
343634
func NewRateLimiter(config LimiterConfig) (*RateLimiter, error) {
	limiter := RateLimiter{
		Mutex: &sync.Mutex{},
	}

	ipExtractor, err := utils.NewExtractor("client.ip")
	if err != nil {
		return nil, trace.Wrap(err)
	}

	limiter.rates = ratelimit.NewRateSet()
	for _, rate := range config.Rates {
		err := limiter.rates.Add(rate.Period, rate.Average, rate.Burst)
		if err != nil {
			return nil, trace.Wrap(err)
		}
	}
	if len(config.Rates) == 0 {
		err := limiter.rates.Add(time.Second, DefaultRate, DefaultRate)
		if err != nil {
			return nil, trace.Wrap(err)
		}
	}

	if config.Clock == nil {
		config.Clock = &timetools.RealTime{}
	}
	limiter.clock = config.Clock

	limiter.TokenLimiter, err = ratelimit.New(nil, ipExtractor,
		limiter.rates, ratelimit.Clock(config.Clock))
	if err != nil {
		return nil, trace.Wrap(err)
	}

	maxNumberOfUsers := config.MaxNumberOfUsers
	if maxNumberOfUsers <= 0 {
		maxNumberOfUsers = DefaultMaxNumberOfUsers
	}
	limiter.rateLimits, err = ttlmap.NewMap(
		maxNumberOfUsers, ttlmap.Clock(config.Clock))
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return &limiter, nil
}
820994
func throttledFn(threshold int64, f http.HandlerFunc) http.Handler {
	return throttled(threshold, f)
}
105285
func NewThrottledLogger(name string, maxInterval time.Duration) *ThrottledLogger {
	return &ThrottledLogger{
		name:        name,
		maxInterval: maxInterval,
	}
}
141375
func (m *managerImpl) MaxRates() map[string]int64 {
	m.mu.Lock()
	defer m.mu.Unlock()

	rates := make(map[string]int64, len(m.throttlers))
	for name, t := range m.throttlers {
		rates[name] = t.MaxRate()
	}
	return rates
}
549604
func NewTokenBucketRateLimiterWithClock(qps float32, burst int, c Clock) RateLimiter {
	limiter := rate.NewLimiter(rate.Limit(qps), burst)
	return newTokenBucketRateLimiter(limiter, c, qps)
}
471361
func (lim *limiter) setLimitsLocked(device config.DeviceConfiguration) bool {
	readLimiter := lim.getReadLimiterLocked(device.DeviceID)
	writeLimiter := lim.getWriteLimiterLocked(device.DeviceID)

	// limiters for this device are created so we can store previous rates for logging
	previousReadLimit := readLimiter.Limit()
	previousWriteLimit := writeLimiter.Limit()
	currentReadLimit := rate.Limit(device.MaxRecvKbps) * 1024
	currentWriteLimit := rate.Limit(device.MaxSendKbps) * 1024
	if device.MaxSendKbps <= 0 {
		currentWriteLimit = rate.Inf
	}
	if device.MaxRecvKbps <= 0 {
		currentReadLimit = rate.Inf
	}
	// Nothing about this device has changed. Start processing next device
	if previousWriteLimit == currentWriteLimit && previousReadLimit == currentReadLimit {
		return false
	}

	readLimiter.SetLimit(currentReadLimit)
	writeLimiter.SetLimit(currentWriteLimit)

	return true
}
74316
func NewRateLimiter(bandwidth float64) *RateLimiter {
	//  convert bandwidth to bytes per nanosecond
	b := bandwidth / float64(time.Second)
	return &RateLimiter{
		bandwidth:    b,
		allowance:    0,
		maxAllowance: bandwidth,
		lastUpdate:   time.Now(),
	}
}
130052
func (q *rateLimitingType) AddRateLimited(item interface{}) {
	q.DelayingInterface.AddAfter(item, q.rateLimiter.When(item))
}
705731
func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
	attemptCh := make(chan int)

	// computes the exponential backoff duration according to
	// https://www.awsarchitectureblog.com/2015/03/backoff.html
	exponentialBackoffWait := func(attempt int) time.Duration {
		// normalize jitter to the range [0, 1.0]
		if jitter < NoJitter {
			jitter = NoJitter
		}
		if jitter > MaxJitter {
			jitter = MaxJitter
		}

		//sleep = random_between(0, min(cap, base * 2 ** attempt))
		sleep := unit * time.Duration(1<<uint(attempt))
		if sleep > cap {
			sleep = cap
		}
		if jitter != NoJitter {
			sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter)
		}
		return sleep
	}

	go func() {
		defer close(attemptCh)
		for i := 0; i < maxRetry; i++ {
			select {
			// Attempts start from 1.
			case attemptCh <- i + 1:
			case <-doneCh:
				// Stop the routine.
				return
			}
			time.Sleep(exponentialBackoffWait(i))
		}
	}()
	return attemptCh
}
1008102
func MaxDuration(a, b time.Duration) time.Duration {
	if a > b {
		return a
	}
	return b
}
1164906
func RateLimit(period time.Duration, limit int) RateLimiter {
	store := memory.NewStore()
	rate := limiter.Rate{
		Period: period,
		Limit:  int64(limit),
	}

	lmt := limiter.New(store, rate)
	middleware := stdlib.NewMiddleware(lmt, stdlib.WithForwardHeader(true))
	middleware.OnLimitReached = func(w http.ResponseWriter, r *http.Request) {
		// Get the clients ip address.
		ipString := r.RemoteAddr
		// Account for proxies.
		if forwardString := r.Header.Get("X-Forwarded-For"); forwardString != "" {
			ipString = forwardString
		}
		// Cloudflare creates a special ipv6 address if the client uses ipv6,
		// so check for the appropriate header
		// We will rate limit on this special ipv4 address, but this is not a problem
		// as Cloudflare maps these special addresses to the underlying ipv6 address
		// in a one on one relationship
		if ipv6 := r.Header.Get("Cf-Connecting-Ipv6"); ipv6 != "" {
			ipString = ipv6
		}
		log.Info("Rate limiting request from: ", ipString)

		// Write some info back to the client
		w.WriteHeader(http.StatusTooManyRequests)
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte("You have reached the maximum request limit."))
		return
	}
	return RateLimiter{middleware}

}
530872
func (r *RateLimiter) Limit(dataSize int) time.Duration {
	r.lock.Lock()
	defer r.lock.Unlock()
	//  update time
	var duration time.Duration = time.Duration(0)
	if r.bandwidth == 0 {
		return duration
	}
	current := time.Now()
	elapsedTime := current.Sub(r.lastUpdate)
	r.lastUpdate = current

	allowance := r.allowance + float64(elapsedTime)*r.bandwidth
	//  allowance can't exceed bandwidth
	if allowance > r.maxAllowance {
		allowance = r.maxAllowance
	}

	allowance -= float64(dataSize)
	if allowance < 0 {
		//  sleep until allowance is back to 0
		duration = time.Duration(-allowance / r.bandwidth)
		//  rate limiting was applied, record stats
		r.count++
		r.duration += duration
	}

	r.allowance = allowance
	return duration
}
250876
func WithLimitReachedHandler(handler LimitReachedHandler) Option {
	return option(func(middleware *Middleware) {
		middleware.OnLimitReached = handler
	})
}
785746
func NewLimitIterator(ctx Context, source RankIterator, limit int, scoreThreshold float64, maxSkip int) *LimitIterator {
	iter := &LimitIterator{
		ctx:            ctx,
		source:         source,
		limit:          limit,
		maxSkip:        maxSkip,
		scoreThreshold: scoreThreshold,
		skippedNodes:   make([]*RankedNode, 0, maxSkip),
	}
	return iter
}
1326731
func (s *Server) MaxRates(_ context.Context, request *throttlerdatapb.MaxRatesRequest) (_ *throttlerdatapb.MaxRatesResponse, err error) {
	defer servenv.HandlePanic("throttler", &err)

	rates := s.manager.MaxRates()
	return &throttlerdatapb.MaxRatesResponse{
		Rates: rates,
	}, nil
}