// NewRateLimiter returns new request rate controller
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
}
292107
func NewLimiter(config LimiterConfig) (*Limiter, error) {
	var err error
	limiter := Limiter{}

	limiter.ConnectionsLimiter, err = NewConnectionsLimiter(config)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	limiter.rateLimiter, err = NewRateLimiter(config)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return &limiter, nil
}
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
}
953884
func RateLimitedReader(r io.Reader, size int, duration time.Duration) io.ReadCloser {
	rl := &rateLimiter{
		action: func(p []byte) (int, error) {
			return r.Read(p)
		},
		limit:     size,
		remaining: size,
		stop:      make(chan bool),
		worker:    make(chan *operation),
	}
	go rl.run(duration)
	return rl
}
613643
func (s *nodeStore) CheckRateLimit(id string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if existRn, ok := s.nodes[id]; ok {
		if time.Since(existRn.Registered) > s.rateLimitPeriod {
			existRn.Attempts = 0
		}
		existRn.Attempts++
		if existRn.Attempts > rateLimitCount {
			return status.Errorf(codes.Unavailable, "node %s exceeded rate limit count of registrations", id)
		}
		existRn.Registered = time.Now()
	}
	return nil
}
693704
func NewRateLimitedSMSService(window int, maxSMS int, actualService SMSService) SMSService {
	return &RateLimitedSMSService{
		actualService: actualService,
		window:        time.Duration(int(time.Second) * window),
		maxSMS:        maxSMS,
	}
}
354021
func (r *RateLimit) NewHandler(next http.Handler) (http.Handler, error) {
	defaultRates := ratelimit.NewRateSet()
	if err := defaultRates.Add(time.Duration(r.PeriodSeconds)*time.Second, r.Requests, r.Burst); err != nil {
		return nil, err
	}
	return ratelimit.New(next, r.extract, defaultRates,
		ratelimit.ExtractRates(r.extractRates), ratelimit.Clock(r.clock))
}
862652
func (rl *RateLimiter) Limit() bool {
	// Calculate the number of ns that have passed since our last call
	now := unixNano()
	passed := now - atomic.SwapUint64(&rl.lastCheck, now)

	// Add them to our allowance
	rate := atomic.LoadUint64(&rl.rate)
	current := atomic.AddUint64(&rl.allowance, passed*rate)

	// Ensure our allowance is not over maximum
	if max := atomic.LoadUint64(&rl.max); current > max {
		atomic.AddUint64(&rl.allowance, max-current)
		current = max
	}

	// If our allowance is less than one unit, rate-limit!
	if current < rl.unit {
		return true
	}

	// Not limited, subtract a unit
	atomic.AddUint64(&rl.allowance, -rl.unit)
	return false
}
911308
func (opts ScheduledImageStreamControllerOptions) GetRateLimiter() flowcontrol.RateLimiter {
	if opts.MaxImageImportsPerMinute <= 0 {
		return flowcontrol.NewFakeAlwaysRateLimiter()
	}

	importRate := float32(opts.MaxImageImportsPerMinute) / float32(time.Minute/time.Second)
	importBurst := opts.MaxImageImportsPerMinute * 2
	return flowcontrol.NewTokenBucketRateLimiter(importRate, importBurst)
}
551714
func NewLimiter(opts LimiterOpts) Limiter {
	if opts.RequestsPerSecond <= 0 {
		panic("RequestsPerSecond must be > 0")
	}

	c := make(chan struct{}, opts.Burst)
	l := &limiter{
		c:        c,
		interval: time.Duration(1.0 / float64(opts.RequestsPerSecond) * float64(time.Second)),
	}
	go l.run()
	return l
}
193693
func New(ctx context.Context, next http.Handler, config config.RateLimit, name string) (http.Handler, error) {
	middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")

	extractFunc, err := utils.NewExtractor(config.ExtractorFunc)
	if err != nil {
		return nil, err
	}

	rateSet := ratelimit.NewRateSet()
	for _, rate := range config.RateSet {
		if err = rateSet.Add(time.Duration(rate.Period), rate.Average, rate.Burst); err != nil {
			return nil, err
		}
	}

	rl, err := ratelimit.New(next, extractFunc, rateSet)
	if err != nil {
		return nil, err
	}
	return &rateLimiter{handler: rl, name: name}, nil
}
1285430
func (s *RemotelyControlledSampler) updateRateLimitingOrProbabilisticSampler(res *sampling.SamplingStrategyResponse) error {
	var newSampler Sampler
	if probabilistic := res.GetProbabilisticSampling(); probabilistic != nil {
		newSampler = newProbabilisticSampler(probabilistic.SamplingRate)
	} else if rateLimiting := res.GetRateLimitingSampling(); rateLimiting != nil {
		newSampler = NewRateLimitingSampler(float64(rateLimiting.MaxTracesPerSecond))
	} else {
		return fmt.Errorf("Unsupported sampling strategy type %v", res.GetStrategyType())
	}
	if !s.sampler.Equal(newSampler) {
		s.sampler = newSampler
	}
	return nil
}
268067
func (s *MethodSetting) SetThrottlingRateLimit(v float64) *MethodSetting {
	s.ThrottlingRateLimit = &v
	return s
}
466272
func IsRateLimit(err error) bool {
	re, ok := err.(rateLimitError)
	return ok && re.IsRateLimit()
}
1304633
func New(operationsPerSecond float64) ratecontroller.Controller {
	return &fixedRateController{opsPerSecond: operationsPerSecond, replayStartTime: time.Now()}
}
1119832
func NewRateLimitError(Reason *RateLimitReason) *RateLimitError {
	s := new(RateLimitError)
	s.Reason = Reason
	s.RetryAfter = 1
	return s
}
757977
func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) {
	pageOpts := PaginationOptions{
		PerPage: 100, // this is the max page size allowed
		Page:    1,
	}

	allRateLimits := make([]RateLimit, 0)
	for {
		rateLimits, resultInfo, err := api.ListRateLimits(zoneID, pageOpts)
		if err != nil {
			return []RateLimit{}, err
		}
		allRateLimits = append(allRateLimits, rateLimits...)
		// total pages is not returned on this call
		// if number of records is less than the max, this must be the last page
		// in case TotalCount % PerPage = 0, the last request will return an empty list
		if resultInfo.Count < resultInfo.PerPage {
			break
		}
		// continue with the next page
		pageOpts.Page = pageOpts.Page + 1
	}

	return allRateLimits, nil
}