-
Notifications
You must be signed in to change notification settings - Fork 242
/
stats.go
118 lines (98 loc) · 2.39 KB
/
stats.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package common
import (
"sync"
"time"
"github.com/ethereum/go-ethereum/rlp"
"github.com/status-im/status-go/eth-node/types"
)
type Measure struct {
Timestamp int64
Size uint64
}
type StatsTracker struct {
Uploads []Measure
Downloads []Measure
statsMutex sync.Mutex
}
const measurementPeriod = 15 * time.Second
func measure(input interface{}) (*Measure, error) {
b, err := rlp.EncodeToBytes(input)
if err != nil {
return nil, err
}
return &Measure{
Timestamp: time.Now().UnixNano(),
Size: uint64(len(b)),
}, nil
}
func (s *StatsTracker) AddUpload(input interface{}) {
go func(input interface{}) {
m, err := measure(input)
if err != nil {
return
}
s.statsMutex.Lock()
defer s.statsMutex.Unlock()
s.Uploads = append(s.Uploads, *m)
}(input)
}
func (s *StatsTracker) AddDownload(input interface{}) {
go func(input interface{}) {
m, err := measure(input)
if err != nil {
return
}
s.statsMutex.Lock()
defer s.statsMutex.Unlock()
s.Downloads = append(s.Downloads, *m)
}(input)
}
func (s *StatsTracker) AddUploadBytes(size uint64) {
go func(size uint64) {
m := Measure{
Timestamp: time.Now().UnixNano(),
Size: size,
}
s.statsMutex.Lock()
defer s.statsMutex.Unlock()
s.Uploads = append(s.Uploads, m)
}(size)
}
func (s *StatsTracker) AddDownloadBytes(size uint64) {
go func(size uint64) {
m := Measure{
Timestamp: time.Now().UnixNano(),
Size: size,
}
s.statsMutex.Lock()
defer s.statsMutex.Unlock()
s.Downloads = append(s.Downloads, m)
}(size)
}
func calculateAverage(measures []Measure, minTime int64) (validMeasures []Measure, rate uint64) {
for _, m := range measures {
if m.Timestamp > minTime {
// Only use recent measures
validMeasures = append(validMeasures, m)
rate += m.Size
}
}
rate /= (uint64(measurementPeriod) / uint64(1*time.Second))
return
}
func (s *StatsTracker) GetRatePerSecond() (uploadRate uint64, downloadRate uint64) {
s.statsMutex.Lock()
defer s.statsMutex.Unlock()
minTime := time.Now().Add(-measurementPeriod).UnixNano()
s.Uploads, uploadRate = calculateAverage(s.Uploads, minTime)
s.Downloads, downloadRate = calculateAverage(s.Downloads, minTime)
return
}
func (s *StatsTracker) GetStats() types.StatsSummary {
uploadRate, downloadRate := s.GetRatePerSecond()
summary := types.StatsSummary{
UploadRate: uploadRate,
DownloadRate: downloadRate,
}
return summary
}