forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
async_reader.go
280 lines (236 loc) · 7.02 KB
/
async_reader.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
package input
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/nehal119/benthos-119/pkg/component"
"github.com/nehal119/benthos-119/pkg/message"
"github.com/nehal119/benthos-119/pkg/shutdown"
"github.com/nehal119/benthos-119/pkg/tracing"
)
// AsyncReader is an input implementation that reads messages from an
// input.Async component.
type AsyncReader struct {
connected int32
connBackoff backoff.BackOff
readBackoff backoff.BackOff
typeStr string
reader Async
mgr component.Observability
transactions chan message.Transaction
shutSig *shutdown.Signaller
}
// NewAsyncReader creates a new AsyncReader input type.
func NewAsyncReader(
typeStr string,
r Async,
mgr component.Observability,
opts ...func(a *AsyncReader),
) (Streamed, error) {
connBoff := backoff.NewExponentialBackOff()
connBoff.InitialInterval = time.Millisecond * 100
connBoff.MaxInterval = time.Second
connBoff.MaxElapsedTime = 0
readBoff := backoff.NewExponentialBackOff()
readBoff.InitialInterval = time.Millisecond * 100
readBoff.MaxInterval = time.Second
readBoff.MaxElapsedTime = 0
rdr := &AsyncReader{
connBackoff: connBoff,
readBackoff: readBoff,
typeStr: typeStr,
reader: r,
mgr: mgr,
transactions: make(chan message.Transaction),
shutSig: shutdown.NewSignaller(),
}
for _, opt := range opts {
opt(rdr)
}
go rdr.loop()
return rdr, nil
}
// AsyncReaderWithConnBackOff set the backoff used for limiting connection
// attempts. If the maximum number of retry attempts is reached then the input
// will gracefully stop.
func AsyncReaderWithConnBackOff(boff backoff.BackOff) func(a *AsyncReader) {
return func(a *AsyncReader) {
a.connBackoff = boff
}
}
//------------------------------------------------------------------------------
func (r *AsyncReader) loop() {
// Metrics paths
var (
mRcvd = r.mgr.Metrics().GetCounter("input_received")
mConn = r.mgr.Metrics().GetCounter("input_connection_up")
mFailedConn = r.mgr.Metrics().GetCounter("input_connection_failed")
mLostConn = r.mgr.Metrics().GetCounter("input_connection_lost")
mLatency = r.mgr.Metrics().GetTimer("input_latency_ns")
traceName = "input_" + r.typeStr
)
closeAtLeisureCtx, calDone := r.shutSig.CloseAtLeisureCtx(context.Background())
defer calDone()
closeNowCtx, cnDone := r.shutSig.CloseNowCtx(context.Background())
defer cnDone()
defer func() {
_ = r.reader.Close(context.Background())
atomic.StoreInt32(&r.connected, 0)
close(r.transactions)
r.shutSig.ShutdownComplete()
}()
pendingAcks := sync.WaitGroup{}
defer func() {
r.mgr.Logger().Debugln("Waiting for pending acks to resolve before shutting down.")
pendingAcks.Wait()
r.mgr.Logger().Debugln("Pending acks resolved.")
}()
initConnection := func() bool {
for {
if r.shutSig.ShouldCloseAtLeisure() {
return false
}
if err := r.reader.Connect(closeAtLeisureCtx); err != nil {
if r.shutSig.ShouldCloseAtLeisure() || errors.Is(err, component.ErrTypeClosed) {
return false
}
r.mgr.Logger().Errorf("Failed to connect to %v: %v\n", r.typeStr, err)
mFailedConn.Incr(1)
var nextBoff time.Duration
var e *component.ErrBackOff
if errors.As(err, &e) {
nextBoff = e.Wait
} else {
nextBoff = r.connBackoff.NextBackOff()
}
if nextBoff == backoff.Stop {
r.mgr.Logger().Errorf("Maximum number of connection attempt retries has been met, gracefully terminating input %v", r.typeStr)
return false
}
if sleepWithCancellation(closeAtLeisureCtx, nextBoff) != nil {
return false
}
} else {
r.connBackoff.Reset()
return true
}
}
}
if !initConnection() {
return
}
mConn.Incr(1)
atomic.StoreInt32(&r.connected, 1)
for {
msg, ackFn, err := r.reader.ReadBatch(closeAtLeisureCtx)
// If our reader says it is not connected.
if errors.Is(err, component.ErrNotConnected) {
mLostConn.Incr(1)
atomic.StoreInt32(&r.connected, 0)
// Continue to try to reconnect while still active.
if !initConnection() {
return
}
mConn.Incr(1)
atomic.StoreInt32(&r.connected, 1)
continue
}
// Close immediately if our reader is closed.
if r.shutSig.ShouldCloseAtLeisure() || errors.Is(err, component.ErrTypeClosed) {
return
}
if err != nil || len(msg) == 0 {
if err != nil && !errors.Is(err, component.ErrTimeout) && !errors.Is(err, component.ErrNotConnected) {
r.mgr.Logger().Errorf("Failed to read message: %v\n", err)
}
nextBoff := r.readBackoff.NextBackOff()
if nextBoff == backoff.Stop {
r.mgr.Logger().Errorf("Maximum number of read attempt retries has been met, gracefully terminating input %v", r.typeStr)
return
}
select {
case <-time.After(nextBoff):
case <-r.shutSig.CloseAtLeisureChan():
return
}
continue
} else {
r.readBackoff.Reset()
mRcvd.Incr(int64(msg.Len()))
r.mgr.Logger().Tracef("Consumed %v messages from '%v'.\n", msg.Len(), r.typeStr)
}
startedAt := time.Now()
resChan := make(chan error, 1)
tracing.InitSpans(r.mgr.Tracer(), traceName, msg)
select {
case r.transactions <- message.NewTransaction(msg, resChan):
case <-r.shutSig.CloseAtLeisureChan():
return
}
pendingAcks.Add(1)
go func(
m message.Batch,
aFn AsyncAckFn,
rChan chan error,
) {
defer pendingAcks.Done()
var res error
select {
case res = <-rChan:
case <-r.shutSig.CloseNowChan():
// Even if the pipeline is terminating we still want to attempt
// to propagate an acknowledgement from in-transit messages.
return
}
mLatency.Timing(time.Since(startedAt).Nanoseconds())
tracing.FinishSpans(m)
if err = aFn(closeNowCtx, res); err != nil {
r.mgr.Logger().Errorf("Failed to acknowledge message: %v\n", err)
}
}(msg, ackFn, resChan)
}
}
// TransactionChan returns a transactions channel for consuming messages from
// this input type.
func (r *AsyncReader) TransactionChan() <-chan message.Transaction {
return r.transactions
}
// Connected returns a boolean indicating whether this input is currently
// connected to its target.
func (r *AsyncReader) Connected() bool {
return atomic.LoadInt32(&r.connected) == 1
}
// TriggerStopConsuming instructs the input to start shutting down resources
// once all pending messages are delivered and acknowledged. This call does
// not block.
func (r *AsyncReader) TriggerStopConsuming() {
r.shutSig.CloseAtLeisure()
}
// TriggerCloseNow triggers the shut down of this component but should not block
// the calling goroutine.
func (r *AsyncReader) TriggerCloseNow() {
r.shutSig.CloseNow()
}
// WaitForClose is a blocking call to wait until the component has finished
// shutting down and cleaning up resources.
func (r *AsyncReader) WaitForClose(ctx context.Context) error {
select {
case <-r.shutSig.HasClosedChan():
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func sleepWithCancellation(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}