-
Notifications
You must be signed in to change notification settings - Fork 117
/
ratelimiter.go
87 lines (64 loc) · 1.87 KB
/
ratelimiter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package ratelimit
import (
"context"
"fmt"
"math"
"github.com/go-redis/redis_rate/v10"
"github.com/redis/go-redis/v9"
)
// Limiter returns an error if quota per key is exceeded.
type Limiter interface {
Limit(ctx context.Context, limitKey string, limit redis_rate.Limit) error
}
// Redis offers rate limiting functionality using a Redis-based rate limiter.
type Redis struct {
*redis_rate.Limiter
}
func NewRedis(client *redis.Client) *Redis {
return &Redis{Limiter: redis_rate.NewLimiter(client)}
}
func (l *Redis) Limit(ctx context.Context, limitKey string, limit redis_rate.Limit) error {
if limit == Unlimited {
return nil
}
if limit.IsZero() {
return NewQuotaExceededError("Resource quota not provided")
}
rateResult, err := l.Allow(ctx, limitKey, limit)
if err != nil {
return err
}
if rateResult.Allowed == 0 {
return NewQuotaExceededError(fmt.Sprintf("Rate limit exceeded. Try again in %v seconds", rateResult.RetryAfter))
}
return nil
}
// Noop performs no rate limiting.
// This can be useful in local/testing environments or when rate limiting is not required.
type Noop struct{}
func NewNoop() *Noop {
return &Noop{}
}
func (n Noop) Limit(ctx context.Context, limitKey string, limit redis_rate.Limit) error {
return nil
}
var Default = redis_rate.PerMinute(180)
var Sensitive = redis_rate.PerMinute(30)
var Public = redis_rate.PerMinute(750)
var Unlimited = redis_rate.PerSecond(math.MaxInt)
var Zero = redis_rate.Limit{}
type QuotaExceededError struct {
message string
}
func (e QuotaExceededError) Error() string {
return e.message
}
func NewQuotaExceededError(message string) QuotaExceededError {
return QuotaExceededError{message}
}
func AuthLimitKey(methodName, authID string) string {
return fmt.Sprintf("auth:%s:%s", methodName, authID)
}
func AnonLimitKey(methodName, peer string) string {
return fmt.Sprintf("anon:%s:%s", methodName, peer)
}