diff --git a/internal/workgroup/group.go b/internal/workgroup/group.go index 9b4cd83f758..2f659ff41c6 100644 --- a/internal/workgroup/group.go +++ b/internal/workgroup/group.go @@ -40,6 +40,7 @@ func (g *Group) Add(fn func(<-chan struct{}) error) { func (g *Group) AddContext(fn func(context.Context) error) { g.fn = append(g.fn, func(stop <-chan struct{}) error { ctx, cancel := context.WithCancel(context.Background()) + defer cancel() res := make(chan error) // run the function & send the result on res @@ -47,8 +48,12 @@ func (g *Group) AddContext(fn func(context.Context) error) { res <- fn(ctx) }() - // wait for stop - <-stop + // wait for stop or if the current function returns a result, return it. + select { + case <-stop: + case err := <-res: + return err + } // cancel fn(ctx) cancel() diff --git a/internal/workgroup/group_test.go b/internal/workgroup/group_test.go index eb0f5147cbd..ea77ff2e1b9 100644 --- a/internal/workgroup/group_test.go +++ b/internal/workgroup/group_test.go @@ -52,7 +52,7 @@ func TestGroupFirstReturnValueIsReturnedToRunsCaller(t *testing.T) { func TestGroupAddContext(t *testing.T) { var g Group wait := make(chan int) - g.Add(func(<-chan struct{}) error { + g.AddContext(func(ctx context.Context) error { <-wait return io.EOF })