Debian Codegraph @

internal/syncutil/limit.go

raw
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 "golang.org/x/sync/semaphore"
23 )
24
25 // LimitedRegion provides a way to bound concurrent access to a code block.
26 type LimitedRegion struct {
27 ctx context.Context
28 limiter *semaphore.Weighted
29 ended bool
30 }
31
32 // LimitRegion creates a new LimitedRegion.
33 func LimitRegion(ctx context.Context, limiter *semaphore.Weighted) *LimitedRegion {
34 if limiter == nil {
35 return nil
36 }
37 return &LimitedRegion{
38 ctx: ctx,
39 limiter: limiter,
40 ended: true,
41 }
42 }
43
44 // Start starts the region with concurrency limit.
45 func (lr *LimitedRegion) Start() error {
46 if lr == nil || !lr.ended {
47 return nil
48 }
49 if err := lr.limiter.Acquire(lr.ctx, 1); err != nil {
50 return err
51 }
52 lr.ended = false
53 return nil
54 }
55
56 // End ends the region with concurrency limit.
57 func (lr *LimitedRegion) End() {
58 if lr == nil || lr.ended {
59 return
60 }
61 lr.limiter.Release(1)
62 lr.ended = true
63 }
64
65 // GoFunc represents a function that can be invoked by Go.
66 type GoFunc[T any] func(ctx context.Context, region *LimitedRegion, t T) error
67
68 // Go concurrently invokes fn on items.
69 func Go[T any](ctx context.Context, limiter *semaphore.Weighted, fn GoFunc[T], items ...T) error {
70 ctx, cancel := context.WithCancelCause(ctx)
71 defer cancel(nil)
72
73 eg, egCtx := errgroup.WithContext(ctx)
74 for _, item := range items {
75 region := LimitRegion(egCtx, limiter)
76 if err := region.Start(); err != nil {
77 cancel(err)
78 // break loop instead of returning to allow previously scheduled
79 // goroutines to finish their deferred region.End() calls
80 break
81 }
82
83 eg.Go(func(t T, lr *LimitedRegion) func() error {
84 return func() error {
85 defer lr.End()
86
87 select {
88 case <-egCtx.Done():
89 // skip the task if the context is already cancelled
90 return nil
91 default:
92 }
93
94 if err := fn(egCtx, lr, t); err != nil {
95 cancel(err)
96 return err
97 }
98 return nil
99 }
100 }(item, region))
101 }
102
103 if err := eg.Wait(); err != nil {
104 cancel(err)
105 }
106 return context.Cause(ctx)
107 }