-
Notifications
You must be signed in to change notification settings - Fork 8
/
batch.go
219 lines (190 loc) · 4.83 KB
/
batch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package goroutines
import (
"context"
"errors"
"sync"
)
var (
// ErrQueueComplete indicates no more incoming tasks allowed to put in the pool
ErrQueueComplete = errors.New("queue has completed already")
// ErrQueueCTXDone indicates context in queue is done due to timeout or cancellation.
ErrQueueCTXDone = errors.New("context in queue is done")
)
// Result is the interface returned by Results()
type Result interface {
// Value returns the value
Value() interface{}
// Error returns the error
Error() error
}
// BatchFunc is the task function assigned by caller, running in the goroutine pool
type BatchFunc func() (interface{}, error)
// Batch is the struct containing all Batch operations
type Batch struct {
pool *Pool
inputChan chan *input
outputChan chan Result
retChan chan Result
completeChan chan struct{}
inputOnce sync.Once
outputOnce sync.Once
resultOnce sync.Once
consumers []*consumer
}
// NewBatch creates a asynchronous goroutine pool with the given size indicating
// total numbers of workers, and register consumers to deal with tasks past by producers.
func NewBatch(size int, options ...BatchOption) *Batch {
// load options
o := &batchOption{}
for _, opt := range options {
opt(o)
}
batchSize := defaultBatchSize
if o.batchSize > batchSize {
batchSize = o.batchSize
}
b := Batch{
pool: NewPool(size),
inputChan: make(chan *input, batchSize),
outputChan: make(chan Result, batchSize),
completeChan: make(chan struct{}),
retChan: make(chan Result),
}
for i := 0; i < size; i++ {
c := newConsumer()
b.pool.Schedule(func() {
defer close(c.closedChan)
// listen on inputChan until it's closed or interrupted by others
for {
select {
case <-c.closeChan:
return
default:
}
select {
case <-c.closeChan:
return
case in, ok := <-b.inputChan:
if !ok {
return
}
intf, err := in.fn()
ret := &result{value: intf, err: err}
b.outputChan <- ret
}
}
})
b.consumers = append(b.consumers, c)
}
return &b
}
// Queue plays as a producer to queue a task into pool, and
// starts processing immediately.
//
// HINT: make sure not to call QueueComplete concurrently
func (b *Batch) Queue(fn BatchFunc) error {
return b.queue(context.Background(), fn)
}
// QueueWithContext plays as a producer to queue a task into pool, or
// return ErrQueueCTXDone due to ctx is done (timeout or cancellation).
//
// HINT: make sure not to call QueueComplete concurrently
func (b *Batch) QueueWithContext(ctx context.Context, fn BatchFunc) error {
return b.queue(ctx, fn)
}
// QueueComplete means finishing queuing tasks
// HINT: make sure not to call Queue concurrently
func (b *Batch) QueueComplete() {
b.inputOnce.Do(func() {
close(b.completeChan)
close(b.inputChan)
})
}
// Results returns a Result channel that will output all completed tasks.
func (b *Batch) Results() <-chan Result {
b.resultOnce.Do(func() {
go func() {
for i := 0; i < len(b.consumers); i++ {
b.consumers[i].join()
}
b.outputOnce.Do(func() {
close(b.outputChan)
})
}()
go func() {
for output := range b.outputChan {
b.retChan <- output
}
close(b.retChan)
}()
})
return b.retChan
}
// WaitAll is an alternative to Results() where you may want/need to wait
// until all work has been processed, but don't need to check results.
func (b *Batch) WaitAll() {
for range b.Results() {
}
}
// Close will terminate all workers and close the job channel of this pool.
func (b *Batch) Close() {
b.QueueComplete()
b.WaitAll()
b.terminateAll()
b.pool.Release()
}
// GracefulClose will terminate all workers and close the job channel of this pool in the background.
func (b *Batch) GracefulClose() {
go func() {
b.Close()
}()
}
func (b *Batch) queue(ctx context.Context, fn BatchFunc) error {
// The first try-receive operation is to try to exit the goroutine
// as early as possible. It is not essential but a good practice to handle
// racing case continue putting task in queue.
select {
case <-b.completeChan:
return ErrQueueComplete
default:
}
select {
case <-b.completeChan:
return ErrQueueComplete
case <-ctx.Done():
// timeout or cancellation
return ErrQueueCTXDone
default:
}
select {
case <-b.completeChan:
return ErrQueueComplete
case <-ctx.Done():
// timeout or cancellation
return ErrQueueCTXDone
case b.inputChan <- &input{fn: fn}:
return nil
}
}
// terminateAll is going to terminate all consumers if possilbe
func (b *Batch) terminateAll() {
for i := 0; i < len(b.consumers); i++ {
b.consumers[i].stop()
}
for i := 0; i < len(b.consumers); i++ {
b.consumers[i].join()
}
}
type input struct {
fn BatchFunc
}
type result struct {
value interface{}
err error
}
func (r *result) Value() interface{} {
return r.value
}
func (r *result) Error() error {
return r.err
}