forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lines.go
227 lines (191 loc) · 5.98 KB
/
lines.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
// Copyright (c) 2018 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 reader
import (
"bufio"
"bytes"
"io"
"time"
"github.com/Jeffail/benthos/lib/types"
)
//------------------------------------------------------------------------------
// Lines is a reader implementation that continuously reads line delimited
// messages from an io.Reader type.
type Lines struct {
handleCtor func() (io.Reader, error)
onClose func()
handle io.Reader
scanner *bufio.Scanner
messageBuffer *bytes.Buffer
messageBufferIndex int
maxBuffer int
multipart bool
delimiter []byte
}
// NewLines creates a new reader input type.
//
// Callers must provide a constructor function for the target io.Reader, which
// is called on start up and again each time a reader is exhausted. If the
// constructor is called but there is no more content to create a Reader for
// then the error `io.EOF` should be returned and the Lines will close.
//
// Callers must also provide an onClose function, which will be called if the
// Lines has been instructed to shut down. This function should unblock any
// blocked Read calls.
func NewLines(
handleCtor func() (io.Reader, error),
onClose func(),
options ...func(r *Lines),
) (*Lines, error) {
r := Lines{
handleCtor: handleCtor,
onClose: onClose,
messageBuffer: &bytes.Buffer{},
maxBuffer: bufio.MaxScanTokenSize,
multipart: false,
delimiter: []byte("\n"),
}
for _, opt := range options {
opt(&r)
}
return &r, nil
}
//------------------------------------------------------------------------------
// OptLinesSetMaxBuffer is a option func that sets the maximum size of the
// line parsing buffers.
func OptLinesSetMaxBuffer(maxBuffer int) func(r *Lines) {
return func(r *Lines) {
r.maxBuffer = maxBuffer
}
}
// OptLinesSetMultipart is a option func that sets the boolean flag
// indicating whether lines should be parsed as multipart or not.
func OptLinesSetMultipart(multipart bool) func(r *Lines) {
return func(r *Lines) {
r.multipart = multipart
}
}
// OptLinesSetDelimiter is a option func that sets the delimiter (default
// '\n') used to divide lines (message parts) in the stream of data.
func OptLinesSetDelimiter(delimiter string) func(r *Lines) {
return func(r *Lines) {
r.delimiter = []byte(delimiter)
}
}
//------------------------------------------------------------------------------
func (r *Lines) closeHandle() {
if r.handle != nil {
if closer, ok := r.handle.(io.ReadCloser); ok {
closer.Close()
}
r.handle = nil
}
r.scanner = nil
}
// Connect attempts to establish a new scanner for an io.Reader.
func (r *Lines) Connect() error {
if r.scanner != nil {
return nil
}
r.closeHandle() // Just incase we have an open handle without a scanner.
var err error
r.handle, err = r.handleCtor()
if err != nil {
if err == io.EOF {
return types.ErrTypeClosed
}
return err
}
r.scanner = bufio.NewScanner(r.handle)
if r.maxBuffer != bufio.MaxScanTokenSize {
r.scanner.Buffer([]byte{}, r.maxBuffer)
}
r.scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, r.delimiter); i >= 0 {
// We have a full terminated line.
return i + len(r.delimiter), data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
})
return nil
}
// Read attempts to read a new line from the io.Reader.
func (r *Lines) Read() (types.Message, error) {
if r.scanner == nil {
return types.Message{}, types.ErrNotConnected
}
msg := types.NewMessage()
for r.scanner.Scan() {
partSize, err := r.messageBuffer.Write(r.scanner.Bytes())
rIndex := r.messageBufferIndex
r.messageBufferIndex += partSize
if err != nil {
return types.Message{}, err
}
if partSize > 0 {
msg.Parts = append(
msg.Parts, r.messageBuffer.Bytes()[rIndex:rIndex+partSize],
)
if !r.multipart {
return msg, nil
}
} else if r.multipart && len(msg.Parts) > 0 {
// Empty line means we're finished reading parts for this
// message.
return msg, nil
}
}
if err := r.scanner.Err(); err != nil {
r.closeHandle()
return types.Message{}, err
}
r.closeHandle()
if len(msg.Parts) > 0 {
return msg, nil
}
return types.Message{}, types.ErrNotConnected
}
// Acknowledge confirms whether or not our unacknowledged messages have been
// successfully propagated or not.
func (r *Lines) Acknowledge(err error) error {
if err == nil && r.messageBuffer != nil {
r.messageBuffer.Reset()
r.messageBufferIndex = 0
}
return nil
}
// CloseAsync shuts down the reader input and stops processing requests.
func (r *Lines) CloseAsync() {
r.onClose()
}
// WaitForClose blocks until the reader input has closed down.
func (r *Lines) WaitForClose(timeout time.Duration) error {
r.closeHandle()
return nil
}
//------------------------------------------------------------------------------