This repository has been archived by the owner on Dec 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
disque.go
381 lines (324 loc) · 8.26 KB
/
disque.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package disque
import (
"errors"
"fmt"
"reflect"
"time"
"github.com/garyburd/redigo/redis"
)
// Pool represent Redis connection to a Disque Pool
// with a certain Disque configuration.
type Pool struct {
redis *redis.Pool
conf Config
}
// New creates a new connection to a given Disque Pool.
func New(address string, extra ...string) (*Pool, error) {
pool := &redis.Pool{
MaxIdle: 1024,
MaxActive: 1024,
IdleTimeout: 300 * time.Second,
Wait: true,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", address)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return &Pool{redis: pool}, nil
}
func NewWithPool(pool *redis.Pool) *Pool {
return &Pool{redis: pool}
}
// Close closes the connection to a Disque Pool.
func (pool *Pool) Close() error {
return pool.redis.Close()
}
// Ping returns nil if Disque Pool is alive, error otherwise.
func (pool *Pool) Ping() error {
sess := pool.redis.Get()
defer sess.Close()
if _, err := sess.Do("PING"); err != nil {
return err
}
return nil
}
// do is a helper function that workarounds redigo/redis API
// flaws with a magic function Call() from the reflect pkg.
//
// None of the following builds or works successfully:
//
// reply, err := sess.Do("GETJOB", "FROM", queues, redis.Args{})
// reply, err := sess.Do("GETJOB", "FROM", queues, redis.Args{}...)
// reply, err := sess.Do("GETJOB", "FROM", queues)
// reply, err := sess.Do("GETJOB", "FROM", queues...)
//
// > Build error: "too many arguments in call to sess.Do"
// > Runtime error: "ERR wrong number of arguments for '...' command"
//
func (pool *Pool) do(args []interface{}) (interface{}, error) {
sess := pool.redis.Get()
defer sess.Close()
fn := reflect.ValueOf(sess.Do)
reflectArgs := make([]reflect.Value, len(args))
for i, arg := range args {
reflectArgs[i] = reflect.ValueOf(arg)
}
ret := fn.Call(reflectArgs)
if len(ret) != 2 {
return nil, errors.New("expected two return values")
}
if !ret[1].IsNil() {
err, ok := ret[1].Interface().(error)
if !ok {
return nil, fmt.Errorf("expected error type, got: %T %#v", ret[1], ret[1])
}
return nil, err
}
if ret[0].IsNil() {
return nil, fmt.Errorf("no data available")
}
reply, ok := ret[0].Interface().(interface{})
if !ok {
return nil, fmt.Errorf("unexpected interface{} error type, got: %T %#v", ret[0], ret[0])
}
return reply, nil
}
// Add enqueues new job with a specified data to a given queue.
func (pool *Pool) Add(data string, queue string) (*Job, error) {
args := []interface{}{
"ADDJOB",
queue,
data,
int(pool.conf.Timeout.Nanoseconds() / 1000000),
}
if pool.conf.Replicate > 0 {
args = append(args, "REPLICATE", pool.conf.Replicate)
}
if pool.conf.Delay > 0 {
delay := int(pool.conf.Delay.Seconds())
if delay == 0 {
delay = 1
}
args = append(args, "DELAY", delay)
}
if pool.conf.RetryAfter > 0 {
retry := int(pool.conf.RetryAfter.Seconds())
if retry == 0 {
retry = 1
}
args = append(args, "RETRY", retry)
}
if pool.conf.TTL > 0 {
ttl := int(pool.conf.TTL.Seconds())
if ttl == 0 {
ttl = 1
}
args = append(args, "TTL", ttl)
}
if pool.conf.MaxLen > 0 {
args = append(args, "MAXLEN", pool.conf.MaxLen)
}
reply, err := pool.do(args)
if err != nil {
return nil, err
}
id, ok := reply.(string)
if !ok {
return nil, errors.New("unexpected reply: id")
}
return &Job{
ID: id,
Data: data,
Queue: queue,
}, nil
}
// Get returns first available job from a highest priority
// queue possible (left-to-right priority).
func (pool *Pool) Get(queues ...string) (*Job, error) {
if len(queues) == 0 {
return nil, errors.New("expected at least one queue")
}
args := []interface{}{
"GETJOB",
"TIMEOUT",
int(pool.conf.Timeout.Nanoseconds() / 1000000),
"WITHCOUNTERS",
"FROM",
}
for _, arg := range queues {
args = append(args, arg)
}
reply, err := pool.do(args)
if err != nil {
return nil, err
}
replyArr, ok := reply.([]interface{})
if !ok || len(replyArr) != 1 {
return nil, errors.New("unexpected reply #1")
}
arr, ok := replyArr[0].([]interface{})
if !ok || len(arr) != 7 {
return nil, errors.New("unexpected reply #2")
}
job := Job{}
if bytes, ok := arr[0].([]byte); ok {
job.Queue = string(bytes)
} else {
return nil, errors.New("unexpected reply: queue")
}
if bytes, ok := arr[1].([]byte); ok {
job.ID = string(bytes)
} else {
return nil, errors.New("unexpected reply: id")
}
if bytes, ok := arr[2].([]byte); ok {
job.Data = string(bytes)
} else {
return nil, errors.New("unexpected reply: data")
}
if job.Nacks, ok = arr[4].(int64); !ok {
return nil, errors.New("unexpected reply: nacks")
}
if job.AdditionalDeliveries, ok = arr[6].(int64); !ok {
return nil, errors.New("unexpected reply: additional-deliveries")
}
return &job, nil
}
// Fetch finds the job by its id and return its details
func (pool *Pool) Fetch(ID string) (*Job, error) {
sess := pool.redis.Get()
defer sess.Close()
reply, err := pool.do([]interface{}{
"SHOW",
ID,
})
if err != nil {
return nil, err
}
arr, ok := reply.([]interface{})
if !ok || len(arr) != 30 {
return nil, errors.New("unexpected reply #1")
}
job := Job{}
var bytes []byte
if bytes, ok = arr[1].([]byte); ok {
job.ID = string(bytes)
} else {
return nil, errors.New("unexpected reply: id")
}
if bytes, ok = arr[3].([]byte); ok {
job.Queue = string(bytes)
} else {
return nil, errors.New("unexpected reply: queue")
}
if bytes, ok = arr[5].([]byte); ok {
job.State = string(bytes)
} else {
return nil, errors.New("unexpected reply: state")
}
if job.Replication, ok = arr[7].(int64); !ok {
return nil, errors.New("unexpected reply: repl")
}
if ttl, ok := arr[9].(int64); ok {
job.TTL = time.Duration(ttl) * time.Second
} else {
return nil, errors.New("unexpected reply: ttl")
}
if createdAt, ok := arr[11].(int64); ok {
job.CreatedAt = time.Unix(0, createdAt)
} else {
return nil, errors.New("unexpected reply: ctime")
}
if delay, ok := arr[13].(int64); ok {
job.Delay = time.Duration(delay) * time.Second
} else {
return nil, errors.New("unexpected reply: delay")
}
if retry, ok := arr[15].(int64); ok {
job.Retry = time.Duration(retry) * time.Second
} else {
return nil, errors.New("unexpected reply: retry")
}
if job.Nacks, ok = arr[17].(int64); !ok {
return nil, errors.New("unexpected reply: nacks")
}
if job.AdditionalDeliveries, ok = arr[19].(int64); !ok {
return nil, errors.New("unexpected reply: additional-deliveries")
}
if bytes, ok := arr[29].([]byte); ok {
job.Data = string(bytes)
} else {
return nil, errors.New("unexpected reply: data")
}
return &job, nil
}
// Ack acknowledges (dequeues/removes) a job from its queue.
func (pool *Pool) Ack(job *Job) error {
sess := pool.redis.Get()
defer sess.Close()
if _, err := sess.Do("ACKJOB", job.ID); err != nil {
return err
}
return nil
}
// Nack re-queues a job back into its queue.
func (pool *Pool) Nack(job *Job) error {
sess := pool.redis.Get()
defer sess.Close()
if _, err := sess.Do("NACK", job.ID); err != nil {
return err
}
return nil
}
// Wait blocks until the given job is ACKed.
// Native WAITJOB discussed upstream at https://github.com/antirez/disque/issues/168.
func (pool *Pool) Wait(job *Job) error {
sess := pool.redis.Get()
defer sess.Close()
for {
reply, err := sess.Do("SHOW", job.ID)
if err != nil {
return err
}
if reply == nil {
break
}
time.Sleep(50 * time.Millisecond)
}
return nil
}
// Len returns length of a given queue.
func (pool *Pool) Len(queue string) (int, error) {
sess := pool.redis.Get()
defer sess.Close()
length, err := redis.Int(sess.Do("QLEN", queue))
if err != nil {
return 0, err
}
return length, nil
}
// ActiveLen returns length of active jobs taken from a given queue.
func (pool *Pool) ActiveLen(queue string) (int, error) {
sess := pool.redis.Get()
defer sess.Close()
reply, err := sess.Do("JSCAN", "QUEUE", queue, "STATE", "active")
if err != nil {
return 0, err
}
replyArr, ok := reply.([]interface{})
if !ok || len(replyArr) != 2 {
return 0, errors.New("unexpected reply #1")
}
jobs, ok := replyArr[1].([]interface{})
if !ok {
return 0, errors.New("unexpected reply #2")
}
return len(jobs), nil
}