| 1 |
/* |
| 2 |
Copyright The ORAS Authors. |
| 3 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
you may not use this file except in compliance with the License. |
| 5 |
You may obtain a copy of the License at |
| 6 |
|
| 7 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
|
| 9 |
Unless required by applicable law or agreed to in writing, software |
| 10 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
See the License for the specific language governing permissions and |
| 13 |
limitations under the License. |
| 14 |
*/ |
| 15 |
|
| 16 |
package syncutil |
| 17 |
|
| 18 |
import ( |
| 19 |
"context" |
| 20 |
|
| 21 |
"golang.org/x/sync/errgroup" |
| 22 |
) |
| 23 |
|
| 24 |
// LimitedGroup is a collection of goroutines working on subtasks that are part of |
| 25 |
// the same overall task. |
| 26 |
type LimitedGroup struct { |
| 27 |
grp *errgroup.Group |
| 28 |
ctx context.Context |
| 29 |
} |
| 30 |
|
| 31 |
// LimitGroup returns a new LimitedGroup and an associated Context derived from ctx. |
| 32 |
// |
| 33 |
// The number of active goroutines in this group is limited to the given limit. |
| 34 |
// A negative value indicates no limit. |
| 35 |
// |
| 36 |
// The derived Context is canceled the first time a function passed to Go |
| 37 |
// returns a non-nil error or the first time Wait returns, whichever occurs |
| 38 |
// first. |
| 39 |
func LimitGroup(ctx context.Context, limit int) (*LimitedGroup, context.Context) { |
| 40 |
grp, ctx := errgroup.WithContext(ctx) |
| 41 |
grp.SetLimit(limit) |
| 42 |
return &LimitedGroup{grp: grp, ctx: ctx}, ctx |
| 43 |
} |
| 44 |
|
| 45 |
// Go calls the given function in a new goroutine. |
| 46 |
// It blocks until the new goroutine can be added without the number of |
| 47 |
// active goroutines in the group exceeding the configured limit. |
| 48 |
// |
| 49 |
// The first call to return a non-nil error cancels the group's context. |
| 50 |
// After which, any subsequent calls to Go will not execute their given function. |
| 51 |
// The error will be returned by Wait. |
| 52 |
func (g *LimitedGroup) Go(f func() error) { |
| 53 |
g.grp.Go(func() error { |
| 54 |
select { |
| 55 |
case <-g.ctx.Done(): |
| 56 |
return g.ctx.Err() |
| 57 |
default: |
| 58 |
return f() |
| 59 |
} |
| 60 |
}) |
| 61 |
} |
| 62 |
|
| 63 |
// Wait blocks until all function calls from the Go method have returned, then |
| 64 |
// returns the first non-nil error (if any) from them. |
| 65 |
func (g *LimitedGroup) Wait() error { |
| 66 |
return g.grp.Wait() |
| 67 |
} |