Files

40 lines
1.4 KiB
Go

package outbound
import (
"context"
"errors"
"time"
)
// ErrInvalidRateLimitRule reports a rule without a positive window or limit,
// or a take without a key or a rule.
var ErrInvalidRateLimitRule = errors.New("invalid rate limit rule")
// RateLimitRule allows at most Limit takes per fixed Window. The window of a
// key starts with its first take and ends Window later.
type RateLimitRule struct {
Window time.Duration
Limit int64
}
// RateLimitDecision is the outcome of Take.
type RateLimitDecision struct {
// Allowed reports that the take was counted against every rule.
Allowed bool
// RetryAfter is, for a refused take, how long until every rule that
// refused it admits another one. It is zero for an allowed take.
RetryAfter time.Duration
}
// RateLimiter counts requests of one caller key against fixed windows. The
// counters are ephemeral: a restart or a flush of the store resets them, so
// a limiter is an abuse brake, never a record of what happened.
type RateLimiter interface {
// Take counts one request of key against every rule at once. It counts
// nothing when any rule refuses, so refused requests do not extend a
// window. The key is an opaque string that must not hold personal data
// in clear form; callers pass a keyed digest. A store failure returns
// an error and the caller decides how to fail.
Take(ctx context.Context, key string, rules ...RateLimitRule) (RateLimitDecision, error)
}