-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
queue.go
352 lines (301 loc) · 6.59 KB
/
queue.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package queue
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/golang-queue/queue/core"
"github.com/golang-queue/queue/job"
"github.com/jpillora/backoff"
)
// ErrQueueShutdown the queue is released and closed.
var ErrQueueShutdown = errors.New("queue has been closed and released")
type (
// A Queue is a message queue.
Queue struct {
sync.Mutex
metric *metric
logger Logger
workerCount int
routineGroup *routineGroup
quit chan struct{}
ready chan struct{}
worker core.Worker
stopOnce sync.Once
stopFlag int32
afterFn func()
}
)
// ErrMissingWorker missing define worker
var ErrMissingWorker = errors.New("missing worker module")
// NewQueue returns a Queue.
func NewQueue(opts ...Option) (*Queue, error) {
o := NewOptions(opts...)
q := &Queue{
routineGroup: newRoutineGroup(),
quit: make(chan struct{}),
ready: make(chan struct{}, 1),
workerCount: o.workerCount,
logger: o.logger,
worker: o.worker,
metric: &metric{},
afterFn: o.afterFn,
}
if q.worker == nil {
return nil, ErrMissingWorker
}
return q, nil
}
// Start to enable all worker
func (q *Queue) Start() {
q.Lock()
count := q.workerCount
q.Unlock()
if count == 0 {
return
}
q.routineGroup.Run(func() {
q.start()
})
}
// Shutdown stops all queues.
func (q *Queue) Shutdown() {
if !atomic.CompareAndSwapInt32(&q.stopFlag, 0, 1) {
return
}
q.stopOnce.Do(func() {
if q.metric.BusyWorkers() > 0 {
q.logger.Infof("shutdown all tasks: %d workers", q.metric.BusyWorkers())
}
if err := q.worker.Shutdown(); err != nil {
q.logger.Error(err)
}
close(q.quit)
})
}
// Release for graceful shutdown.
func (q *Queue) Release() {
q.Shutdown()
q.Wait()
}
// BusyWorkers returns the numbers of workers in the running process.
func (q *Queue) BusyWorkers() int {
return int(q.metric.BusyWorkers())
}
// BusyWorkers returns the numbers of success tasks.
func (q *Queue) SuccessTasks() int {
return int(q.metric.SuccessTasks())
}
// BusyWorkers returns the numbers of failure tasks.
func (q *Queue) FailureTasks() int {
return int(q.metric.FailureTasks())
}
// BusyWorkers returns the numbers of submitted tasks.
func (q *Queue) SubmittedTasks() int {
return int(q.metric.SubmittedTasks())
}
// Wait all process
func (q *Queue) Wait() {
q.routineGroup.Wait()
}
// Queue to queue single job with binary
func (q *Queue) Queue(message core.QueuedMessage, opts ...job.AllowOption) error {
data := job.NewMessage(message, opts...)
data.Encode()
return q.queue(&data)
}
// QueueTask to queue single task
func (q *Queue) QueueTask(task job.TaskFunc, opts ...job.AllowOption) error {
data := job.NewTask(task, opts...)
return q.queue(&data)
}
func (q *Queue) queue(m *job.Message) error {
if atomic.LoadInt32(&q.stopFlag) == 1 {
return ErrQueueShutdown
}
if err := q.worker.Queue(m); err != nil {
return err
}
q.metric.IncSubmittedTask()
return nil
}
func (q *Queue) work(task core.QueuedMessage) {
var err error
// to handle panic cases from inside the worker
// in such case, we start a new goroutine
defer func() {
q.metric.DecBusyWorker()
e := recover()
if e != nil {
q.logger.Errorf("panic error: %v", e)
}
q.schedule()
// increase success or failure number
if err == nil && e == nil {
q.metric.IncSuccessTask()
} else {
q.metric.IncFailureTask()
}
if q.afterFn != nil {
q.afterFn()
}
}()
if err = q.run(task); err != nil {
q.logger.Errorf("runtime error: %s", err.Error())
}
}
func (q *Queue) run(task core.QueuedMessage) error {
data := task.(*job.Message)
if data.Task == nil {
data = job.Decode(task.Bytes())
data.Data = data.Payload
}
return q.handle(data)
}
func (q *Queue) handle(m *job.Message) error {
// create channel with buffer size 1 to avoid goroutine leak
done := make(chan error, 1)
panicChan := make(chan interface{}, 1)
startTime := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), m.Timeout)
defer func() {
cancel()
}()
// run the job
go func() {
// handle panic issue
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
// run custom process function
var err error
b := &backoff.Backoff{
Min: m.RetryMin,
Max: m.RetryMax,
Factor: m.RetryFactor,
Jitter: m.Jitter,
}
delay := m.RetryDelay
loop:
for {
if m.Task != nil {
err = m.Task(ctx)
} else {
err = q.worker.Run(ctx, m)
}
// check error and retry count
if err == nil || m.RetryCount == 0 {
break
}
m.RetryCount--
if m.RetryDelay == 0 {
delay = b.Duration()
}
select {
case <-time.After(delay): // retry delay
q.logger.Infof("retry remaining times: %d, delay time: %s", m.RetryCount, delay)
case <-ctx.Done(): // timeout reached
err = ctx.Err()
break loop
}
}
done <- err
}()
select {
case p := <-panicChan:
panic(p)
case <-ctx.Done(): // timeout reached
return ctx.Err()
case <-q.quit: // shutdown service
// cancel job
cancel()
leftTime := m.Timeout - time.Since(startTime)
// wait job
select {
case <-time.After(leftTime):
return context.DeadlineExceeded
case err := <-done: // job finish
return err
case p := <-panicChan:
panic(p)
}
case err := <-done: // job finish
return err
}
}
// UpdateWorkerCount to update worker number dynamically.
func (q *Queue) UpdateWorkerCount(num int) {
q.Lock()
q.workerCount = num
q.Unlock()
q.schedule()
}
// schedule to check worker number
func (q *Queue) schedule() {
q.Lock()
defer q.Unlock()
if q.BusyWorkers() >= q.workerCount {
return
}
select {
case q.ready <- struct{}{}:
default:
}
}
// start to start all worker
func (q *Queue) start() {
tasks := make(chan core.QueuedMessage, 1)
for {
// check worker number
q.schedule()
select {
// wait worker ready
case <-q.ready:
case <-q.quit:
return
}
// request task from queue in background
q.routineGroup.Run(func() {
for {
t, err := q.worker.Request()
if t == nil || err != nil {
if err != nil {
select {
case <-q.quit:
if !errors.Is(err, ErrNoTaskInQueue) {
close(tasks)
return
}
case <-time.After(time.Second):
// sleep 1 second to fetch new task
}
}
}
if t != nil {
tasks <- t
return
}
select {
case <-q.quit:
if !errors.Is(err, ErrNoTaskInQueue) {
close(tasks)
return
}
default:
}
}
})
task, ok := <-tasks
if !ok {
return
}
// start new task
q.metric.IncBusyWorker()
q.routineGroup.Run(func() {
q.work(task)
})
}
}