-
Notifications
You must be signed in to change notification settings - Fork 0
/
limit.go
60 lines (54 loc) · 1.27 KB
/
limit.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
package limit
import (
"context"
"time"
"go-common/library/container/queue/aqm"
"go-common/library/log"
"go-common/library/rate"
"go-common/library/rate/vegas"
)
var _ rate.Limiter = &Limiter{}
// New returns a new Limiter that allows events up to adaptive rtt.
func New(c *aqm.Config) *Limiter {
l := &Limiter{
rate: vegas.New(),
queue: aqm.New(c),
}
go func() {
ticker := time.NewTicker(time.Second * 1)
defer ticker.Stop()
for {
<-ticker.C
v := l.rate.Stat()
q := l.queue.Stat()
log.Info("rate/limit: limit(%d) inFlight(%d) minRtt(%v) rtt(%v) codel packets(%d)", v.Limit, v.InFlight, v.MinRTT, v.LastRTT, q.Packets)
}
}()
return l
}
// Limiter use tcp vegas + codel for adaptive limit.
type Limiter struct {
rate *vegas.Vegas
queue *aqm.Queue
}
// Allow immplemnet rate.Limiter.
// if error is returned,no need to call done()
func (l *Limiter) Allow(ctx context.Context) (func(rate.Op), error) {
var (
done func(time.Time, rate.Op)
err error
ok bool
)
if done, ok = l.rate.Acquire(); !ok {
// NOTE exceed max inflight, use queue
if err = l.queue.Push(ctx); err != nil {
done(time.Time{}, rate.Ignore)
return func(rate.Op) {}, err
}
}
start := time.Now()
return func(op rate.Op) {
done(start, op)
l.queue.Pop()
}, nil
}