forked from streamingfast/dmetering
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes.go
132 lines (98 loc) · 2.43 KB
/
bytes.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package dmetering
import (
"context"
"fmt"
"sync"
)
type bytesMeterKey string
const contextKey = bytesMeterKey("bytesMeter")
func GetBytesMeter(ctx context.Context) Meter {
if bm, ok := ctx.Value(contextKey).(Meter); ok && bm != nil {
return bm
}
return NoopBytesMeter
}
func WithBytesMeter(ctx context.Context) context.Context {
//check if meter already exists and that it is not nil or a noop
if bm, ok := ctx.Value(contextKey).(Meter); ok && bm != nil && bm != NoopBytesMeter {
return ctx
}
bm := NewBytesMeter()
return WithExistingBytesMeter(ctx, bm)
}
func WithExistingBytesMeter(ctx context.Context, bm Meter) context.Context {
if bm == nil {
return ctx
}
return context.WithValue(ctx, contextKey, bm)
}
type Meter interface {
AddBytesWritten(n int)
AddBytesRead(n int)
BytesWritten() uint64
BytesRead() uint64
BytesWrittenDelta() uint64
BytesReadDelta() uint64
}
type meter struct {
bytesWritten uint64
bytesRead uint64
bytesWrittenDelta uint64
bytesReadDelta uint64
mu sync.RWMutex
}
func NewBytesMeter() Meter {
return &meter{}
}
func (b *meter) String() string {
b.mu.RLock()
defer b.mu.RUnlock()
return fmt.Sprintf("bytes written: %d, bytes read: %d", b.bytesWritten, b.bytesRead)
}
func (b *meter) AddBytesWritten(n int) {
b.mu.Lock()
defer b.mu.Unlock()
if n < 0 {
panic("negative value")
}
b.bytesWrittenDelta += uint64(n)
b.bytesWritten += uint64(n)
}
func (b *meter) AddBytesRead(n int) {
b.mu.Lock()
defer b.mu.Unlock()
b.bytesReadDelta += uint64(n)
b.bytesRead += uint64(n)
}
func (b *meter) BytesWritten() uint64 {
b.mu.RLock()
defer b.mu.RUnlock()
return b.bytesWritten
}
func (b *meter) BytesRead() uint64 {
b.mu.RLock()
defer b.mu.RUnlock()
return b.bytesRead
}
func (b *meter) BytesWrittenDelta() uint64 {
b.mu.Lock()
defer b.mu.Unlock()
result := b.bytesWrittenDelta
b.bytesWrittenDelta = 0
return result
}
func (b *meter) BytesReadDelta() uint64 {
b.mu.Lock()
defer b.mu.Unlock()
result := b.bytesReadDelta
b.bytesReadDelta = 0
return result
}
type noopMeter struct{}
func (_ *noopMeter) AddBytesWritten(n int) { return }
func (_ *noopMeter) AddBytesRead(n int) { return }
func (_ *noopMeter) BytesWritten() uint64 { return 0 }
func (_ *noopMeter) BytesRead() uint64 { return 0 }
func (_ *noopMeter) BytesWrittenDelta() uint64 { return 0 }
func (_ *noopMeter) BytesReadDelta() uint64 { return 0 }
var NoopBytesMeter Meter = &noopMeter{}