forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
processor.go
307 lines (262 loc) · 7.27 KB
/
processor.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Copyright (c) 2017 Ashley Jeffs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package pipeline
import (
"sync"
"sync/atomic"
"time"
"github.com/Jeffail/benthos/lib/log"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/response"
"github.com/Jeffail/benthos/lib/types"
"github.com/Jeffail/benthos/lib/util/throttle"
)
//------------------------------------------------------------------------------
// Processor is a pipeline that supports both Consumer and Producer interfaces.
// The processor will read from a source, perform some processing, and then
// either propagate a new message or drop it.
type Processor struct {
running int32
dispatchers int32
log log.Modular
stats metrics.Type
msgProcessors []types.Processor
messagesOut chan types.Transaction
responsesIn chan types.Response
messagesIn <-chan types.Transaction
mSndSucc metrics.StatCounter
mSndErr metrics.StatCounter
closeChan chan struct{}
closed chan struct{}
}
// NewProcessor returns a new message processing pipeline.
func NewProcessor(
log log.Modular,
stats metrics.Type,
msgProcessors ...types.Processor,
) *Processor {
return &Processor{
running: 1,
dispatchers: 1,
msgProcessors: msgProcessors,
log: log.NewModule(".pipeline.processor"),
stats: stats,
mSndSucc: stats.GetCounter("pipeline.processor.send.success"),
mSndErr: stats.GetCounter("pipeline.processor.send.error"),
messagesOut: make(chan types.Transaction),
responsesIn: make(chan types.Response),
closeChan: make(chan struct{}),
closed: make(chan struct{}),
}
}
//------------------------------------------------------------------------------
// loop is the processing loop of this pipeline.
func (p *Processor) loop() {
defer func() {
if atomic.AddInt32(&p.dispatchers, -1) == 0 {
close(p.messagesOut)
close(p.closed)
}
}()
var (
mProcCount = p.stats.GetCounter("pipeline.processor.count")
mProcDropped = p.stats.GetCounter("pipeline.processor.dropped")
)
var open bool
for atomic.LoadInt32(&p.running) == 1 {
var tran types.Transaction
select {
case tran, open = <-p.messagesIn:
if !open {
return
}
case <-p.closeChan:
return
}
mProcCount.Incr(1)
resultMsgs := []types.Message{tran.Payload}
var resultRes types.Response
for i := 0; len(resultMsgs) > 0 && i < len(p.msgProcessors); i++ {
var nextResultMsgs []types.Message
for _, m := range resultMsgs {
var rMsgs []types.Message
rMsgs, resultRes = p.msgProcessors[i].ProcessMessage(m)
nextResultMsgs = append(nextResultMsgs, rMsgs...)
}
resultMsgs = nextResultMsgs
}
if len(resultMsgs) == 0 {
mProcDropped.Incr(1)
select {
case tran.ResponseChan <- resultRes:
case <-p.closeChan:
return
}
continue
}
if len(resultMsgs) > 1 {
p.dispatchMessages(resultMsgs, tran.ResponseChan)
} else {
p.dispatchMessage(resultMsgs[0], tran.ResponseChan)
}
}
}
// dispatchMessage attempts to send a single message result of processors over
// the shared messages channel. This send is retried until success.
func (p *Processor) dispatchMessage(m types.Message, ogResChan chan<- types.Response) {
resChan := make(chan types.Response)
transac := types.NewTransaction(m, resChan)
var res types.Response
select {
case p.messagesOut <- transac:
case <-p.closeChan:
return
}
atomic.AddInt32(&p.dispatchers, 1)
go func() {
defer func() {
if atomic.AddInt32(&p.dispatchers, -1) == 0 {
close(p.messagesOut)
close(p.closed)
}
}()
throt := throttle.New(throttle.OptCloseChan(p.closeChan))
sendLoop:
for {
var open bool
select {
case res, open = <-resChan:
if !open {
return
}
case <-p.closeChan:
return
}
if res.Error() == nil {
p.mSndSucc.Incr(1)
break sendLoop
}
p.mSndErr.Incr(1)
if !throt.Retry() {
return
}
select {
case p.messagesOut <- transac:
case <-p.closeChan:
return
}
}
select {
case ogResChan <- res:
case <-p.closeChan:
return
}
}()
}
// dispatchMessages attempts to send a multiple messages results of processors
// over the shared messages channel. This send is retried until success.
func (p *Processor) dispatchMessages(msgs []types.Message, ogResChan chan<- types.Response) {
throt := throttle.New(throttle.OptCloseChan(p.closeChan))
var skipAcks int64
sendMsg := func(m types.Message) {
resChan := make(chan types.Response)
transac := types.NewTransaction(m, resChan)
for {
select {
case p.messagesOut <- transac:
case <-p.closeChan:
return
}
var res types.Response
var open bool
select {
case res, open = <-resChan:
if !open {
return
}
case <-p.closeChan:
return
}
if skipAck := res.SkipAck(); res.Error() == nil || skipAck {
if skipAck {
atomic.AddInt64(&skipAcks, 1)
}
p.mSndSucc.Incr(1)
return
}
p.mSndErr.Incr(1)
if !throt.Retry() {
return
}
}
}
wg := sync.WaitGroup{}
wg.Add(len(msgs))
for _, msg := range msgs {
go func(m types.Message) {
defer wg.Done()
sendMsg(m)
}(msg)
}
wg.Wait()
throt.Reset()
var res types.Response
if skipAcks == int64(len(msgs)) {
res = response.NewUnack()
} else {
res = response.NewAck()
}
select {
case ogResChan <- res:
case <-p.closeChan:
return
}
}
//------------------------------------------------------------------------------
// Consume assigns a messages channel for the pipeline to read.
func (p *Processor) Consume(msgs <-chan types.Transaction) error {
if p.messagesIn != nil {
return types.ErrAlreadyStarted
}
p.messagesIn = msgs
go p.loop()
return nil
}
// TransactionChan returns the channel used for consuming messages from this
// pipeline.
func (p *Processor) TransactionChan() <-chan types.Transaction {
return p.messagesOut
}
// CloseAsync shuts down the pipeline and stops processing messages.
func (p *Processor) CloseAsync() {
if atomic.CompareAndSwapInt32(&p.running, 1, 0) {
close(p.closeChan)
}
}
// WaitForClose blocks until the StackBuffer output has closed down.
func (p *Processor) WaitForClose(timeout time.Duration) error {
select {
case <-p.closed:
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}
//------------------------------------------------------------------------------