-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreaper.go
236 lines (192 loc) · 4.63 KB
/
reaper.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package reaper
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/go-redis/redis/v8"
"github.com/gotidy/batch"
)
const (
collectorKey = "task_durations"
batchSize = 1000
batchFlushInterval = 10 * time.Second
flushTimeout = 60 * time.Second
popCount = 1000
)
type Batcher interface {
Put(v interface{})
Close()
}
// Handler handles collected messages.
type Handler interface {
Serve(ctx context.Context, item Item)
}
type HandlerFunc func(ctx context.Context, item Item)
func (f HandlerFunc) Serve(ctx context.Context, item Item) {
f(ctx, item)
}
// Logger handles errors.
type Logger interface {
Error(err error)
}
type ErrorFunc func(err error)
func (f ErrorFunc) Error(err error) {
f(err)
}
type Collector struct {
redis *redis.Client
batcher Batcher
err chan error
cancel chan struct{}
handler Handler
logger Logger
wg sync.WaitGroup
}
type Item struct {
// Duration seconds
Duration int
Labels []string
}
// Option sets the batcher option.
type Option func(*Collector)
// WithLogger sets logger.
func WithLogger(log Logger) func(*Collector) {
return func(c *Collector) {
c.logger = log
}
}
// WithHandler sets handler of collected data.
func WithHandler(handler Handler) func(*Collector) {
return func(c *Collector) {
c.handler = handler
}
}
func New(redis *redis.Client, opts ...Option) *Collector {
c := &Collector{
redis: redis,
cancel: make(chan struct{}),
}
c.batcher = batch.New(batch.FlusherFunc(c.flush), batch.WithBatchSize(batchSize), batch.WithFlushInterval(batchFlushInterval))
for _, opt := range opts {
opt(c)
}
if c.handler != nil {
c.wg.Add(1)
go c.listen()
}
return c
}
func (c *Collector) Close() {
c.batcher.Close()
close(c.cancel)
c.wg.Wait()
}
func (c *Collector) error(err error) {
if c.logger != nil {
c.logger.Error(err)
}
}
func (c *Collector) flush(batch []interface{}) {
ctx, cancel := context.WithTimeout(context.Background(), flushTimeout)
defer cancel()
c.push(ctx, batch)
}
func (c *Collector) push(ctx context.Context, items ...interface{}) error {
if err := c.redis.RPush(ctx, collectorKey, items...).Err(); err != nil {
return fmt.Errorf("inserting duration info to redis: %w", err)
}
return nil
}
func (c *Collector) Push(ctx context.Context, d time.Duration, labels ...string) error {
b, err := json.Marshal(Item{Duration: int(d.Seconds()), Labels: labels})
if err != nil {
return fmt.Errorf("marshaling duration info: %w", err)
}
return c.push(ctx, string(b))
}
func (c *Collector) AsyncPush(ctx context.Context, d time.Duration, labels ...string) error {
b, err := json.Marshal(Item{Duration: int(d.Seconds()), Labels: labels})
if err != nil {
return fmt.Errorf("marshaling duration info: %w", err)
}
c.batcher.Put(string(b))
return nil
}
func (c *Collector) get(ctx context.Context, buffer []Item) (count int, err error) {
res, err := c.redis.LPopCount(ctx, collectorKey, len(buffer)).Result()
if err != nil {
return 0, fmt.Errorf("getting all durations info from redis: %w", err)
}
for i, s := range res {
var item Item
err := json.Unmarshal([]byte(s), &item)
if err != nil {
return 0, fmt.Errorf("unmarshaling duration info (%s): %w", s, err)
}
buffer[i] = item
}
return len(res), nil
}
func (c *Collector) listen() {
defer c.wg.Done()
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-c.cancel:
cancel()
}
}()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-ctx.Done():
return
}
// Read all items from the list.
for {
select {
case <-ctx.Done():
return
default:
}
res, err := c.redis.LPopCount(ctx, collectorKey, popCount).Result()
if err != nil && err != redis.Nil {
c.error(fmt.Errorf("getting all durations info from redis: %w", err))
continue
}
if err == redis.Nil || len(res) == 0 {
break
}
for _, s := range res {
var item Item
err := json.Unmarshal([]byte(s), &item)
if err != nil {
c.error(fmt.Errorf("unmarshaling duration info (%s): %w", s, err))
}
c.handler.Serve(ctx, item)
}
if len(res) < popCount {
break
}
}
}
}
// func (c *Collector) Get(ctx context.Context) ([]Item, error) {
// items := make([]Item, 0, len(res))
// for _, s := range res {
// var item Item
// err := json.Unmarshal([]byte(s), &item)
// if err != nil {
// return nil, fmt.Errorf("unmarshaling duration info (%s): %w", s, err)
// }
// items = append(items, item)
// }
// return items, nil
// }
// func (c *Collector) GetAll(ctx context.Context) ([]Item, error) {
// c.Get(ctx)
// }