// DEPRECATED. RateLimit creates a Throttler that conforms to the given
// rate limits
14617
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,
		},
	}
}
1087902
func RateLimited(limit int) *Notifier {
	n := &Notifier{}
	if limit > 0 {
		n.lim = ratelimit.NewRateLimiter(process.Background(), limit)
	}
	return n
}
451977
func NewLimiter(max float64, tbOptions *limiter.ExpirableOptions) *limiter.Limiter {
	return limiter.New(tbOptions).SetMax(max).SetBurst(int(math.Max(1, max)))
}
1119422
func (s *UpdateRateBasedRuleInput) SetRateLimit(v int64) *UpdateRateBasedRuleInput {
	s.RateLimit = &v
	return s
}
170049
func RateLimited(detail string, a ...interface{}) *ProblemDetails {
	return &ProblemDetails{
		Type:       RateLimitedProblem,
		Detail:     fmt.Sprintf(detail, a...),
		HTTPStatus: statusTooManyRequests,
	}
}
959420
func (o *OAuthSession) Throttle(interval time.Duration) {
	if interval == 0 {
		o.throttle = nil
		return
	}
	o.throttle = rate.New(1, interval)
}
1015963
func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) {
	v := url.Values{}
	if pageOpts.PerPage > 0 {
		v.Set("per_page", strconv.Itoa(pageOpts.PerPage))
	}
	if pageOpts.Page > 0 {
		v.Set("page", strconv.Itoa(pageOpts.Page))
	}

	uri := "/zones/" + zoneID + "/rate_limits"
	if len(v) > 0 {
		uri = uri + "?" + v.Encode()
	}

	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError)
	}

	var r rateLimitListResponse
	err = json.Unmarshal(res, &r)
	if err != nil {
		return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError)
	}
	return r.Result, r.ResultInfo, nil
}
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
}
198396
func (q *RateLimitedTimedQueue) SwapLimiter(newQPS float32) {
	q.limiterLock.Lock()
	defer q.limiterLock.Unlock()
	if q.limiter.QPS() == newQPS {
		return
	}
	var newLimiter flowcontrol.RateLimiter
	if newQPS <= 0 {
		newLimiter = flowcontrol.NewFakeNeverRateLimiter()
	} else {
		newLimiter = flowcontrol.NewTokenBucketRateLimiter(newQPS, EvictionRateLimiterBurst)

		// If we're currently waiting on limiter, we drain the new one - this is a good approach when Burst value is 1
		// TODO: figure out if we need to support higher Burst values and decide on the drain logic, should we keep:
		// - saturation (percentage of used tokens)
		// - number of used tokens
		// - number of available tokens
		// - something else
		if q.limiter.TryAccept() == false {
			newLimiter.TryAccept()
		}
	}
	q.limiter.Stop()
	q.limiter = newLimiter
}
489327
func (s *MethodSetting) SetThrottlingBurstLimit(v int64) *MethodSetting {
	s.ThrottlingBurstLimit = &v
	return s
}
130052
func (q *rateLimitingType) AddRateLimited(item interface{}) {
	q.DelayingInterface.AddAfter(item, q.rateLimiter.When(item))
}
1050658
func (r *Throttler) ThrottleAdd(ct int32) (bool, int32) {

	if r.maxPer == 0 {
		return false, 0
	}

	// http://stackoverflow.com/questions/667508/whats-a-good-rate-limiting-algorithm
	now := time.Now()
	elapsed := float64(now.Sub(r.last).Nanoseconds()) / 1e9 // seconds
	r.last = now
	r.allowance += elapsed * (r.maxPer / r.per)

	//Infof("maxRate: %v  cur: %v elapsed:%-6.6f  incr: %v", r.maxPer, int(r.allowance), elapsed, elapsed*float64(r.maxPer))
	if r.allowance > r.maxPer {
		r.allowance = r.maxPer
	}

	if r.allowance < 1.0 {
		r.count += ct        // increment throttled log count
		return true, r.count // do throttle/limit
	}

	tmpCount := r.count
	r.count = 0 // reset count

	r.allowance -= 1.0
	return false, tmpCount // dont throttle, return previous throttle count
}
899559
func newEventRateLimit(config *eventratelimitapi.Configuration, clock flowcontrol.Clock) (*Plugin, error) {
	limitEnforcers := make([]*limitEnforcer, 0, len(config.Limits))
	for _, limitConfig := range config.Limits {
		enforcer, err := newLimitEnforcer(limitConfig, clock)
		if err != nil {
			return nil, err
		}
		limitEnforcers = append(limitEnforcers, enforcer)
	}

	eventRateLimitAdmission := &Plugin{
		Handler:        admission.NewHandler(admission.Create, admission.Update),
		limitEnforcers: limitEnforcers,
	}

	return eventRateLimitAdmission, nil
}
268067
func (s *MethodSetting) SetThrottlingRateLimit(v float64) *MethodSetting {
	s.ThrottlingRateLimit = &v
	return s
}
970989
func (s *ListIPSetsInput) SetLimit(v int64) *ListIPSetsInput {
	s.Limit = &v
	return s
}
513216
func NewLimiter(defaultRates *RateSet, capacity int, mapper limit.MapperFn, configMapper ConfigMapperFn, clock timetools.TimeProvider) (*TokenLimiter, error) {
	if defaultRates == nil || len(defaultRates.m) == 0 {
		return nil, fmt.Errorf("Provide default rates")
	}
	if mapper == nil {
		return nil, fmt.Errorf("Provide mapper function")
	}

	// Set default values for optional fields.
	if capacity <= 0 {
		capacity = DefaultCapacity
	}
	if clock == nil {
		clock = &timetools.RealTime{}
	}

	bucketSets, err := ttlmap.NewMapWithProvider(DefaultCapacity, clock)
	if err != nil {
		return nil, err
	}

	return &TokenLimiter{
		defaultRates: defaultRates,
		mapper:       mapper,
		configMapper: configMapper,
		clock:        clock,
		bucketSets:   bucketSets,
	}, nil
}
1011357
func (r *Request) Throttle(limiter flowcontrol.RateLimiter) *Request {
	r.throttle = limiter
	return r
}