-
Notifications
You must be signed in to change notification settings - Fork 7
/
consume.go
206 lines (169 loc) · 4.41 KB
/
consume.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
package cogman
import (
"context"
"sync"
"time"
"github.com/Joker666/cogman/util"
"github.com/streadway/amqp"
)
// Consume start task consumption
func (s *Server) Consume(ctx context.Context, prefetch int) {
ctx, stop := context.WithCancel(ctx)
if err := s.consume(ctx, prefetch); err != nil {
s.connError <- err
}
stop()
}
type errorTaskBody struct {
taskID string
status util.Status
err error
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func (s *Server) consume(ctx context.Context, prefetch int) error {
errCh := make(chan errorTaskBody, 1)
s.lgr.Debug("creating channel")
taskPool := make(chan amqp.Delivery)
s.lgr.Debug("creating consumer")
for i := 0; i < s.cfg.AMQP.HighPriorityQueueCount; i++ {
queue := formQueueName(util.HighPriorityQueue, i)
go s.setConsumer(ctx, queue, util.QueueModeDefault, maxInt(20, prefetch), taskPool)
}
for i := 0; i < s.cfg.AMQP.LowPriorityQueueCount; i++ {
queue := formQueueName(util.LowPriorityQueue, i)
go s.setConsumer(ctx, queue, util.QueueModeLazy, maxInt(10, prefetch), taskPool)
}
wg := sync.WaitGroup{}
var closeErr error
s.lgr.Debug("waiting for tasks")
// waiting for task response from queue consumer.
for {
var msg amqp.Delivery
done := false
select {
case <-ctx.Done():
s.lgr.Debug("task processing stopped")
done = true
case msg = <-taskPool:
s.lgr.Debug("received a task to process", util.Object{Key: "TaskID", Val: msg.MessageId})
case errTask := <-errCh:
s.lgr.Error("got error in task", errTask.err, util.Object{Key: "ID", Val: errTask.taskID})
func() {
task, err := s.taskRepo.GetTask(errTask.taskID)
if err != nil {
s.lgr.Error("failed to get task", err, util.Object{Key: "TaskID", Val: errTask.taskID})
return
}
if orgTask, err := s.taskRepo.GetTask(task.OriginalTaskID); err != nil {
s.lgr.Error("failed to get task", err, util.Object{Key: "TaskID", Val: orgTask.TaskID})
return
} else if orgTask.Retry != 0 {
go s.retryConn.RetryTask(*orgTask)
}
}()
s.taskRepo.UpdateTaskStatus(ctx, errTask.taskID, errTask.status, errTask.err)
continue
}
if done {
break
}
if err := msg.Ack(true); err != nil {
s.lgr.Warn("fail to ack")
continue
}
hdr := msg.Headers
if hdr == nil {
s.lgr.Warn("skipping headless task")
continue
}
taskID, ok := hdr["TaskID"].(string)
if !ok {
s.lgr.Warn("skipping unidentified task")
continue
}
s.taskRepo.UpdateTaskStatus(ctx, taskID, util.StatusInProgress)
taskName, ok := hdr["TaskName"].(string)
if !ok {
errCh <- errorTaskBody{
taskID,
util.StatusFailed,
ErrTaskUnidentified,
}
continue
}
worker, ok := s.workers[taskName]
if !ok {
errCh <- errorTaskBody{
taskID,
util.StatusFailed,
ErrTaskUnhandled,
}
continue
}
wg.Add(1)
// Start processing task
go func(worker *util.Worker, msg *amqp.Delivery) {
defer wg.Done()
s.lgr.Info("processing task", util.Object{Key: "taskName", Val: worker.Name()}, util.Object{Key: "taskID", Val: taskID})
startAt := time.Now()
if err := worker.Process(msg); err != nil {
errCh <- errorTaskBody{
taskID,
util.StatusFailed,
err,
}
return
}
duration := float64(time.Since(startAt)) / float64(time.Second)
s.taskRepo.UpdateTaskStatus(ctx, taskID, util.StatusSuccess, duration)
}(worker, &msg)
}
wg.Wait()
return closeErr
}
// setConsumer set a consumer for each single queue.
func (s *Server) setConsumer(ctx context.Context, queue, mode string, prefetch int, taskPool chan<- amqp.Delivery) {
channel, err := s.aConn.Channel()
if err != nil {
s.lgr.Error("failed to create channel", err)
return
}
defer channel.Close()
closeNotification := channel.NotifyClose(make(chan *amqp.Error, 1))
if err := channel.Qos(prefetch, 0, false); err != nil {
s.lgr.Error("failed to set qos", err)
return
}
msg, err := channel.Consume(
queue,
"",
false,
false,
false,
false,
amqp.Table{
"x-queue-mode": mode,
},
)
if err != nil {
s.lgr.Error("failed to create consumer", err)
return
}
for {
select {
case closeErr := <-closeNotification:
s.lgr.Error("queue closing", closeErr, util.Object{Key: "queue", Val: queue})
return
case <-ctx.Done():
s.lgr.Debug("queue closing", util.Object{Key: "queue", Val: queue})
return
case taskPool <- <-msg:
s.lgr.Debug("new task", util.Object{Key: "queue", Val: queue})
}
}
}