forked from vmihailenco/taskq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
msg_batcher.go
129 lines (106 loc) · 1.74 KB
/
msg_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
package msgqueue
import (
"sync"
"sync/atomic"
"time"
)
type BatcherOptions struct {
Worker func([]*Message) error
Splitter func([]*Message) ([]*Message, []*Message)
Timeout time.Duration
}
func (opt *BatcherOptions) init() {
if opt.Timeout == 0 {
opt.Timeout = 3 * time.Second
}
}
type Batcher struct {
q Queue
opt *BatcherOptions
timer *time.Timer
_sync uint32 // atomic
wg sync.WaitGroup
mu sync.Mutex
msgs []*Message
}
func NewBatcher(q Queue, opt *BatcherOptions) *Batcher {
opt.init()
b := Batcher{
q: q,
opt: opt,
}
b.timer = time.AfterFunc(time.Minute, b.onTimeout)
b.timer.Stop()
return &b
}
func (b *Batcher) SetSync(v bool) {
var n uint32
if v {
n = 1
}
atomic.StoreUint32(&b._sync, n)
if !v {
return
}
b.mu.Lock()
b.wait()
b.mu.Unlock()
}
func (b *Batcher) wait() {
if len(b.msgs) > 0 {
b.process(b.msgs)
b.msgs = nil
}
}
func (b *Batcher) isSync() bool {
return atomic.LoadUint32(&b._sync) == 1
}
func (b *Batcher) Add(msg *Message) {
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.isSync() {
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)
}
}
func (b *Batcher) process(msgs []*Message) {
_ = b.opt.Worker(msgs)
for _, msg := range msgs {
if msg.Err == nil {
b.q.Delete(msg)
} else {
b.q.Release(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
}
func (b *Batcher) stopTimer() {
if !b.timer.Stop() {
select {
case <-b.timer.C:
default:
}
}
}