-
Notifications
You must be signed in to change notification settings - Fork 21
/
collector_buffered.go
60 lines (51 loc) · 1.09 KB
/
collector_buffered.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
package ftdc
import (
"context"
"github.com/mongodb/ftdc/util"
)
type bufferedCollector struct {
Collector
pipe chan interface{}
catcher util.Catcher
ctx context.Context
}
// NewBufferedCollector wraps an existing collector with a buffer to
// normalize throughput to an underlying collector implementation.
func NewBufferedCollector(ctx context.Context, size int, coll Collector) Collector {
c := &bufferedCollector{
Collector: coll,
pipe: make(chan interface{}, size),
catcher: util.NewCatcher(),
ctx: ctx,
}
go func() {
for {
select {
case <-ctx.Done():
if len(c.pipe) != 0 {
for in := range c.pipe {
c.catcher.Add(c.Collector.Add(in))
}
}
return
case in := <-c.pipe:
c.catcher.Add(c.Collector.Add(in))
}
}
}()
return c
}
func (c *bufferedCollector) Add(in interface{}) error {
select {
case <-c.ctx.Done():
return c.ctx.Err()
case c.pipe <- in:
return nil
}
}
func (c *bufferedCollector) Resolve() ([]byte, error) {
if c.catcher.HasErrors() {
return nil, c.catcher.Resolve()
}
return c.Collector.Resolve()
}