forked from vmihailenco/taskq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batcher.go
127 lines (105 loc) · 1.89 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
package msgqueue
import (
"errors"
"sync"
"time"
)
var errBatched = errors.New("message is batched")
var errBatchProcessed = errors.New("message is processed in a batch")
type BatcherOptions struct {
Handler func([]*Message) error
Splitter func([]*Message) ([]*Message, []*Message)
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
msgs []*Message
sync 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) SetSync(v bool) {
b.mu.Lock()
b.sync = v
if v {
b.wait()
}
b.mu.Unlock()
}
func (b *Batcher) wait() {
if len(b.msgs) > 0 {
b.process(b.msgs)
b.msgs = nil
}
}
func (b *Batcher) Add(msg *Message) error {
var msgs []*Message
b.mu.Lock()
if len(b.msgs) == 0 {
b.stopTimer()
b.timer.Reset(b.opt.Timeout)
}
b.msgs = append(b.msgs, msg)
if b.sync {
msgs = b.msgs
b.msgs = nil
} else {
msgs, b.msgs = b.opt.Splitter(b.msgs)
}
b.mu.Unlock()
if len(msgs) > 0 {
b.process(msgs)
return errBatchProcessed
}
return errBatched
}
func (b *Batcher) stopTimer() {
if !b.timer.Stop() {
select {
case <-b.timer.C:
default:
}
}
}
func (b *Batcher) process(msgs []*Message) {
err := b.opt.Handler(msgs)
for _, msg := range msgs {
if msg.Err == nil && 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()
b.stopTimer()
b.wait()
b.mu.Unlock()
return nil
}