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

fix: BatchError.Add() non thread safe #3946

Merged
merged 2 commits into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
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
9 changes: 8 additions & 1 deletion core/errorx/batcherror.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package errorx

import "bytes"
import (
"bytes"
"sync"
)

type (
// A BatchError is an error that can hold multiple errors.
BatchError struct {
mu sync.Mutex
errs errorArray
}

Expand All @@ -13,6 +17,9 @@ type (

// Add adds errs to be, nil errors are ignored.
func (be *BatchError) Add(errs ...error) {
be.mu.Lock()
defer be.mu.Unlock()

for _, err := range errs {
if err != nil {
be.errs = append(be.errs, err)
Expand Down
24 changes: 22 additions & 2 deletions core/errorx/batcherror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package errorx
import (
"errors"
"fmt"
"sync"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -33,7 +34,7 @@ func TestBatchErrorNilFromFunc(t *testing.T) {
func TestBatchErrorOneError(t *testing.T) {
var batch BatchError
batch.Add(errors.New(err1))
assert.NotNil(t, batch)
assert.NotNil(t, batch.Err())
assert.Equal(t, err1, batch.Err().Error())
assert.True(t, batch.NotNil())
}
Expand All @@ -42,7 +43,26 @@ func TestBatchErrorWithErrors(t *testing.T) {
var batch BatchError
batch.Add(errors.New(err1))
batch.Add(errors.New(err2))
assert.NotNil(t, batch)
assert.NotNil(t, batch.Err())
assert.Equal(t, fmt.Sprintf("%s\n%s", err1, err2), batch.Err().Error())
assert.True(t, batch.NotNil())
}

func TestBatchErrorConcurrentAdd(t *testing.T) {
const count = 10000
var batch BatchError
var wg sync.WaitGroup

wg.Add(count)
for i := 0; i < count; i++ {
go func() {
defer wg.Done()
batch.Add(errors.New(err1))
}()
}
wg.Wait()

assert.NotNil(t, batch.Err())
assert.Equal(t, count, len(batch.errs))
assert.True(t, batch.NotNil())
}
Loading