// NewLimiter returns a new Limiter configured
// to only allow rps requests per seconds.
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
}
432809
func (p Proc) NewLimits() (ProcLimits, error) {
	f, err := os.Open(p.path("limits"))
	if err != nil {
		return ProcLimits{}, err
	}
	defer f.Close()

	var (
		l = ProcLimits{}
		s = bufio.NewScanner(f)
	)
	for s.Scan() {
		fields := limitsDelimiter.Split(s.Text(), limitsFields)
		if len(fields) != limitsFields {
			return ProcLimits{}, fmt.Errorf(
				"couldn't parse %s line %s", f.Name(), s.Text())
		}

		switch fields[0] {
		case "Max cpu time":
			l.CPUTime, err = parseInt(fields[1])
		case "Max file size":
			l.FileSize, err = parseInt(fields[1])
		case "Max data size":
			l.DataSize, err = parseInt(fields[1])
		case "Max stack size":
			l.StackSize, err = parseInt(fields[1])
		case "Max core file size":
			l.CoreFileSize, err = parseInt(fields[1])
		case "Max resident set":
			l.ResidentSet, err = parseInt(fields[1])
		case "Max processes":
			l.Processes, err = parseInt(fields[1])
		case "Max open files":
			l.OpenFiles, err = parseInt(fields[1])
		case "Max locked memory":
			l.LockedMemory, err = parseInt(fields[1])
		case "Max address space":
			l.AddressSpace, err = parseInt(fields[1])
		case "Max file locks":
			l.FileLocks, err = parseInt(fields[1])
		case "Max pending signals":
			l.PendingSignals, err = parseInt(fields[1])
		case "Max msgqueue size":
			l.MsqqueueSize, err = parseInt(fields[1])
		case "Max nice priority":
			l.NicePriority, err = parseInt(fields[1])
		case "Max realtime priority":
			l.RealtimePriority, err = parseInt(fields[1])
		case "Max realtime timeout":
			l.RealtimeTimeout, err = parseInt(fields[1])
		}
		if err != nil {
			return ProcLimits{}, err
		}
	}

	return l, s.Err()
}
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,
		},
	}
}
591753
func NewRatelimiter() *RateLimiter {

	return &RateLimiter{
		buckets: make(map[string]*Bucket),
		global:  new(int64),
		customRateLimits: []*customRateLimit{
			&customRateLimit{
				suffix:   "//reactions//",
				requests: 1,
				reset:    200 * time.Millisecond,
			},
		},
	}
}
412770
func NewReader(r io.Reader, limiter Limiter) io.Reader {
	return &reader{r, limiter}
}
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
}
345395
func New(rate int, per time.Duration) *RateLimiter {
	nano := uint64(per)
	if nano < 1 {
		nano = uint64(time.Second)
	}
	if rate < 1 {
		rate = 1
	}

	return &RateLimiter{
		rate:      uint64(rate),        // store the rate
		allowance: uint64(rate) * nano, // set our allowance to max in the beginning
		max:       uint64(rate) * nano, // remember our maximum allowance
		unit:      nano,                // remember our unit size

		lastCheck: unixNano(),
	}
}
1087902
func RateLimited(limit int) *Notifier {
	n := &Notifier{}
	if limit > 0 {
		n.lim = ratelimit.NewRateLimiter(process.Background(), limit)
	}
	return n
}
1172507
func LimitWriter(w io.Writer, n int64) io.Writer {
	return &limitedWriter{W: w, N: n}
}
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
}
751064
func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter {
	if c == nil {
		return nil
	}
	return c.Throttle
}
576931
func (dl *downloader) rateLimit(ctx context.Context, f func() error) error {
	const (
		msgRateLimitExceeded          = "Rate Limit Exceeded"
		msgUserRateLimitExceeded      = "User Rate Limit Exceeded"
		msgUserRateLimitExceededShort = "userRateLimitExceeded"
	)

	// Ensure a 1 minute try limit.
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	for {
		if err := dl.rate.Wait(ctx); err != nil {
			log.Printf("gphotos: rate limit failure: %v", err)
			return err
		}
		err := f()
		if err == nil {
			return nil
		}
		ge, ok := err.(*googleapi.Error)
		if !ok || ge.Code != 403 {
			return err
		}
		if ge.Message == "" {
			var ok bool
			for _, e := range ge.Errors {
				if ok = e.Reason == msgUserRateLimitExceededShort; ok {
					break
				}
			}
			// For some cases, googleapi does not parse the returned JSON
			// properly, so we have to fall back to check the original text.
			//
			// Usually this is a "User Rate Limit Exceeded", but that's
			// also a "Rate Limit Exceeded", and we're interested just in the
			// fact, not the cause.
			if !ok && !strings.Contains(ge.Body, msgRateLimitExceeded) {
				return err
			}
		}
		// Some arbitrary sleep.
		log.Printf("gphotos: sleeping for 5s after 403 error, presumably due to a rate limit")
		time.Sleep(5 * time.Second)
		log.Printf("gphotos: retrying after sleep...")
	}
}
927013
func (c *Client) SetLimiter(rateLimit float64, burst int) {
	c.modifyLock.RLock()
	c.config.modifyLock.Lock()
	defer c.config.modifyLock.Unlock()
	c.modifyLock.RUnlock()

	c.config.Limiter = rate.NewLimiter(rate.Limit(rateLimit), burst)
}
370945
func newLimitRanges(c *CoreV1Client, namespace string) *limitRanges {
	return &limitRanges{
		client: c.RESTClient(),
		ns:     namespace,
	}
}
1105838
func New(max int64, ttl time.Duration) *config.Limiter {
	return config.NewLimiter(max, ttl)
}
110048
func LimitHandler(lmt *limiter.Limiter, next http.Handler) http.Handler {
	middle := func(w http.ResponseWriter, r *http.Request) {
		httpError := LimitByRequest(lmt, w, r)
		if httpError != nil {
			lmt.ExecOnLimitReached(w, r)
			w.Header().Add("Content-Type", lmt.GetMessageContentType())
			w.WriteHeader(httpError.StatusCode)
			w.Write([]byte(httpError.Message))
			return
		}

		// There's no rate-limit error, serve the next handler.
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(middle)
}
934811
func New() *Limiter {
	return &Limiter{
		buckets: make(map[string]*Bucket),
		m:       &sync.Mutex{},
	}
}