// RateLimited returns a ProblemDetails representing a RateLimitedProblem error
170049
func RateLimited(detail string, a ...interface{}) *ProblemDetails {
	return &ProblemDetails{
		Type:       RateLimitedProblem,
		Detail:     fmt.Sprintf(detail, a...),
		HTTPStatus: statusTooManyRequests,
	}
}
1309656
func rateLimitExceeded(err *googleapi.Error) bool {
	for _, err := range err.Errors {
		if strings.Contains(err.Message, "Rate Limit Exceeded") {
			return true
		}
	}
	return false
}
931569
func (m *RateLimit) Validate() error {
	if m == nil {
		return nil
	}

	if wrapper := m.GetStage(); wrapper != nil {

		if wrapper.GetValue() > 10 {
			return RateLimitValidationError{
				field:  "Stage",
				reason: "value must be less than or equal to 10",
			}
		}

	}

	// no validation rules for DisableKey

	if len(m.GetActions()) < 1 {
		return RateLimitValidationError{
			field:  "Actions",
			reason: "value must contain at least 1 item(s)",
		}
	}

	for idx, item := range m.GetActions() {
		_, _ = idx, item

		{
			tmp := item

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return RateLimitValidationError{
						field:  fmt.Sprintf("Actions[%v]", idx),
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	}

	return nil
}
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(),
	}
}
186752
func (s *RateBasedRule) SetRateLimit(v int64) *RateBasedRule {
	s.RateLimit = &v
	return s
}
206483
func RateLimitedWriter(w io.Writer, size int, duration time.Duration) io.WriteCloser {
	rl := &rateLimiter{
		action: func(p []byte) (int, error) {
			return w.Write(p)
		},
		limit:     size,
		remaining: size,
		stop:      make(chan bool),
		worker:    make(chan *operation),
	}
	go rl.run(duration)
	return rl
}
87640
func (c *Client) RateLimitInfo() (*RateLimit, error) {
	var rateLimit RateLimit
	return &rateLimit, c.Get(&rateLimit, "/account/rate-limits")
}
1368862
func (t *Throttler) Throttle(h http.Handler) http.Handler {
	return t.RateLimit(h)
}
1279199
func (l *Limiter) ResetRate(name string, rateLimit rate.Limit) error {
	if rateLimit == 0 {
		return nil
	}
	if rateLimit == rate.Inf {
		return nil
	}

	_, period := limitPeriod(rateLimit)
	slot := time.Now().UnixNano() / period.Nanoseconds()

	name = allowRateName(name, period, slot)
	return l.redis.Del(name).Err()
}
416698
func (r *Response) RateLimitReset() time.Time {
	value, _ := strconv.ParseInt(r.HttpResponse.Header.Get("X-RateLimit-Reset"), 10, 64)
	return time.Unix(value, 0)
}
1209499
func (l *Limiter) AllowRate(name string, rateLimit rate.Limit) (delay time.Duration, allow bool) {
	if rateLimit == 0 {
		return 0, false
	}
	if rateLimit == rate.Inf {
		return 0, true
	}

	limit, period := limitPeriod(rateLimit)
	now := time.Now()
	slot := now.UnixNano() / period.Nanoseconds()

	name = allowRateName(name, period, slot)
	count, err := l.incr(name, period, 1)
	if err == nil {
		allow = count <= limit
	} else if l.Fallback != nil {
		allow = l.Fallback.Allow()
	}

	if !allow {
		delay = time.Duration(slot+1)*period - time.Duration(now.UnixNano())
	}

	return delay, allow
}
151421
func (c *Client) RateLimits(ctx context.Context) (*RateLimits, *Response, error) {
	req, err := c.NewRequest("GET", "rate_limit", nil)
	if err != nil {
		return nil, nil, err
	}

	response := new(struct {
		Resources *RateLimits `json:"resources"`
	})
	resp, err := c.Do(ctx, req, response)
	if err != nil {
		return nil, nil, err
	}

	if response.Resources != nil {
		c.rateMu.Lock()
		if response.Resources.Core != nil {
			c.rateLimits[coreCategory] = *response.Resources.Core
		}
		if response.Resources.Search != nil {
			c.rateLimits[searchCategory] = *response.Resources.Search
		}
		c.rateMu.Unlock()
	}

	return response.Resources, resp, nil
}
562740
func (r *RateLimitedLogger) Disabled() bool {
	now := r.now()
	return r.EventCounter.Events(now, 0) > r.Limit || IsDisabled(r.Logger)
}
1278819
func (rl *RateLimiter) Allow() bool {
	rl.mu.Lock()
	defer rl.mu.Unlock()
	if time.Since(rl.lastTime) < rl.interval {
		if rl.curCount > 0 {
			rl.curCount--
			return true
		}
		return false
	}
	rl.curCount = rl.maxCount - 1
	rl.lastTime = time.Now()
	return true
}
343302
func (c *CmdChatSetRetention) parseEphemeralAgeLimited(s string) (gregor1.DurationSec, error) {
	var d time.Duration
	var err error
	switch s {
	case "30s",
		"5m",
		"1h",
		"6h":
		d, err = time.ParseDuration(s)
	case "1d", "24h":
		d = 24 * time.Hour
	case "3d":
		d = 3 * 24 * time.Hour
	case "7d", "1w":
		d = 7 * 24 * time.Hour
	default:
		return 0, fmt.Errorf("invalid expiration age: %v", s)
	}
	return gregor1.DurationSec(d.Seconds()), 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,
		},
	}
}
453525
func (conn *Conn) rateLimit(chars int) time.Duration {
	// Hybrid's algorithm allows for 2 seconds per line and an additional
	// 1/120 of a second per character on that line.
	linetime := 2*time.Second + time.Duration(chars)*time.Second/120
	elapsed := time.Now().Sub(conn.lastsent)
	if conn.badness += linetime - elapsed; conn.badness < 0 {
		// negative badness times are badness...
		conn.badness = 0
	}
	conn.lastsent = time.Now()
	// If we've sent more than 10 second's worth of lines according to the
	// calculation above, then we're at risk of "Excess Flood".
	if conn.badness > 10*time.Second {
		return linetime
	}
	return 0
}