-
Notifications
You must be signed in to change notification settings - Fork 323
/
kafka_worker.go
624 lines (555 loc) · 23.3 KB
/
kafka_worker.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
package worker
import (
"context"
"encoding/binary"
"fmt"
"math"
"strings"
"time"
"github.com/highlight-run/highlight/backend/clickhouse"
"github.com/highlight-run/highlight/backend/email"
kafka_queue "github.com/highlight-run/highlight/backend/kafka-queue"
kafkaqueue "github.com/highlight-run/highlight/backend/kafka-queue"
"github.com/highlight-run/highlight/backend/model"
privateModel "github.com/highlight-run/highlight/backend/private-graph/graph/model"
"github.com/highlight-run/highlight/backend/util"
"github.com/highlight/highlight/sdk/highlight-go"
hmetric "github.com/highlight/highlight/sdk/highlight-go/metric"
e "github.com/pkg/errors"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/trace"
)
func (k *KafkaWorker) processWorkerError(ctx context.Context, task kafkaqueue.RetryableMessage, err error, start time.Time) {
log.WithContext(ctx).
WithError(err).
WithField("type", task.GetType()).
WithField("duration", time.Since(start).Seconds()).
Errorf("task %+v failed: %s", task, err)
if task.GetFailures() >= task.GetMaxRetries() {
log.WithContext(ctx).
WithError(err).
WithField("type", task.GetType()).
WithField("failures", task.GetFailures()).
WithField("duration", time.Since(start).Seconds()).
Errorf("task %+v failed after %d retries", task, task.GetFailures())
} else {
hmetric.Histogram(ctx, "worker.kafka.processed.taskFailures", float64(task.GetFailures()), nil, 1)
}
task.SetFailures(task.GetFailures() + 1)
}
func (k *KafkaWorker) log(ctx context.Context, task kafkaqueue.RetryableMessage, msg ...interface{}) {
if task == nil {
return
}
m := task.GetKafkaMessage()
if m == nil {
return
}
if m.Partition == 408 || m.Partition == 58 || m.Partition == 289 {
log.WithContext(ctx).
WithField("key", string(m.Key)).
WithField("offset", m.Offset).
WithField("taskType", task.GetType()).
WithField("partition", m.Partition).
Info(msg...)
}
}
func (k *KafkaWorker) ProcessMessages(ctx context.Context) {
for {
func() {
var err error
defer util.Recover()
s, sCtx := util.StartSpanFromContext(ctx, "processPublicWorkerMessage", util.ResourceName("worker.kafka.process"), util.WithSpanKind(trace.SpanKindConsumer))
s.SetAttribute("worker.goroutine", k.WorkerThread)
defer s.Finish(err)
s1, _ := util.StartSpanFromContext(sCtx, "worker.kafka.receiveMessage")
task := k.KafkaQueue.Receive(ctx)
s1.Finish()
if task == nil {
return
} else if task.GetType() == kafkaqueue.HealthCheck {
return
}
s.SetAttribute("taskType", task.GetType())
s.SetAttribute("partition", task.GetKafkaMessage().Partition)
s.SetAttribute("partitionKey", string(task.GetKafkaMessage().Key))
k.log(ctx, task, "received message")
s2, _ := util.StartSpanFromContext(sCtx, "worker.kafka.processMessage")
for i := 0; i <= task.GetMaxRetries(); i++ {
k.log(ctx, task, "starting processing", i)
start := time.Now()
publicWorkerMessage, ok := task.(*kafka_queue.Message)
if !ok {
k.processWorkerError(ctx, task, e.New("failed to cast as publicWorkerMessage"), start)
break
}
if err = k.Worker.processPublicWorkerMessage(sCtx, publicWorkerMessage); err != nil {
k.processWorkerError(ctx, task, err, start)
} else {
break
}
}
k.log(ctx, task, "finished processing", task.GetFailures())
s.SetAttribute("taskFailures", task.GetFailures())
s2.Finish(err)
s3, _ := util.StartSpanFromContext(sCtx, "worker.kafka.commitMessage")
k.KafkaQueue.Commit(ctx, task.GetKafkaMessage())
k.log(ctx, task, "committed")
s3.Finish()
hmetric.Incr(ctx, "worker.kafka.processed.total", nil, 1)
}()
}
}
// DefaultBatchFlushSize set per https://clickhouse.com/docs/en/cloud/bestpractices/bulk-inserts
const DefaultBatchFlushSize = 10000
const DefaultBatchedFlushTimeout = 5 * time.Second
const SessionsMaxRowsPostgres = 500
const ErrorGroupsMaxRowsPostgres = 500
const ErrorObjectsMaxRowsPostgres = 500
const MinRetryDelay = 250 * time.Millisecond
type KafkaWorker struct {
KafkaQueue *kafkaqueue.Queue
Worker *Worker
WorkerThread int
}
func (k *KafkaBatchWorker) flush(ctx context.Context) error {
s, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush", k.Name)))
s.SetAttribute("BatchSize", len(k.messages))
defer s.Finish()
var syncSessionIds []int
var syncErrorGroupIds []int
var syncErrorObjectIds []int
var logRows []*clickhouse.LogRow
var traceRows []*clickhouse.ClickhouseTraceRow
var lastMsg kafkaqueue.RetryableMessage
var oldestMsg = time.Now()
readSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.readMessages", k.Name)))
for _, lastMsg = range k.messages {
if lastMsg.GetKafkaMessage().Time.Before(oldestMsg) {
oldestMsg = lastMsg.GetKafkaMessage().Time
}
publicWorkerMessage, ok := lastMsg.(*kafka_queue.Message)
if !ok && lastMsg.GetType() != kafkaqueue.PushLogsFlattened && lastMsg.GetType() != kafkaqueue.PushTracesFlattened {
log.WithContext(ctx).Errorf("type assertion failed for *kafka_queue.Message")
continue
}
switch lastMsg.GetType() {
case kafkaqueue.SessionDataSync:
syncSessionIds = append(syncSessionIds, publicWorkerMessage.SessionDataSync.SessionID)
case kafkaqueue.ErrorGroupDataSync:
syncErrorGroupIds = append(syncErrorGroupIds, publicWorkerMessage.ErrorGroupDataSync.ErrorGroupID)
case kafkaqueue.ErrorObjectDataSync:
syncErrorObjectIds = append(syncErrorObjectIds, publicWorkerMessage.ErrorObjectDataSync.ErrorObjectID)
case kafkaqueue.PushLogsFlattened:
logRow, ok := lastMsg.(*kafka_queue.LogRowMessage)
if !ok {
log.WithContext(ctx).Errorf("type assertion failed for *kafka_queue.LogRowMessage")
continue
}
if logRow != nil {
logRows = append(logRows, logRow.LogRow)
}
case kafkaqueue.PushTracesFlattened:
traceRow, ok := lastMsg.(*kafka_queue.TraceRowMessage)
if !ok {
log.WithContext(ctx).Errorf("type assertion failed for *kafka_queue.TraceRowMessage")
continue
}
if traceRow != nil {
traceRows = append(traceRows, traceRow.ClickhouseTraceRow)
}
case kafkaqueue.PushLogs:
logRow := publicWorkerMessage.PushLogs.LogRow
if logRow != nil {
logRows = append(logRows, logRow)
}
case kafkaqueue.PushTraces:
traceRow := publicWorkerMessage.PushTraces.TraceRow
if traceRow != nil {
traceRows = append(traceRows, clickhouse.ConvertTraceRow(traceRow))
}
default:
log.WithContext(ctx).Errorf("unknown message type received by batch worker %+v", lastMsg.GetType())
}
}
k.messages = []kafka_queue.RetryableMessage{}
readSpan.SetAttribute("MaxIngestDelay", time.Since(oldestMsg).Seconds())
readSpan.Finish()
workSpan, wCtx := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.work", k.Name)))
if len(syncSessionIds) > 0 || len(syncErrorGroupIds) > 0 || len(syncErrorObjectIds) > 0 {
if err := k.flushDataSync(wCtx, syncSessionIds, syncErrorGroupIds, syncErrorObjectIds); err != nil {
workSpan.Finish(err)
return err
}
}
if len(logRows) > 0 {
if err := k.flushLogs(wCtx, logRows); err != nil {
workSpan.Finish(err)
return err
}
}
if len(traceRows) > 0 {
if err := k.flushTraces(wCtx, traceRows); err != nil {
workSpan.Finish(err)
return err
}
}
workSpan.Finish()
commitSpan, cCtx := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.commit", k.Name)))
if lastMsg != nil {
k.KafkaQueue.Commit(cCtx, lastMsg.GetKafkaMessage())
}
commitSpan.Finish()
return nil
}
func (k *KafkaBatchWorker) getQuotaExceededByProject(ctx context.Context, projectIds map[uint32]struct{}, productType model.PricingProductType) (map[uint32]bool, error) {
spanW, ctxW := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.checkBillingQuotas", k.Name)))
// If it's saved in Redis that a project has exceeded / not exceeded
// its quota, use that value. Else, add the projectId to a list of
// projects to query.
quotaExceededByProject := map[uint32]bool{}
projectsToQuery := []uint32{}
for projectId := range projectIds {
exceeded, err := k.Worker.Resolver.Redis.IsBillingQuotaExceeded(ctxW, int(projectId), productType)
if err != nil {
log.WithContext(ctxW).Error(err)
continue
}
if exceeded != nil {
quotaExceededByProject[projectId] = *exceeded
} else {
projectsToQuery = append(projectsToQuery, projectId)
}
}
// For any projects to query, get the associated workspace,
// check if that workspace is within the quota,
// and write the result to redis.
for _, projectId := range projectsToQuery {
project, err := k.Worker.Resolver.Store.GetProject(ctx, int(projectId))
if err != nil {
log.WithContext(ctxW).Error(e.Wrap(err, "error querying project"))
continue
}
var workspace model.Workspace
if err := k.Worker.Resolver.DB.WithContext(ctx).Model(&workspace).
Where("id = ?", project.WorkspaceID).Find(&workspace).Error; err != nil {
log.WithContext(ctxW).Error(e.Wrap(err, "error querying workspace"))
continue
}
projects := []model.Project{}
if err := k.Worker.Resolver.DB.WithContext(ctx).Order("name ASC").Model(&workspace).Association("Projects").Find(&projects); err != nil {
log.WithContext(ctxW).Error(e.Wrap(err, "error querying associated projects"))
continue
}
workspace.Projects = projects
withinBillingQuota, quotaPercent := k.Worker.PublicResolver.IsWithinQuota(ctxW, productType, &workspace, time.Now())
quotaExceededByProject[projectId] = !withinBillingQuota
if err := k.Worker.Resolver.Redis.SetBillingQuotaExceeded(ctxW, int(projectId), productType, !withinBillingQuota); err != nil {
log.WithContext(ctxW).Error(err)
return nil, err
}
// Send alert emails if above the relevant thresholds
go func() {
defer util.Recover()
var emailType email.EmailType
if quotaPercent >= 1 {
if productType == model.PricingProductTypeLogs {
emailType = email.BillingLogsUsage100Percent
} else if productType == model.PricingProductTypeTraces {
emailType = email.BillingTracesUsage100Percent
}
} else if quotaPercent >= .8 {
if productType == model.PricingProductTypeLogs {
emailType = email.BillingLogsUsage80Percent
} else if productType == model.PricingProductTypeTraces {
emailType = email.BillingTracesUsage80Percent
}
}
if emailType != "" {
if err := model.SendBillingNotifications(ctx, k.Worker.PublicResolver.DB, k.Worker.PublicResolver.MailClient, emailType, &workspace); err != nil {
log.WithContext(ctx).Error(e.Wrap(err, "failed to send billing notifications"))
}
}
}()
}
spanW.Finish()
return quotaExceededByProject, nil
}
func (k *KafkaBatchWorker) flushLogs(ctx context.Context, logRows []*clickhouse.LogRow) error {
projectIds := map[uint32]struct{}{}
for _, row := range logRows {
projectIds[row.ProjectId] = struct{}{}
}
quotaExceededByProject, err := k.getQuotaExceededByProject(ctx, projectIds, model.PricingProductTypeLogs)
if err != nil {
return err
}
var markBackendSetupProjectIds []uint32
var filteredRows []*clickhouse.LogRow
for _, logRow := range logRows {
// create service record for any services found in ingested logs
if logRow.ServiceName != "" {
spanX, ctxX := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.UpsertService", k.Name)))
project, err := k.Worker.Resolver.Store.GetProject(ctx, int(logRow.ProjectId))
if err == nil && project != nil {
_, err := k.Worker.Resolver.Store.UpsertService(ctx, *project, logRow.ServiceName, logRow.LogAttributes)
if err != nil {
log.WithContext(ctxX).Error(e.Wrap(err, "failed to create service"))
}
}
spanX.Finish()
}
if logRow.Source == privateModel.LogSourceBackend {
markBackendSetupProjectIds = append(markBackendSetupProjectIds, logRow.ProjectId)
}
// Filter out any log rows for projects where the log quota has been exceeded
if quotaExceededByProject[logRow.ProjectId] {
continue
}
// Temporarily filter NextJS logs
// TODO - remove this condition when https://github.com/highlight/highlight/issues/6181 is fixed
if !strings.HasPrefix(logRow.Body, "ENOENT: no such file or directory") && !strings.HasPrefix(logRow.Body, "connect ECONNREFUSED") {
filteredRows = append(filteredRows, logRow)
}
}
wSpan, wCtx := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.process", k.Name)))
wSpan.SetAttribute("BatchSize", len(k.messages))
wSpan.SetAttribute("NumProjects", len(projectIds))
for _, projectId := range markBackendSetupProjectIds {
err := k.Worker.PublicResolver.MarkBackendSetupImpl(wCtx, int(projectId), model.MarkBackendSetupTypeLogs)
if err != nil {
log.WithContext(wCtx).WithError(err).Error("failed to mark backend logs setup")
return err
}
}
span, ctxT := util.StartSpanFromContext(wCtx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.clickhouse.logs", k.Name)))
span.SetAttribute("NumLogRows", len(logRows))
span.SetAttribute("NumFilteredRows", len(filteredRows))
err = k.Worker.PublicResolver.Clickhouse.BatchWriteLogRows(ctxT, filteredRows)
span.Finish(err)
if err != nil {
log.WithContext(ctxT).WithError(err).Error("failed to batch write logs to clickhouse")
return err
}
wSpan.Finish()
return nil
}
func (k *KafkaBatchWorker) flushTraces(ctx context.Context, traceRows []*clickhouse.ClickhouseTraceRow) error {
markBackendSetupProjectIds := map[uint32]struct{}{}
projectIds := map[uint32]struct{}{}
for _, trace := range traceRows {
// Skip traces with a `http.method` attribute as likely autoinstrumented frontend traces
if _, found := trace.TraceAttributes["http.method"]; !found {
markBackendSetupProjectIds[trace.ProjectId] = struct{}{}
}
projectIds[trace.ProjectId] = struct{}{}
}
quotaExceededByProject, err := k.getQuotaExceededByProject(ctx, projectIds, model.PricingProductTypeLogs)
if err != nil {
return err
}
filteredTraceRows := []*clickhouse.ClickhouseTraceRow{}
for _, trace := range traceRows {
if quotaExceededByProject[trace.ProjectId] {
continue
}
filteredTraceRows = append(filteredTraceRows, trace)
}
span, ctxT := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.clickhouse", k.Name)), util.WithHighlightTracingDisabled(true))
span.SetAttribute("NumTraceRows", len(traceRows))
span.SetAttribute("PayloadSizeBytes", binary.Size(traceRows))
err = k.Worker.PublicResolver.Clickhouse.BatchWriteTraceRows(ctxT, filteredTraceRows)
defer span.Finish(err)
if err != nil {
log.WithContext(ctxT).WithError(err).Error("failed to batch write traces to clickhouse")
span.Finish(err)
return err
}
for projectId := range markBackendSetupProjectIds {
err := k.Worker.PublicResolver.MarkBackendSetupImpl(ctx, int(projectId), model.MarkBackendSetupTypeTraces)
if err != nil {
log.WithContext(ctx).WithError(err).Error("failed to mark backend traces setup")
return err
}
}
return nil
}
func (k *KafkaBatchWorker) flushDataSync(ctx context.Context, sessionIds []int, errorGroupIds []int, errorObjectIds []int) error {
sessionIdChunks := lo.Chunk(lo.Uniq(sessionIds), SessionsMaxRowsPostgres)
if len(sessionIdChunks) > 0 {
allSessionObjs := []*model.Session{}
for _, chunk := range sessionIdChunks {
sessionObjs := []*model.Session{}
sessionSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.readSessions", k.Name)))
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Model(&model.Session{}).Preload("ViewedByAdmins").Where("id in ?", chunk).Find(&sessionObjs).Error; err != nil {
log.WithContext(ctx).Error(err)
return err
}
sessionSpan.Finish()
fieldObjs := []*model.Field{}
fieldSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.readFields", k.Name)))
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Model(&model.Field{}).Where("id IN (SELECT field_id FROM session_fields sf WHERE sf.session_id IN ?)", chunk).Find(&fieldObjs).Error; err != nil {
log.WithContext(ctx).Error(err)
return err
}
fieldSpan.Finish()
fieldsById := lo.KeyBy(fieldObjs, func(f *model.Field) int64 {
return f.ID
})
type sessionField struct {
SessionID int
FieldID int64
}
sessionFieldObjs := []*sessionField{}
sessionFieldSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.readSessionFields", k.Name)))
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Table("session_fields").Where("session_id IN ?", chunk).Find(&sessionFieldObjs).Error; err != nil {
log.WithContext(ctx).Error(err)
return err
}
sessionFieldSpan.Finish()
sessionToFields := lo.GroupBy(sessionFieldObjs, func(sf *sessionField) int {
return sf.SessionID
})
for _, session := range sessionObjs {
session.Fields = lo.Map(sessionToFields[session.ID], func(sf *sessionField, _ int) *model.Field {
return fieldsById[sf.FieldID]
})
span := util.StartSpan(
"IsIngestedBy", util.ResourceName("sampling"),
util.Tag(highlight.ProjectIDAttribute, session.ProjectID),
util.Tag(highlight.TraceTypeAttribute, highlight.TraceTypeHighlightInternal),
util.Tag("product", privateModel.ProductTypeSessions),
)
// fields are populated, so calculate whether session is excluded
if k.Worker.PublicResolver.IsSessionExcludedByFilter(ctx, session) {
reason := privateModel.SessionExcludedReasonExclusionFilter
session.Excluded = true
session.ExcludedReason = &reason
span.SetAttribute("reason", session.ExcludedReason)
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Model(&model.Session{Model: model.Model{ID: session.ID}}).
Select("Excluded", "ExcludedReason").Updates(&session).Error; err != nil {
return err
}
}
span.SetAttribute("ingested", !session.Excluded)
span.Finish()
}
allSessionObjs = append(allSessionObjs, sessionObjs...)
}
chSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.flush.clickhouse", k.Name)))
err := k.Worker.PublicResolver.Clickhouse.WriteSessions(ctx, allSessionObjs)
defer chSpan.Finish(err)
if err != nil {
log.WithContext(ctx).Error(err)
return err
}
}
errorGroupIdChunks := lo.Chunk(lo.Uniq(errorGroupIds), ErrorGroupsMaxRowsPostgres)
if len(errorGroupIdChunks) > 0 {
allErrorGroups := []*model.ErrorGroup{}
for _, chunk := range errorGroupIdChunks {
errorGroups := []*model.ErrorGroup{}
errorGroupSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName("worker.kafka.datasync.readErrorGroups"))
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Model(&model.ErrorGroup{}).Joins("ErrorTag").Where("error_groups.id in ?", chunk).Find(&errorGroups).Error; err != nil {
log.WithContext(ctx).Error(err)
return err
}
errorGroupSpan.Finish()
allErrorGroups = append(allErrorGroups, errorGroups...)
}
chSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName("worker.kafka.datasync.writeClickhouse.errorGroups"))
if err := k.Worker.PublicResolver.Clickhouse.WriteErrorGroups(ctx, allErrorGroups); err != nil {
log.WithContext(ctx).Error(err)
return err
}
chSpan.Finish()
}
errorObjectIdChunks := lo.Chunk(lo.Uniq(errorObjectIds), ErrorObjectsMaxRowsPostgres)
if len(errorObjectIdChunks) > 0 {
allErrorObjects := []*model.ErrorObject{}
for _, chunk := range errorObjectIdChunks {
errorObjects := []*model.ErrorObject{}
errorObjectSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName("worker.kafka.datasync.readErrorObjects"))
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Model(&model.ErrorObject{}).Where("id in ?", chunk).Find(&errorObjects).Error; err != nil {
log.WithContext(ctx).Error(err)
return err
}
errorObjectSpan.Finish()
allErrorObjects = append(allErrorObjects, errorObjects...)
}
// error objects -> filter non nil -> get session id -> get unique
uniqueSessionIds := lo.Uniq(lo.Map(lo.Filter(
allErrorObjects,
func(eo *model.ErrorObject, _ int) bool { return eo.SessionID != nil }),
func(eo *model.ErrorObject, _ int) int { return *eo.SessionID }))
sessionIdChunks := lo.Chunk(uniqueSessionIds, SessionsMaxRowsPostgres)
allSessions := []*model.Session{}
for _, chunk := range sessionIdChunks {
sessions := []*model.Session{}
sessionSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName("worker.kafka.datasync.readErrorObjectSessions"))
if err := k.Worker.PublicResolver.DB.WithContext(ctx).Model(&model.Session{}).Where("id in ?", chunk).Find(&sessions).Error; err != nil {
log.WithContext(ctx).Error(err)
return err
}
sessionSpan.Finish()
allSessions = append(allSessions, sessions...)
}
chSpan, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName("worker.kafka.datasync.writeClickhouse.errorObjects"))
if err := k.Worker.PublicResolver.Clickhouse.WriteErrorObjects(ctx, allErrorObjects, allSessions); err != nil {
log.WithContext(ctx).Error(err)
return err
}
chSpan.Finish()
}
return nil
}
func (k *KafkaBatchWorker) processWorkerError(ctx context.Context, attempt int, err error) {
log.WithContext(ctx).WithError(err).WithField("worker_name", k.Name).WithField("attempt", attempt).Errorf("batched worker task failed: %s", err)
// exponential backoff on retries
time.Sleep(MinRetryDelay * time.Duration(math.Pow(2, float64(attempt))))
}
func (k *KafkaBatchWorker) ProcessMessages(ctx context.Context) {
for {
func() {
defer util.Recover()
s, ctx := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.process", k.Name)), util.WithHighlightTracingDisabled(k.TracingDisabled))
s.SetAttribute("worker.goroutine", k.WorkerThread)
s.SetAttribute("BatchSize", len(k.messages))
defer s.Finish()
s1, _ := util.StartSpanFromContext(ctx, util.KafkaBatchWorkerOp, util.ResourceName(fmt.Sprintf("worker.kafka.%s.receive", k.Name)))
// wait for up to k.BatchedFlushTimeout to receive a message
// before proceeding to flush previously batched messages
// and restarting the receive call
receiveCtx, receiveCancel := context.WithTimeout(ctx, k.BatchedFlushTimeout)
defer receiveCancel()
task := k.KafkaQueue.Receive(receiveCtx)
s1.Finish()
if task != nil && task.GetType() != kafkaqueue.HealthCheck {
k.messages = append(k.messages, task)
}
if time.Since(k.lastFlush) > k.BatchedFlushTimeout || len(k.messages) >= k.BatchFlushSize {
s.SetAttribute("FlushDelay", time.Since(k.lastFlush).Seconds())
for i := 0; i <= kafkaqueue.TaskRetries; i++ {
if err := k.flush(ctx); err != nil {
k.processWorkerError(ctx, i, err)
} else {
break
}
}
k.lastFlush = time.Now()
}
}()
}
}
type KafkaBatchWorker struct {
KafkaQueue *kafkaqueue.Queue
Worker *Worker
WorkerThread int
BatchFlushSize int
BatchedFlushTimeout time.Duration
Name string
TracingDisabled bool
lastFlush time.Time
messages []kafkaqueue.RetryableMessage
}