forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutput_wrapper.go
244 lines (211 loc) · 6.06 KB
/
output_wrapper.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
/*
Copyright (c) 2014 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 buffer
import (
"sync"
"sync/atomic"
"time"
"github.com/jeffail/benthos/lib/buffer/impl"
"github.com/jeffail/benthos/lib/types"
"github.com/jeffail/util/metrics"
)
//------------------------------------------------------------------------------
// OutputWrapper - Wraps a buffer with a Producer/Consumer interface.
type OutputWrapper struct {
stats metrics.Type
buffer impl.Buffer
running int32
messagesIn <-chan types.Message
messagesOut chan types.Message
responsesIn <-chan types.Response
responsesOut chan types.Response
errorsChan chan []error
closedWG sync.WaitGroup
closeChan chan struct{}
closedChan chan struct{}
}
// NewOutputWrapper - Create a new Producer/Consumer around a buffer.
func NewOutputWrapper(buffer impl.Buffer, stats metrics.Type) Type {
m := OutputWrapper{
stats: stats,
buffer: buffer,
running: 1,
messagesOut: make(chan types.Message),
responsesOut: make(chan types.Response),
errorsChan: make(chan []error),
closeChan: make(chan struct{}),
closedChan: make(chan struct{}),
}
return &m
}
//------------------------------------------------------------------------------
// inputLoop - Internal loop brokers incoming messages to the buffer.
func (m *OutputWrapper) inputLoop() {
defer func() {
close(m.responsesOut)
m.buffer.CloseOnceEmpty()
m.closedWG.Done()
}()
for atomic.LoadInt32(&m.running) == 1 {
var msg types.Message
var open bool
select {
case msg, open = <-m.messagesIn:
if !open {
return
}
case <-m.closeChan:
return
}
backlog, err := m.buffer.PushMessage(msg)
if err == nil {
m.stats.Gauge("buffer.backlog", int64(backlog))
}
select {
case m.responsesOut <- types.NewSimpleResponse(err):
case <-m.closeChan:
return
}
}
}
// outputLoop - Internal loop brokers buffer messages to output pipe.
func (m *OutputWrapper) outputLoop() {
defer func() {
m.buffer.Close()
close(m.messagesOut)
close(m.errorsChan)
m.closedWG.Done()
}()
errs := []error{}
errMap := map[error]struct{}{}
var msg types.Message
for atomic.LoadInt32(&m.running) == 1 {
if msg.Parts == nil {
var err error
if msg, err = m.buffer.NextMessage(); err != nil {
if err != types.ErrTypeClosed {
// Unconventional errors here should always indicate some sort of corruption.
// Hopefully the corruption was message specific and not the whole buffer, so we
// can try shifting and reading again.
m.buffer.ShiftMessage()
if _, exists := errMap[err]; !exists {
errMap[err] = struct{}{}
errs = append(errs, err)
}
} else {
// If our buffer is closed then we exit.
return
}
}
}
if msg.Parts != nil {
select {
case m.messagesOut <- msg:
case <-m.closeChan:
return
}
res, open := <-m.responsesIn
if !open {
return
}
if res.Error() == nil {
msg = types.Message{}
backlog, _ := m.buffer.ShiftMessage()
m.stats.Gauge("buffer.backlog", int64(backlog))
} else {
if _, exists := errMap[res.Error()]; !exists {
errMap[res.Error()] = struct{}{}
errs = append(errs, res.Error())
}
}
}
// If we have errors built up.
if len(errs) > 0 {
select {
case m.errorsChan <- errs:
errMap = map[error]struct{}{}
errs = []error{}
default:
// Reader not ready, do not block here.
}
}
}
}
// StartReceiving - Assigns a messages channel for the output to read.
func (m *OutputWrapper) StartReceiving(msgs <-chan types.Message) error {
if m.messagesIn != nil {
return types.ErrAlreadyStarted
}
m.messagesIn = msgs
if m.responsesIn != nil {
m.closedWG.Add(2)
go m.inputLoop()
go m.outputLoop()
go func() {
m.closedWG.Wait()
close(m.closedChan)
}()
}
return nil
}
// MessageChan - Returns the channel used for consuming messages from this input.
func (m *OutputWrapper) MessageChan() <-chan types.Message {
return m.messagesOut
}
// StartListening - Sets the channel for reading responses.
func (m *OutputWrapper) StartListening(responses <-chan types.Response) error {
if m.responsesIn != nil {
return types.ErrAlreadyStarted
}
m.responsesIn = responses
if m.messagesIn != nil {
m.closedWG.Add(2)
go m.inputLoop()
go m.outputLoop()
go func() {
m.closedWG.Wait()
close(m.closedChan)
}()
}
return nil
}
// ResponseChan - Returns the response channel.
func (m *OutputWrapper) ResponseChan() <-chan types.Response {
return m.responsesOut
}
// ErrorsChan - Returns the errors channel.
func (m *OutputWrapper) ErrorsChan() <-chan []error {
return m.errorsChan
}
// CloseAsync - Shuts down the OutputWrapper and stops processing messages.
func (m *OutputWrapper) CloseAsync() {
if atomic.CompareAndSwapInt32(&m.running, 1, 0) {
close(m.closeChan)
}
}
// WaitForClose - Blocks until the OutputWrapper output has closed down.
func (m *OutputWrapper) WaitForClose(timeout time.Duration) error {
select {
case <-m.closedChan:
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}
//------------------------------------------------------------------------------