/
shared.go
127 lines (105 loc) · 2.5 KB
/
shared.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
package main
import (
"io"
"sync/atomic"
"github.com/klauspost/compress/s2"
)
type compressedConn struct {
r *s2.Reader
w *s2.Writer
c io.Closer
}
func CompressedReadWriteCloser(rwc io.ReadWriteCloser) io.ReadWriteCloser {
r := s2.NewReader(rwc)
w := s2.NewWriter(rwc, s2.WriterFlushOnWrite())
return &compressedConn{
r,
w,
rwc,
}
}
func (c *compressedConn) Read(p []byte) (n int, err error) {
n, err = c.r.Read(p)
return
}
func (c *compressedConn) Write(p []byte) (n int, err error) {
n, err = c.w.Write(p)
return
}
func (c *compressedConn) Close() (err error) {
c.w.Close()
err = c.c.Close()
return
}
// performance related stuff
type PerformanceCounterType int
const (
SentOverWire PerformanceCounterType = iota
RecievedOverWire
SentBytes
RecievedBytes
WrittenBytes
ReadBytes
BytesProcessed
FilesProcessed
DirectoriesProcessed
FileQueue
FolderQueue
maxperformancecountertype
)
type AtomicAdder func(uint64)
type performanceentry struct {
counters [maxperformancecountertype]uint64
}
type performance struct {
current atomic.Pointer[performanceentry]
maxhistory int
entries []performanceentry
}
func NewPerformance() *performance {
p := performance{}
p.current.Store(&performanceentry{})
p.maxhistory = 300
return &p
}
func (p *performance) GetAtomicAdder(ct PerformanceCounterType) AtomicAdder {
return func(v uint64) {
p.Add(ct, v)
}
}
func (p *performance) Add(ct PerformanceCounterType, v uint64) {
pc := p.current.Load()
atomic.AddUint64(&pc.counters[ct], v)
}
func (p *performance) NextHistory() performanceentry {
newhistory := performanceentry{}
oldhistory := p.current.Swap(&newhistory)
if len(p.entries) > p.maxhistory {
copy(p.entries, p.entries[1:])
p.entries[len(p.entries)-1] = *oldhistory
} else {
p.entries = append(p.entries, *oldhistory)
}
return *oldhistory
}
var p = NewPerformance()
type PerformanceWrapperReadWriteCloser struct {
onWrite, onRead AtomicAdder
rwc io.ReadWriteCloser
}
func NewPerformanceWrapper(rwc io.ReadWriteCloser, onRead, onWrite AtomicAdder) *PerformanceWrapperReadWriteCloser {
return &PerformanceWrapperReadWriteCloser{onRead, onWrite, rwc}
}
func (pw *PerformanceWrapperReadWriteCloser) Write(b []byte) (int, error) {
n, err := pw.rwc.Write(b)
pw.onWrite(uint64(n))
return n, err
}
func (pw *PerformanceWrapperReadWriteCloser) Read(b []byte) (int, error) {
n, err := pw.rwc.Read(b)
pw.onRead(uint64(n))
return n, err
}
func (pw *PerformanceWrapperReadWriteCloser) Close() error {
return pw.rwc.Close()
}