forked from vmihailenco/taskq
/
batcher.go
131 lines (107 loc) · 2 KB
/
batcher.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
package msgqueue
import (
"errors"
"sync"
"time"
)
var errBatched = errors.New("message is batched for later processing")
var errBatchProcessed = errors.New("message is processed in a batch")
type BatcherOptions struct {
Handler func([]*Message) error
ShouldBatch func([]*Message, *Message) bool
RetryLimit int
Timeout time.Duration
}
func (opt *BatcherOptions) init(p *Processor) {
if opt.RetryLimit == 0 {
opt.RetryLimit = p.Options().RetryLimit
}
if opt.Timeout == 0 {
opt.Timeout = 3 * time.Second
}
}
// Batcher collects messages for later batch processing.
type Batcher struct {
p *Processor
opt *BatcherOptions
timer *time.Timer
mu sync.Mutex
batch []*Message
closed bool
}
func NewBatcher(p *Processor, opt *BatcherOptions) *Batcher {
opt.init(p)
b := Batcher{
p: p,
opt: opt,
}
b.timer = time.AfterFunc(time.Minute, b.onTimeout)
b.timer.Stop()
return &b
}
func (b *Batcher) wait() {
if len(b.batch) > 0 {
b.process(b.batch)
b.batch = nil
}
}
func (b *Batcher) Add(msg *Message) error {
var batch []*Message
b.mu.Lock()
if b.closed {
if len(b.batch) > 0 {
panic("not reached")
}
batch = []*Message{msg}
} else {
if len(b.batch) == 0 {
b.stopTimer()
b.timer.Reset(b.opt.Timeout)
}
if b.opt.ShouldBatch(b.batch, msg) {
b.batch = append(b.batch, msg)
} else {
batch = b.batch
b.batch = []*Message{msg}
}
}
b.mu.Unlock()
if len(batch) > 0 {
b.process(batch)
return errBatchProcessed
}
return errBatched
}
func (b *Batcher) stopTimer() {
if !b.timer.Stop() {
select {
case <-b.timer.C:
default:
}
}
}
func (b *Batcher) process(batch []*Message) {
err := b.opt.Handler(batch)
for _, msg := range batch {
if err != nil && msg.Err == nil {
msg.Err = err
}
b.p.Put(msg)
}
}
func (b *Batcher) onTimeout() {
b.mu.Lock()
b.wait()
b.mu.Unlock()
}
func (b *Batcher) Close() error {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return nil
}
b.closed = true
b.stopTimer()
b.wait()
return nil
}