-
Notifications
You must be signed in to change notification settings - Fork 0
/
processor.go
333 lines (288 loc) · 6.85 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package processor
import (
"context"
"sync"
"time"
"github.com/DoNewsCode/core/di"
"github.com/DoNewsCode/core/logging"
"github.com/DoNewsCode/core/otkafka"
"github.com/go-kit/log"
"github.com/oklog/run"
"github.com/pkg/errors"
"github.com/segmentio/kafka-go"
"golang.org/x/sync/errgroup"
)
// Processor dispatch Handler.
type Processor struct {
maker otkafka.ReaderMaker
handlers []*handler
logger logging.LevelLogger
}
// Handler only include Info and Handle func.
type Handler interface {
// Info set the topic name and some config.
Info() *Info
// Handle for *kafka.Message.
Handle(ctx context.Context, msg *kafka.Message) (interface{}, error)
}
// BatchHandler one more Batch method than Handler.
type BatchHandler interface {
Handler
// Batch processing the results returned by Handler.Handle.
Batch(ctx context.Context, data []interface{}) error
}
// HandleFunc type for Handler.Handle Func.
type HandleFunc func(ctx context.Context, msg *kafka.Message) (interface{}, error)
// BatchFunc type for BatchHandler.Batch Func.
type BatchFunc func(ctx context.Context, data []interface{}) error
type in struct {
di.In
Handlers []Handler `group:"ProcessorHandler"`
Maker otkafka.ReaderMaker
Logger log.Logger
}
// New create *Processor Module.
func New(i in) (*Processor, error) {
e := &Processor{
maker: i.Maker,
logger: logging.WithLevel(i.Logger),
handlers: []*handler{},
}
if len(i.Handlers) == 0 {
return nil, errors.New("empty handler list")
}
for _, hh := range i.Handlers {
if err := e.addHandler(hh); err != nil {
return nil, err
}
}
return e, nil
}
// Out to provide Handler to in.Handlers.
type Out struct {
di.Out
Handlers []Handler `group:"ProcessorHandler,flatten"`
}
// NewOut create Out to provide Handler to in.Handlers.
// Usage:
// func newHandlerA(logger log.Logger) processor.Out {
// return processor.NewOut(
// &HandlerA{logger: logger},
// )
// }
// Or
// func newHandlers(logger log.Logger) processor.Out {
// return processor.NewOut(
// &HandlerA{logger: logger},
// &HandlerB{logger: logger},
// )
// }
func NewOut(handlers ...Handler) Out {
return Out{Handlers: handlers}
}
// addHandler create handler and add to Processor.handlers
func (e *Processor) addHandler(h Handler) error {
name := h.Info().name()
reader, err := e.maker.Make(name)
if err != nil {
return err
}
if reader.Config().GroupID == "" {
return errors.New("kafka reader must set consume group")
}
closeMsgOnce := sync.Once{}
var hd = &handler{
msgCh: make(chan *kafka.Message, h.Info().chanSize()),
reader: reader,
handleFunc: h.Handle,
info: h.Info(),
logger: e.logger,
closeBatchCh: func() {
},
}
hd.closeMsgCh = func() {
closeMsgOnce.Do(func() {
close(hd.msgCh)
})
}
batchHandler, isBatchHandler := h.(BatchHandler)
if isBatchHandler {
hd.hasBatch = true
hd.batchFunc = batchHandler.Batch
hd.batchCh = make(chan *batchInfo, h.Info().chanSize())
hd.ticker = time.NewTicker(h.Info().autoBatchInterval())
closeBatchOnce := sync.Once{}
hd.closeBatchCh = func() {
closeBatchOnce.Do(func() {
close(hd.batchCh)
})
}
}
e.handlers = append(e.handlers, hd)
return nil
}
// batchInfo data is the result of message processed by Handler.Handle.
//
// When BatchHandler.Batch is successfully called, then commit the message.
type batchInfo struct {
message *kafka.Message
data interface{}
}
// ProvideRunGroup run workers:
// 1. Fetch message from *kafka.Reader.
// 2. Handle message by Handler.Handle.
// 3. Batch data by BatchHandler.Batch. If batch success then commit message.
func (e *Processor) ProvideRunGroup(group *run.Group) {
if len(e.handlers) == 0 {
return
}
ctx, cancel := context.WithCancel(context.Background())
errorGroup, ctx := errgroup.WithContext(ctx)
for _, one := range e.handlers {
handler := one
for i := 0; i < handler.info.readWorker(); i++ {
errorGroup.Go(func() error {
return handler.read(ctx)
})
}
for i := 0; i < handler.info.handleWorker(); i++ {
errorGroup.Go(func() error {
return handler.handle(ctx)
})
}
if handler.batchFunc != nil {
for i := 0; i < handler.info.batchWorker(); i++ {
errorGroup.Go(func() error {
return handler.batch(ctx)
})
}
}
}
group.Add(func() error {
return errorGroup.Wait()
}, func(err error) {
cancel()
})
}
// handler private processor
// todo It's a bit messy
type handler struct {
reader *kafka.Reader
msgCh chan *kafka.Message
handleFunc HandleFunc
batchCh chan *batchInfo
batchFunc BatchFunc
hasBatch bool
info *Info
ticker *time.Ticker
logger logging.LevelLogger
closeMsgCh func()
closeBatchCh func()
}
// read fetch message from kafka
func (h *handler) read(ctx context.Context) error {
defer h.closeMsgCh()
for {
select {
default:
message, err := h.reader.FetchMessage(ctx)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case h.msgCh <- &message:
}
case <-ctx.Done():
return ctx.Err()
}
}
}
// handle call Handler.Handle
func (h *handler) handle(ctx context.Context) error {
defer h.closeBatchCh()
for {
select {
case msg := <-h.msgCh:
v, err := h.handleFunc(ctx, msg)
if err != nil {
if IsFatalErr(err) {
return err
}
h.logger.Warn("action", "handle", "err", err)
}
if !h.hasBatch || v == nil {
if err := h.commit(*msg); err != nil {
return err
}
continue
}
select {
case <-ctx.Done():
return ctx.Err()
case h.batchCh <- &batchInfo{message: msg, data: v}:
}
case <-ctx.Done():
return ctx.Err()
}
}
}
// batch Call BatchHandler.Batch and commit *kafka.Message.
func (h *handler) batch(ctx context.Context) error {
defer h.ticker.Stop()
var data = make([]interface{}, 0, h.info.batchSize())
var messages = make([]kafka.Message, 0, h.info.batchSize())
doFunc := func() error {
if len(data) == 0 {
return nil
}
if err := h.batchFunc(ctx, data); err != nil {
if IsFatalErr(err) {
return err
}
h.logger.Warn("action", "batch", "err", err)
}
if err := h.commit(messages...); err != nil {
return err
}
data = data[0:0]
messages = messages[0:0]
h.ticker.Reset(h.info.autoBatchInterval())
return nil
}
for {
select {
case v := <-h.batchCh:
if v == nil {
continue
}
if v.message != nil {
messages = append(messages, *v.message)
}
if v.data != nil {
data = append(data, v.data)
}
if len(data) < h.info.batchSize() {
continue
}
if err := doFunc(); err != nil {
return err
}
case <-h.ticker.C:
if err := doFunc(); err != nil {
return err
}
case <-ctx.Done():
return ctx.Err()
}
}
}
func (h *handler) commit(messages ...kafka.Message) error {
if len(messages) > 0 {
if err := h.reader.CommitMessages(context.Background(), messages...); err != nil {
return err
}
}
return nil
}