-
Notifications
You must be signed in to change notification settings - Fork 656
/
util.go
92 lines (72 loc) · 1.38 KB
/
util.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
package goflyway
import (
"net"
"strings"
"sync"
"time"
)
func isClosedConnErr(err error) bool {
return strings.Contains(err.Error(), "use of closed")
}
func isTimeoutErr(err error) bool {
if ne, ok := err.(net.Error); ok {
return ne.Timeout()
}
return false
}
type TokenBucket struct {
Speed int64 // bytes per second
capacity int64 // bytes
maxCapacity int64
lastConsume time.Time
mu sync.Mutex
}
func NewTokenBucket(speed, max int64) *TokenBucket {
return &TokenBucket{
Speed: speed,
lastConsume: time.Now(),
maxCapacity: max,
}
}
func (tb *TokenBucket) Consume(n int64) {
tb.mu.Lock()
defer tb.mu.Unlock()
now := time.Now()
if tb.Speed == 0 {
tb.lastConsume = now
return
}
ms := now.Sub(tb.lastConsume).Nanoseconds() / 1e6
tb.capacity += ms * tb.Speed / 1000
if tb.capacity > tb.maxCapacity {
tb.capacity = tb.maxCapacity
}
if n <= tb.capacity {
tb.lastConsume = now
tb.capacity -= n
return
}
sec := float64(n-tb.capacity) / float64(tb.Speed)
time.Sleep(time.Duration(sec*1000) * time.Millisecond)
tb.capacity = 0
tb.lastConsume = time.Now()
}
type Traffic struct {
sent int64
received int64
}
func (t *Traffic) Set(s, r int64) {
t.sent, t.received = s, r
}
func (t *Traffic) Sent() *int64 {
if t == nil {
return nil
}
return &t.sent
}
func (t *Traffic) Recv() *int64 {
if t == nil {
return nil
}
return &t.received
}