-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratelimit.go
More file actions
50 lines (42 loc) · 1.24 KB
/
ratelimit.go
File metadata and controls
50 lines (42 loc) · 1.24 KB
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
package cachegrid
import (
"time"
"github.com/skshohagmiah/cachegrid/internal/ratelimit"
)
// RateLimitOptions configures token bucket rate limiting.
type RateLimitOptions struct {
Limit int64
Window time.Duration
}
// SlidingWindowOptions configures sliding window rate limiting.
type SlidingWindowOptions struct {
Limit int64
Window time.Duration
}
// RateLimitState is the public rate limit response.
type RateLimitState struct {
Allowed bool
Remaining int64
Limit int64
ResetsAt time.Time
}
func stateFromInternal(s ratelimit.State) RateLimitState {
return RateLimitState{
Allowed: s.Allowed,
Remaining: s.Remaining,
Limit: s.Limit,
ResetsAt: s.ResetsAt,
}
}
// RateLimit checks a token bucket rate limiter for the given key.
func (c *Cache) RateLimit(key string, opts RateLimitOptions) (bool, RateLimitState) {
s := c.tokenBucket.Allow(key, opts.Limit, opts.Window)
state := stateFromInternal(s)
return state.Allowed, state
}
// RateLimitSliding checks a sliding window rate limiter for the given key.
func (c *Cache) RateLimitSliding(key string, opts SlidingWindowOptions) (bool, RateLimitState) {
s := c.slidingWindow.Allow(key, opts.Limit, opts.Window)
state := stateFromInternal(s)
return state.Allowed, state
}