-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetricsReadWriter.go
57 lines (49 loc) · 1.39 KB
/
metricsReadWriter.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
package p2p
import (
"io"
"sync/atomic"
)
type StatsCollector interface {
Collect() (mw uint64, mr uint64, bw uint64, br uint64)
}
type ReadWriteCollector interface {
io.Reader
io.Writer
StatsCollector
}
// MetricsReadWriter is a wrapper for net.Conn that allows the package to
// observe the actual amount of bytes passing through it
type MetricsReadWriter struct {
rw io.ReadWriter
messagesWritten uint64
messagesRead uint64
bytesWritten uint64
bytesRead uint64
}
var _ StatsCollector = (*MetricsReadWriter)(nil)
var _ ReadWriteCollector = (*MetricsReadWriter)(nil)
var _ io.ReadWriter = (*MetricsReadWriter)(nil)
func NewMetricsReadWriter(rw io.ReadWriter) *MetricsReadWriter {
sc := new(MetricsReadWriter)
sc.rw = rw
return sc
}
func (sc *MetricsReadWriter) Write(p []byte) (int, error) {
n, e := sc.rw.Write(p)
atomic.AddUint64(&sc.messagesWritten, 1)
atomic.AddUint64(&sc.bytesWritten, uint64(n))
return n, e
}
func (sc *MetricsReadWriter) Read(p []byte) (int, error) {
n, e := sc.rw.Read(p)
atomic.AddUint64(&sc.messagesRead, 1)
atomic.AddUint64(&sc.bytesRead, uint64(n))
return n, e
}
func (sc *MetricsReadWriter) Collect() (mw uint64, mr uint64, bw uint64, br uint64) {
mw = atomic.SwapUint64(&sc.messagesWritten, 0)
mr = atomic.SwapUint64(&sc.messagesRead, 0)
bw = atomic.SwapUint64(&sc.bytesWritten, 0)
br = atomic.SwapUint64(&sc.bytesRead, 0)
return
}