forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
async_cut_off.go
89 lines (78 loc) · 2.02 KB
/
async_cut_off.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
package input
import (
"context"
"github.com/nehal119/benthos-119/pkg/component"
"github.com/nehal119/benthos-119/pkg/message"
)
type asyncCutOffMsg struct {
msg message.Batch
ackFn AsyncAckFn
}
// AsyncCutOff is a wrapper for input.Async implementations that exits from
// WaitForClose immediately. This is only useful when the underlying readable
// resource cannot be closed reliably and can block forever.
type AsyncCutOff struct {
msgChan chan asyncCutOffMsg
errChan chan error
ctx context.Context
close func()
r Async
}
// NewAsyncCutOff returns a new AsyncCutOff wrapper around a input.Async.
func NewAsyncCutOff(r Async) *AsyncCutOff {
ctx, done := context.WithCancel(context.Background())
return &AsyncCutOff{
msgChan: make(chan asyncCutOffMsg),
errChan: make(chan error),
ctx: ctx,
close: done,
r: r,
}
}
//------------------------------------------------------------------------------
// Connect attempts to establish a connection to the source, if
// unsuccessful returns an error. If the attempt is successful (or not
// necessary) returns nil.
func (c *AsyncCutOff) Connect(ctx context.Context) error {
return c.r.Connect(ctx)
}
// ReadBatch attempts to read a new message from the source.
func (c *AsyncCutOff) ReadBatch(ctx context.Context) (message.Batch, AsyncAckFn, error) {
go func() {
msg, ackFn, err := c.r.ReadBatch(ctx)
if err == nil {
select {
case c.msgChan <- asyncCutOffMsg{
msg: msg,
ackFn: ackFn,
}:
case <-ctx.Done():
}
} else {
select {
case c.errChan <- err:
case <-ctx.Done():
}
}
}()
select {
case m := <-c.msgChan:
return m.msg, m.ackFn, nil
case e := <-c.errChan:
return nil, nil, e
case <-ctx.Done():
go func() {
_ = c.r.Close(context.Background())
}()
case <-c.ctx.Done():
}
return nil, nil, component.ErrTypeClosed
}
// Close triggers the asynchronous closing of the reader.
func (c *AsyncCutOff) Close(ctx context.Context) error {
go func() {
_ = c.r.Close(context.Background())
}()
c.close()
return nil
}