-
Notifications
You must be signed in to change notification settings - Fork 15
/
bulk.go
419 lines (364 loc) · 10.3 KB
/
bulk.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package bulk
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/Trendyol/go-dcp/helpers"
"golang.org/x/sync/errgroup"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/Trendyol/go-dcp/logger"
"github.com/Trendyol/go-dcp-elasticsearch/config"
dcpElasticsearch "github.com/Trendyol/go-dcp-elasticsearch/elasticsearch"
"github.com/Trendyol/go-dcp-elasticsearch/elasticsearch/client"
"github.com/Trendyol/go-dcp-elasticsearch/elasticsearch/document"
"github.com/Trendyol/go-dcp-elasticsearch/helper"
"github.com/Trendyol/go-dcp/models"
"github.com/elastic/go-elasticsearch/v7"
"github.com/json-iterator/go"
)
type Bulk struct {
sinkResponseHandler dcpElasticsearch.SinkResponseHandler
metric *Metric
collectionIndexMapping map[string]string
config *config.Config
batchKeys map[string]int
dcpCheckpointCommit func()
batchTicker *time.Ticker
isClosed chan bool
actionCh chan document.ESActionDocument
esClient *elasticsearch.Client
readers []*helper.MultiDimByteReader
typeName []byte
batch []BatchItem
batchIndex int
batchSize int
batchSizeLimit int
batchTickerDuration time.Duration
batchByteSizeLimit int
batchByteSize int
concurrentRequest int
flushLock sync.Mutex
isDcpRebalancing bool
}
type Metric struct {
ProcessLatencyMs int64
BulkRequestProcessLatencyMs int64
}
type BatchItem struct {
Action *document.ESActionDocument
Bytes []byte
}
func NewBulk(
config *config.Config,
dcpCheckpointCommit func(),
sinkResponseHandler dcpElasticsearch.SinkResponseHandler,
) (*Bulk, error) {
esClient, err := client.NewElasticClient(config)
if err != nil {
return nil, err
}
readers := make([]*helper.MultiDimByteReader, config.Elasticsearch.ConcurrentRequest)
for i := 0; i < config.Elasticsearch.ConcurrentRequest; i++ {
readers[i] = helper.NewMultiDimByteReader(nil)
}
bulk := &Bulk{
batchTickerDuration: config.Elasticsearch.BatchTickerDuration,
batchTicker: time.NewTicker(config.Elasticsearch.BatchTickerDuration),
actionCh: make(chan document.ESActionDocument, config.Elasticsearch.BatchSizeLimit),
batchSizeLimit: config.Elasticsearch.BatchSizeLimit,
batchByteSizeLimit: helpers.ResolveUnionIntOrStringValue(config.Elasticsearch.BatchByteSizeLimit),
isClosed: make(chan bool, 1),
dcpCheckpointCommit: dcpCheckpointCommit,
esClient: esClient,
metric: &Metric{},
collectionIndexMapping: config.Elasticsearch.CollectionIndexMapping,
config: config,
typeName: helper.Byte(config.Elasticsearch.TypeName),
readers: readers,
concurrentRequest: config.Elasticsearch.ConcurrentRequest,
batchKeys: make(map[string]int, config.Elasticsearch.BatchSizeLimit),
sinkResponseHandler: sinkResponseHandler,
}
if sinkResponseHandler != nil {
sinkResponseHandler.OnInit(&dcpElasticsearch.SinkResponseHandlerInitContext{
Config: config,
ElasticsearchClient: esClient,
})
}
return bulk, nil
}
func (b *Bulk) StartBulk() {
for range b.batchTicker.C {
b.flushMessages()
}
}
func (b *Bulk) PrepareStartRebalancing() {
b.flushLock.Lock()
defer b.flushLock.Unlock()
b.isDcpRebalancing = true
b.batch = b.batch[:0]
b.batchKeys = make(map[string]int, b.batchSizeLimit)
b.batchIndex = 0
b.batchSize = 0
b.batchByteSize = 0
}
func (b *Bulk) PrepareEndRebalancing() {
b.flushLock.Lock()
defer b.flushLock.Unlock()
b.isDcpRebalancing = false
}
func (b *Bulk) AddActions(
ctx *models.ListenerContext,
eventTime time.Time,
actions []document.ESActionDocument,
collectionName string,
isLastChunk bool,
) {
b.flushLock.Lock()
if b.isDcpRebalancing {
logger.Log.Warn("could not add new message to batch while rebalancing")
b.flushLock.Unlock()
return
}
for i, action := range actions {
indexName := b.getIndexName(collectionName, action.IndexName)
actions[i].IndexName = indexName
value := getEsActionJSON(
action.ID,
action.Type,
actions[i].IndexName,
action.Routing,
action.Source,
b.typeName,
)
key := getActionKey(actions[i])
if batchIndex, ok := b.batchKeys[key]; ok {
b.batchByteSize += len(value) - len(b.batch[batchIndex].Bytes)
b.batch[batchIndex] = BatchItem{
Action: &actions[i],
Bytes: value,
}
} else {
b.batch = append(b.batch, BatchItem{
Action: &actions[i],
Bytes: value,
})
b.batchKeys[key] = b.batchIndex
b.batchIndex++
b.batchSize++
b.batchByteSize += len(value)
}
}
if isLastChunk {
ctx.Ack()
}
b.flushLock.Unlock()
if isLastChunk {
b.metric.ProcessLatencyMs = time.Since(eventTime).Milliseconds()
}
if b.batchSize >= b.batchSizeLimit || b.batchByteSize >= b.batchByteSizeLimit {
b.flushMessages()
}
}
var (
indexPrefix = helper.Byte(`{"index":{"_index":"`)
deletePrefix = helper.Byte(`{"delete":{"_index":"`)
idPrefix = helper.Byte(`","_id":"`)
typePrefix = helper.Byte(`","_type":"`)
routingPrefix = helper.Byte(`","routing":"`)
postFix = helper.Byte(`"}}`)
)
var metaPool = sync.Pool{
New: func() interface{} {
return []byte{}
},
}
func getEsActionJSON(docID []byte, action document.EsAction, indexName string, routing *string, source []byte, typeName []byte) []byte {
meta := metaPool.Get().([]byte)[:0]
if action == document.Index {
meta = append(meta, indexPrefix...)
} else {
meta = append(meta, deletePrefix...)
}
meta = append(meta, helper.Byte(indexName)...)
meta = append(meta, idPrefix...)
meta = append(meta, helper.EscapePredefinedBytes(docID)...)
if routing != nil {
meta = append(meta, routingPrefix...)
meta = append(meta, helper.Byte(*routing)...)
}
if typeName != nil {
meta = append(meta, typePrefix...)
meta = append(meta, typeName...)
}
meta = append(meta, postFix...)
if action == document.Index {
meta = append(meta, '\n')
meta = append(meta, source...)
}
meta = append(meta, '\n')
return meta
}
func (b *Bulk) Close() {
b.batchTicker.Stop()
b.flushMessages()
}
func (b *Bulk) flushMessages() {
b.flushLock.Lock()
defer b.flushLock.Unlock()
if b.isDcpRebalancing {
return
}
if len(b.batch) > 0 {
err := b.bulkRequest()
if err != nil && b.sinkResponseHandler == nil {
panic(err)
}
b.batchTicker.Reset(b.batchTickerDuration)
for _, batch := range b.batch {
//nolint:staticcheck
metaPool.Put(batch.Bytes)
}
b.batch = b.batch[:0]
b.batchKeys = make(map[string]int, b.batchSizeLimit)
b.batchIndex = 0
b.batchSize = 0
b.batchByteSize = 0
}
b.dcpCheckpointCommit()
}
func (b *Bulk) requestFunc(concurrentRequestIndex int, batchItems []BatchItem) func() error {
return func() error {
reader := b.readers[concurrentRequestIndex]
reader.Reset(getBytes(batchItems))
r, err := b.esClient.Bulk(reader)
if err != nil {
return err
}
errorData, err := hasResponseError(r)
b.executeSinkResponseHandler(getActions(batchItems), errorData)
if err != nil {
return err
}
return nil
}
}
func (b *Bulk) bulkRequest() error {
eg, _ := errgroup.WithContext(context.Background())
chunks := helpers.ChunkSlice(b.batch, b.concurrentRequest)
startedTime := time.Now()
for i, chunk := range chunks {
if len(chunk) > 0 {
eg.Go(b.requestFunc(i, chunk))
}
}
err := eg.Wait()
b.metric.BulkRequestProcessLatencyMs = time.Since(startedTime).Milliseconds()
return err
}
func (b *Bulk) GetMetric() *Metric {
return b.metric
}
func hasResponseError(r *esapi.Response) (map[string]string, error) {
if r == nil {
return nil, fmt.Errorf("esapi response is nil")
}
if r.IsError() {
return nil, fmt.Errorf("bulk request has error %v", r.String())
}
rb := new(bytes.Buffer)
defer r.Body.Close()
_, err := rb.ReadFrom(r.Body)
if err != nil {
return nil, err
}
b := make(map[string]any)
err = jsoniter.Unmarshal(rb.Bytes(), &b)
if err != nil {
return nil, err
}
hasError, ok := b["errors"].(bool)
if !ok || !hasError {
return nil, nil
}
return joinErrors(b)
}
func joinErrors(body map[string]any) (map[string]string, error) {
var sb strings.Builder
ivd := make(map[string]string)
sb.WriteString("bulk request has error. Errors will be listed below:\n")
items, ok := body["items"].([]any)
if !ok {
return nil, nil
}
for _, i := range items {
item, ok := i.(map[string]any)
if !ok {
continue
}
for _, v := range item {
iv, ok := v.(map[string]any)
if !ok {
continue
}
if iv["error"] != nil {
itemValue := fmt.Sprintf("%v\n", i)
sb.WriteString(itemValue)
itemValueDataKey := fmt.Sprintf("%s:%s", iv["_id"].(string), iv["_index"].(string))
ivd[itemValueDataKey] = itemValue
}
}
}
return ivd, fmt.Errorf(sb.String())
}
func (b *Bulk) getIndexName(collectionName, actionIndexName string) string {
if actionIndexName != "" {
return actionIndexName
}
indexName := b.collectionIndexMapping[collectionName]
if indexName == "" {
panic(fmt.Sprintf("there is no index mapping for collection: %s on your configuration", collectionName))
}
return indexName
}
func (b *Bulk) executeSinkResponseHandler(batchActions []*document.ESActionDocument, errorData map[string]string) {
if b.sinkResponseHandler == nil {
return
}
for _, action := range batchActions {
key := getActionKey(*action)
if _, ok := errorData[key]; ok {
b.sinkResponseHandler.OnError(&dcpElasticsearch.SinkResponseHandlerContext{
Action: action,
Err: fmt.Errorf(errorData[key]),
})
} else {
b.sinkResponseHandler.OnSuccess(&dcpElasticsearch.SinkResponseHandlerContext{
Action: action,
})
}
}
}
func getActionKey(action document.ESActionDocument) string {
if action.Routing != nil {
return fmt.Sprintf("%s:%s:%s", action.ID, action.IndexName, *action.Routing)
}
return fmt.Sprintf("%s:%s", action.ID, action.IndexName)
}
func getBytes(batchItems []BatchItem) [][]byte {
var batchBytes [][]byte
for _, batchItem := range batchItems {
batchBytes = append(batchBytes, batchItem.Bytes)
}
return batchBytes
}
func getActions(batchItems []BatchItem) []*document.ESActionDocument {
var batchActions []*document.ESActionDocument
for _, batchItem := range batchItems {
batchActions = append(batchActions, batchItem.Action)
}
return batchActions
}