-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_throttled_reader.go
101 lines (80 loc) · 1.98 KB
/
shared_throttled_reader.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package ioutils
import (
"context"
"io"
"sync"
"time"
"golang.org/x/time/rate"
)
const sharedBurstLimit = 1000 * 1000 * 1000
type SharedLimiter struct {
bytesPerSec int64
limiter *rate.Limiter
limiterMutex sync.RWMutex
}
func NewSharedLimiter(bytesPerSec int64) *SharedLimiter {
var limiter *rate.Limiter
if bytesPerSec > 0 {
limiter = rate.NewLimiter(rate.Limit(bytesPerSec), sharedBurstLimit)
limiter.AllowN(time.Now(), sharedBurstLimit) // spend initial burst
}
return &SharedLimiter{
bytesPerSec: bytesPerSec,
limiter: limiter,
}
}
func (l *SharedLimiter) WaitN(ctx context.Context, n int) (err error) {
l.limiterMutex.RLock()
limiter := l.limiter
l.limiterMutex.RUnlock()
if limiter == nil {
return nil
}
return limiter.WaitN(ctx, n)
}
func (l *SharedLimiter) GetLimit() int64 {
return l.bytesPerSec
}
func (l *SharedLimiter) SetLimit(newBytesPerSec int64) {
l.limiterMutex.Lock()
defer l.limiterMutex.Unlock()
l.bytesPerSec = newBytesPerSec
if newBytesPerSec == 0 {
l.limiter = nil
} else {
if l.limiter == nil {
l.limiter = rate.NewLimiter(rate.Limit(newBytesPerSec), sharedBurstLimit)
l.limiter.AllowN(time.Now(), sharedBurstLimit) // spend initial burst
} else {
l.limiter.SetLimit(rate.Limit(newBytesPerSec))
}
}
}
type SharedThrottledReaderLimiter interface {
WaitN(ctx context.Context, n int) error
}
type SharedThrottledReader struct {
ctx context.Context
r io.ReadCloser
limiter SharedThrottledReaderLimiter
}
func NewSharedThrottledReader(ctx context.Context, r io.ReadCloser, limiter SharedThrottledReaderLimiter) *SharedThrottledReader {
return &SharedThrottledReader{
ctx: ctx,
r: r,
limiter: limiter,
}
}
func (r *SharedThrottledReader) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p)
if err != nil {
return n, err
}
if err := r.limiter.WaitN(r.ctx, n); err != nil {
return n, err
}
return n, nil
}
func (r *SharedThrottledReader) Close() (err error) {
return r.r.Close()
}