-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
232 lines (204 loc) · 5.3 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
package goq
import (
"encoding/base32"
"encoding/json"
"errors"
"gopkg.in/redis.v3"
"time"
"fmt"
)
const (
JOB_STATUS_PREFIX = "goq:queue:job:status:"
JOB_CACHE_PREFIX = "goq:queue:job:cache:"
JOB_FAILED_PREFIX = "goq:queue:job:failed:"
)
var (
client *redis.Client
)
// Function signature for job processor.
type Processor func(*Job)
// Function signature for queue level error handler.
type ErrorHandler func(*Queue, string, error)
type ConnectionOptions struct {
Addr string `json:"host"`
Password string `json:"password"`
DB int64 `json:"db"`
MaxRetries int `json:"max_retries"`
DialTimeout time.Duration `json:"dial_timeout"`
ReadTimeout time.Duration `json:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout"`
PoolSize int `json:"pool_size"`
PoolTimeout time.Duration `json:"pool_timeout"`
IdleTimeout time.Duration `json:"idle_timeout"`
}
type Options struct {
Connection *ConnectionOptions
Concurrency uint8
QueueName string
Processor Processor
ErrorHandler ErrorHandler
}
// Function to create new Queue struct.
func New(opt *Options) *Queue {
if client == nil {
redisOpt := &redis.Options{
Addr: opt.Connection.Addr,
Password: opt.Connection.Password,
DB: opt.Connection.DB,
MaxRetries: opt.Connection.MaxRetries,
DialTimeout: opt.Connection.DialTimeout,
ReadTimeout: opt.Connection.ReadTimeout,
WriteTimeout: opt.Connection.WriteTimeout,
PoolSize: opt.Connection.PoolSize,
PoolTimeout: opt.Connection.PoolTimeout,
IdleTimeout: opt.Connection.IdleTimeout,
}
client = redis.NewClient(redisOpt)
}
return &Queue{
jobChannel: make(chan string, 1000),
concurrency: opt.Concurrency,
queueName: opt.QueueName,
processor: opt.Processor,
errorHandler: opt.ErrorHandler,
}
}
type Queue struct {
jobChannel chan string
concurrency uint8
queueName string
processor Processor
errorHandler ErrorHandler
}
type QueueStatus struct {
QueueLength int64
FailedJobs int64
}
func (qs *QueueStatus) String() string {
return fmt.Sprintf("&QueueStatus{ QueueLength: %d, FailedJobs: %d }", qs.QueueLength, qs.FailedJobs)
}
// Method to get status of this queue.
func (q *Queue) QueueStatus() (*QueueStatus, error) {
queueLen, err := client.LLen(q.queueName).Result()
if err != nil {
return nil, err
}
failedJobs, err := client.SCard(JOB_FAILED_PREFIX+q.queueName).Result()
if err != nil {
return nil, err
}
return &QueueStatus{
QueueLength: queueLen,
FailedJobs: failedJobs,
}, nil
}
// Method to re-enqueue failed job, returns job id.
func (q *Queue) ReEnqueue(jobJSON string) (string, error) {
var err error
// check if jobJSON is a failed job
isAFailedJob, err := client.SIsMember(JOB_FAILED_PREFIX+q.queueName, jobJSON).Result()
if err != nil {
return "", err
}
if !isAFailedJob {
return "", errors.New("Job is not in failed job pool")
}
// create id
id := base32.StdEncoding.EncodeToString([]byte(jobJSON))
// remove from failed job pool
err = client.SRem(JOB_FAILED_PREFIX+q.queueName, jobJSON).Err()
if err != nil {
return "", errors.New("Failed to remove from failed jobs set of job " + id + " : " + err.Error())
}
// re-enqueue
err = client.RPush(q.queueName, jobJSON).Err()
if err != nil {
return "", err
}
// set status to 0 again
// create status JSON
statusJSON, err := json.Marshal(&Status{
Code: 0,
Progress: 0,
})
if err != nil {
return "", err
}
// apply the status
err = client.Set(JOB_STATUS_PREFIX+id, string(statusJSON), 0).Err()
if err != nil {
return "", err
}
return id, nil
}
// Method to enqueue job to queue, returns job id.
func (q *Queue) Enqueue(jobJSON string) (string, error) {
var err error
// push to queue
err = client.RPush(q.queueName, jobJSON).Err()
if err != nil {
return "", err
}
// create status JSON
statusJSON, err := json.Marshal(&Status{
Code: 0,
Progress: 0,
})
if err != nil {
return "", err
}
// create id
id := base32.StdEncoding.EncodeToString([]byte(jobJSON))
// set status of this job
err = client.Set(JOB_STATUS_PREFIX+id, string(statusJSON), 0).Err()
if err != nil {
return "", err
}
return id, nil
}
// Method to run the queue worker.
func (q *Queue) Run() {
for i := uint8(0); i < q.concurrency; i++ {
go q.work()
}
for {
// dequeue the job
// jobJSONSlice will always be 2 length
jobJSONSlice, err := client.BLPop(0, q.queueName).Result()
if err != nil {
q.errorHandler(q, "", err)
continue
}
q.jobChannel <- jobJSONSlice[1]
}
}
func (q *Queue) work() {
for {
jobJSON := <-q.jobChannel
// create the id
id := base32.StdEncoding.EncodeToString([]byte(jobJSON))
// check status
statusJSON, err := client.Get(JOB_STATUS_PREFIX + id).Result()
if err != nil {
q.errorHandler(q, jobJSON, errors.New("Failed to get status of job "+id+" : "+err.Error()))
continue
}
// unmarshal the status
status := &Status{}
err = json.Unmarshal([]byte(statusJSON), status)
if err != nil {
q.errorHandler(q, jobJSON, errors.New("Failed to unmarshal status of job "+id+" : "+err.Error()))
continue
}
// create a job
job := &Job{
ID: id,
JSON: jobJSON,
Status: status,
processor: q.processor,
queueName: q.queueName,
}
// process it
q.processor(job)
}
}