Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(processor): improve batch processor shutdown and channel handling #421

Merged
merged 2 commits into from
Dec 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions pkg/processor/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,21 +439,27 @@ func (bvp *BatchItemProcessor[T]) waitForBatchCompletion(ctx context.Context, it

func (bvp *BatchItemProcessor[T]) batchBuilder(ctx context.Context) {
log := bvp.log.WithField("module", "batch_builder")

var batch []*TraceableItem[T]

for {
select {
case <-bvp.stopWorkersCh:
log.Info("Stopping batch builder")

return
case item := <-bvp.queue:
case item, ok := <-bvp.queue:
if !ok {
// Channel is closed, send any remaining items in the batch for processing
// before shutting down.
if len(batch) > 0 {
bvp.sendBatch(batch, "shutdown")
}

return
}

if item == nil {
bvp.metrics.IncItemsDroppedBy(bvp.name, float64(1))

bvp.log.Warnf("Attempted to build a batch with a nil item. This item has been dropped. This probably shouldn't happen and is likely a bug.")

continue
}

Expand Down Expand Up @@ -505,19 +511,21 @@ func (bvp *BatchItemProcessor[T]) worker(ctx context.Context, number int) {
}

func (bvp *BatchItemProcessor[T]) drainQueue() {
bvp.log.Info("Draining queue: waiting for the batch builder to pull all the items from the queue")
bvp.log.Info("Draining queue: waiting for the batch builder to process remaining items")

// First wait for queue to be processed
for len(bvp.queue) > 0 {
time.Sleep(10 * time.Millisecond)
}

bvp.log.Info("Draining queue: waiting for workers to finish processing batches")

for len(bvp.queue) > 0 {
<-bvp.queue
// Then wait for any in-flight batches
for len(bvp.batchCh) > 0 {
time.Sleep(10 * time.Millisecond)
}

bvp.log.Info("Draining queue: all batches finished")
bvp.log.Info("Draining queue: all items processed")

close(bvp.queue)
}
Expand Down
Loading