...
1 package pool
2
3 import (
4 "context"
5 "sync"
6
7 "github.com/sourcegraph/conc/internal/multierror"
8 )
9
10
11
12
13
14
15
16
17 type ErrorPool struct {
18 pool Pool
19
20 onlyFirstError bool
21
22 mu sync.Mutex
23 errs error
24 }
25
26
27
28 func (p *ErrorPool) Go(f func() error) {
29 p.pool.Go(func() {
30 p.addErr(f())
31 })
32 }
33
34
35
36 func (p *ErrorPool) Wait() error {
37 p.pool.Wait()
38 return p.errs
39 }
40
41
42
43
44
45 func (p *ErrorPool) WithContext(ctx context.Context) *ContextPool {
46 p.panicIfInitialized()
47 ctx, cancel := context.WithCancel(ctx)
48 return &ContextPool{
49 errorPool: p.deref(),
50 ctx: ctx,
51 cancel: cancel,
52 }
53 }
54
55
56
57 func (p *ErrorPool) WithFirstError() *ErrorPool {
58 p.panicIfInitialized()
59 p.onlyFirstError = true
60 return p
61 }
62
63
64
65 func (p *ErrorPool) WithMaxGoroutines(n int) *ErrorPool {
66 p.panicIfInitialized()
67 p.pool.WithMaxGoroutines(n)
68 return p
69 }
70
71
72
73
74 func (p *ErrorPool) deref() ErrorPool {
75 return ErrorPool{
76 pool: p.pool.deref(),
77 onlyFirstError: p.onlyFirstError,
78 }
79 }
80
81 func (p *ErrorPool) panicIfInitialized() {
82 p.pool.panicIfInitialized()
83 }
84
85 func (p *ErrorPool) addErr(err error) {
86 if err != nil {
87 p.mu.Lock()
88 if p.onlyFirstError {
89 if p.errs == nil {
90 p.errs = err
91 }
92 } else {
93 p.errs = multierror.Join(p.errs, err)
94 }
95 p.mu.Unlock()
96 }
97 }
98
View as plain text