-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathratelimit.go
More file actions
62 lines (52 loc) · 1.42 KB
/
Copy pathratelimit.go
File metadata and controls
62 lines (52 loc) · 1.42 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
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (c) 2026 Onur Cinar.
// The source code is provided under MIT License.
// https://github.com/cinar/resile
package resile
import (
"context"
"errors"
"sync"
"time"
)
// ErrRateLimitExceeded is returned when the rate limit is exceeded.
var ErrRateLimitExceeded = errors.New("rate limit exceeded")
// RateLimiter implements a time-based token bucket rate limiter.
type RateLimiter struct {
mu sync.Mutex
limit float64
tokens float64
interval time.Duration
lastRefillAt time.Time
}
// NewRateLimiter creates a new RateLimiter with the specified limit and interval.
// Example: NewRateLimiter(100, time.Second) allows 100 requests per second.
func NewRateLimiter(limit float64, interval time.Duration) *RateLimiter {
return &RateLimiter{
limit: limit,
tokens: limit,
interval: interval,
lastRefillAt: time.Now(),
}
}
// Acquire attempts to consume a token from the bucket.
// Returns true if a token was acquired, false otherwise.
func (rl *RateLimiter) Acquire(ctx context.Context) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
elapsed := now.Sub(rl.lastRefillAt)
// Refill tokens based on elapsed time.
refill := float64(elapsed) / float64(rl.interval) * rl.limit
if refill > 0 {
rl.tokens += refill
if rl.tokens > rl.limit {
rl.tokens = rl.limit
}
rl.lastRefillAt = now
}
if rl.tokens >= 1 {
rl.tokens -= 1
return true
}
return false
}