Debian Codegraph @

pool.go

raw ◀ ▶
1 Debian patch touch this file
1 package proton
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "sync"
8
9 "github.com/ProtonMail/gluon/async"
10 )
11
12 // ErrJobCancelled indicates the job was cancelled.
13 var ErrJobCancelled = errors.New("job cancelled by surrounding context")
14
15 // Pool is a worker pool that handles input of type In and returns results of type Out.
16 type Pool[In comparable, Out any] struct {
17 queue *async.QueuedChannel[*job[In, Out]]
18 wg sync.WaitGroup
19 panicHandler async.PanicHandler
20 }
21
22 // doneFunc must be called to free up pool resources.
23 type doneFunc func()
24
25 // New returns a new pool.
26 func NewPool[In comparable, Out any](size int, panicHandler async.PanicHandler, work func(context.Context, In) (Out, error)) *Pool[In, Out] {
27 pool := &Pool[In, Out]{
•28 queue: async.NewQueuedChannel[*job[In, Out]](0, 0, panicHandler),
29 }
30
31 for i := 0; i < size; i++ {
32 pool.wg.Add(1)
33
34 go func() {
35 defer async.HandlePanic(pool.panicHandler)
36
37 defer pool.wg.Done()
38
39 for job := range pool.queue.GetChannel() {
40 select {
41 case <-job.ctx.Done():
42 job.postFailure(ErrJobCancelled)
43
44 default:
45 res, err := work(job.ctx, job.req)
46 if err != nil {
47 job.postFailure(err)
48 } else {
49 job.postSuccess(res)
50 }
51
52 job.waitDone()
53 }
54 }
55 }()
56 }
57
58 return pool
59 }
60
61 // Process submits jobs to the pool. The callback provides access to the result, or an error if one occurred.
62 func (pool *Pool[In, Out]) Process(ctx context.Context, reqs []In, fn func(int, In, Out, error) error) error {
63 ctx, cancel := context.WithCancel(ctx)
64 defer cancel()
65
66 var (
67 wg sync.WaitGroup
68 errList []error
69 lock sync.Mutex
70 )
71
72 for i, req := range reqs {
73 req := req
74
75 wg.Add(1)
76
77 go func(index int) {
78 defer async.HandlePanic(pool.panicHandler)
79
80 defer wg.Done()
81
82 job, done, err := pool.newJob(ctx, req)
83 if err != nil {
84 lock.Lock()
85 defer lock.Unlock()
86
87 // Cancel ongoing jobs.
88 cancel()
89
90 // Collect the error.
91 errList = append(errList, err)
92
93 return
94 }
95
96 defer done()
97
98 res, err := job.result()
99
100 if err := fn(index, req, res, err); err != nil {
101 lock.Lock()
102 defer lock.Unlock()
103
104 // Cancel ongoing jobs.
105 cancel()
106
107 // Collect the error.
108 errList = append(errList, err)
109 }
110 }(i)
111 }
112
113 wg.Wait()
114
115 // TODO: Join the errors somehow?
116 if len(errList) > 0 {
117 return errList[0]
118 }
119
120 return nil
121 }
122
123 // ProcessAll submits jobs to the pool. All results are returned once available.
124 func (pool *Pool[In, Out]) ProcessAll(ctx context.Context, reqs []In) ([]Out, error) {
125 data := make([]Out, len(reqs))
126
127 if err := pool.Process(ctx, reqs, func(index int, req In, res Out, err error) error {
128 if err != nil {
129 return err
130 }
131
132 data[index] = res
133
134 return nil
135 }); err != nil {
136 return nil, err
137 }
138
139 return data, nil
140 }
141
142 // ProcessOne submits one job to the pool and returns the result.
143 func (pool *Pool[In, Out]) ProcessOne(ctx context.Context, req In) (Out, error) {
144 job, done, err := pool.newJob(ctx, req)
145 if err != nil {
146 var o Out
147 return o, err
148 }
149
150 defer done()
151
152 return job.result()
153 }
154
155 func (pool *Pool[In, Out]) Done() {
156 pool.queue.Close()
157 pool.wg.Wait()
158 }
159
160 // newJob submits a job to the pool. It returns a job handle and a DoneFunc.
161 // The job handle allows the job result to be obtained. The DoneFunc is used to mark the job as done,
162 // which frees up the worker in the pool for reuse.
163 func (pool *Pool[In, Out]) newJob(ctx context.Context, req In) (*job[In, Out], doneFunc, error) {
164 job := newJob[In, Out](ctx, req)
165
166 if !pool.queue.Enqueue(job) {
167 return nil, nil, fmt.Errorf("pool closed")
168 }
169
170 return job, func() { close(job.done) }, nil
171 }