github.com/opcr-io/oras-go/v2@v2.0.0-20231122155130-eb4260d8a0ae/internal/syncutil/limit.go (about) 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 eg, egCtx := errgroup.WithContext(ctx) 71 for _, item := range items { 72 region := LimitRegion(ctx, limiter) 73 if err := region.Start(); err != nil { 74 return err 75 } 76 eg.Go(func(t T) func() error { 77 return func() error { 78 defer region.End() 79 return fn(egCtx, region, t) 80 } 81 }(item)) 82 } 83 return eg.Wait() 84 }