-
Notifications
You must be signed in to change notification settings - Fork 26
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
Add batching functionality #120
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package grpcutil | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"runtime" | ||
|
||
"golang.org/x/sync/errgroup" | ||
"golang.org/x/sync/semaphore" | ||
) | ||
|
||
func min(a int, b int) int { | ||
if a <= b { | ||
return a | ||
} | ||
return b | ||
} | ||
|
||
// EachFunc is a callback function that is called for each batch. no is the | ||
// batch number, start is the starting index of this batch in the slice, and | ||
// end is the ending index of this batch in the slice. | ||
type EachFunc func(ctx context.Context, no int, start int, end int) error | ||
|
||
// ConcurrentBatch will calculate the minimum number of batches to required to batch n items | ||
// with batchSize batches. For each batch, it will execute the each function. | ||
// These functions will be processed in parallel using maxWorkers number of | ||
// goroutines. If maxWorkers is 1, then batching will happen sychronously. If | ||
// maxWorkers is 0, then GOMAXPROCS number of workers will be used. | ||
// | ||
// If an error occurs during a batch, all the worker's contexts are cancelled | ||
// and the original error is returned. | ||
func ConcurrentBatch(ctx context.Context, n int, batchSize int, maxWorkers int, each EachFunc) error { | ||
if n < 0 { | ||
return errors.New("cannot batch items of length < 0") | ||
} else if n == 0 { | ||
// Batching zero items is a noop. | ||
return nil | ||
} | ||
|
||
if batchSize < 1 { | ||
return errors.New("cannot batch items with batch size < 1") | ||
} | ||
|
||
if maxWorkers < 0 { | ||
return errors.New("cannot batch items with workers < 0") | ||
} else if maxWorkers == 0 { | ||
maxWorkers = runtime.GOMAXPROCS(0) | ||
} | ||
|
||
sem := semaphore.NewWeighted(int64(maxWorkers)) | ||
g, ctx := errgroup.WithContext(ctx) | ||
numBatches := (n + batchSize - 1) / batchSize | ||
for i := 0; i < numBatches; i++ { | ||
if err := sem.Acquire(ctx, 1); err != nil { | ||
return fmt.Errorf("failed to acquire semaphore for batch number %d: %w", i, err) | ||
} | ||
|
||
batchNum := i | ||
g.Go(func() error { | ||
defer sem.Release(1) | ||
start := batchNum * batchSize | ||
end := min(start+batchSize, n) | ||
return each(ctx, batchNum, start, end) | ||
}) | ||
} | ||
return g.Wait() | ||
} | ||
bryanhuhta marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
package grpcutil | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"sync/atomic" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
type batch struct { | ||
no int | ||
start int | ||
end int | ||
} | ||
|
||
func generateItems(n int) []string { | ||
items := make([]string, n) | ||
for i := 0; i < n; i++ { | ||
items[i] = fmt.Sprintf("item %d", i) | ||
} | ||
return items | ||
} | ||
|
||
func TestConcurrentBatchOrdering(t *testing.T) { | ||
const batchSize = 3 | ||
const workers = 1 // Set to one to keep everything synchronous. | ||
|
||
tests := []struct { | ||
name string | ||
items []string | ||
want []batch | ||
}{ | ||
{ | ||
name: "1 item", | ||
items: generateItems(1), | ||
want: []batch{ | ||
{0, 0, 1}, | ||
}, | ||
}, | ||
{ | ||
name: "3 items", | ||
items: generateItems(3), | ||
want: []batch{ | ||
{0, 0, 3}, | ||
}, | ||
}, | ||
{ | ||
name: "5 items", | ||
items: generateItems(5), | ||
want: []batch{ | ||
{0, 0, 3}, | ||
{1, 3, 5}, | ||
}, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
require := require.New(t) | ||
|
||
gotCh := make(chan batch, len(tt.items)) | ||
fn := func(ctx context.Context, no, start, end int) error { | ||
gotCh <- batch{no, start, end} | ||
return nil | ||
} | ||
|
||
err := ConcurrentBatch(context.Background(), len(tt.items), batchSize, workers, fn) | ||
require.NoError(err) | ||
|
||
got := make([]batch, len(gotCh)) | ||
i := 0 | ||
for span := range gotCh { | ||
got[i] = span | ||
i++ | ||
|
||
if i == len(got) { | ||
break | ||
} | ||
} | ||
require.Equal(tt.want, got) | ||
}) | ||
} | ||
} | ||
|
||
func TestConcurrentBatch(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
items []string | ||
batchSize int | ||
workers int | ||
wantCalls int | ||
}{ | ||
{ | ||
name: "5 batches", | ||
items: generateItems(50), | ||
batchSize: 10, | ||
workers: 3, | ||
wantCalls: 5, | ||
}, | ||
{ | ||
name: "0 batches", | ||
items: []string{}, | ||
batchSize: 10, | ||
workers: 3, | ||
wantCalls: 0, | ||
}, | ||
{ | ||
name: "1 batch", | ||
items: generateItems(10), | ||
batchSize: 10, | ||
workers: 3, | ||
wantCalls: 1, | ||
}, | ||
{ | ||
name: "1 full batch, 1 partial batch", | ||
items: generateItems(15), | ||
batchSize: 10, | ||
workers: 3, | ||
wantCalls: 2, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
require := require.New(t) | ||
|
||
var calls int64 | ||
fn := func(ctx context.Context, no, start, end int) error { | ||
atomic.AddInt64(&calls, 1) | ||
return nil | ||
} | ||
err := ConcurrentBatch(context.Background(), len(tt.items), tt.batchSize, tt.workers, fn) | ||
|
||
require.NoError(err) | ||
require.Equal(tt.wantCalls, int(calls)) | ||
}) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In theory we could use a cancel context here and have another cli flag to dictate how long a timeout should be. I think that should be a follow up feature though.