forked from olivere/jobqueue
/
store.go
656 lines (599 loc) · 15 KB
/
store.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package mysql
import (
"context"
"database/sql"
"encoding/json"
"errors"
"sync"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/go-sql-driver/mysql"
"golang.org/x/sync/errgroup"
"github.com/vaibhav-sinha/jobqueue"
"github.com/vaibhav-sinha/jobqueue/mysql/internal"
)
// Store represents a persistent MySQL storage implementation.
// It implements the jobqueue.Store interface.
type Store struct {
db *sql.DB
debug bool
stmtOnce sync.Once
createStmt *sql.Stmt
updateStmt *sql.Stmt
deleteStmt *sql.Stmt
nextStmt *sql.Stmt
lookupStmt *sql.Stmt
lookupByCorrIDStmt *sql.Stmt
}
// StoreOption is an options provider for Store.
type StoreOption func(*Store)
// NewStore initializes a new MySQL-based storage.
func NewStore(url string, options ...StoreOption) (*Store, error) {
st := &Store{}
for _, opt := range options {
opt(st)
}
cfg, err := mysql.ParseDSN(url)
if err != nil {
return nil, err
}
dbname := cfg.DBName
if dbname == "" {
return nil, errors.New("no database specified")
}
// Now connect again, this time with the db name
st.db, err = sql.Open("mysql", url)
if err != nil {
return nil, err
}
return st, nil
}
func NewStoreWithDb(db *sql.DB, options ...StoreOption) (*Store, error) {
st := &Store{
db: db,
}
for _, opt := range options {
opt(st)
}
return st, nil
}
// SetDebug indicates whether to enable or disable debugging (which will
// output SQL to the console).
func SetDebug(enabled bool) StoreOption {
return func(s *Store) {
s.debug = enabled
}
}
func (s *Store) initStmt() {
var err error
// Create statement
s.createStmt, err = s.db.Prepare("INSERT INTO jobqueue_jobs (id,topic,state,args,`rank`,priority,retry,max_retry,correlation_group,correlation_id,created,started,completed,last_mod) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
if err != nil {
panic(err)
}
// Update statement
s.updateStmt, err = s.db.Prepare("UPDATE jobqueue_jobs SET topic=?,state=?,args=?,`rank`=?,priority=?,retry=?,max_retry=?,correlation_group=?,correlation_id=?,created=?,started=?,completed=?,last_mod=? WHERE id=?")
if err != nil {
panic(err)
}
// Delete statement
s.deleteStmt, err = s.db.Prepare("DELETE FROM jobqueue_jobs WHERE id=?")
if err != nil {
panic(err)
}
// Next statement
s.nextStmt, err = s.db.Prepare("SELECT id,topic,state,args,`rank`,priority,retry,max_retry,correlation_group,correlation_id,created,started,completed,last_mod FROM jobqueue_jobs WHERE state=? ORDER BY `rank` DESC, priority DESC LIMIT 1")
if err != nil {
panic(err)
}
// Lookup (by id) statement
s.lookupStmt, err = s.db.Prepare("SELECT id,topic,state,args,`rank`,priority,retry,max_retry,correlation_group,correlation_id,created,started,completed,last_mod FROM jobqueue_jobs WHERE id=? LIMIT 1")
if err != nil {
panic(err)
}
// Lookup by correlation id
s.lookupByCorrIDStmt, err = s.db.Prepare("SELECT id,topic,state,args,`rank`,priority,retry,max_retry,correlation_group,correlation_id,created,started,completed,last_mod FROM jobqueue_jobs WHERE correlation_id=? LIMIT 1")
if err != nil {
panic(err)
}
}
func (s *Store) wrapError(err error) error {
if internal.IsNotFound(err) {
// Map specific errors to jobqueue-specific "not found" error
return jobqueue.ErrNotFound
}
return err
}
// Start is called when the manager starts up.
// We ensure that stale jobs are marked as failed so that we have place
// for new jobs.
func (s *Store) Start(b jobqueue.StartupBehaviour) error {
s.stmtOnce.Do(s.initStmt)
if b == jobqueue.MarkAsFailed {
ctx := context.Background()
err := internal.RunInTxWithRetry(ctx, s.db, func(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(
ctx,
`UPDATE jobqueue_jobs SET state = ?, completed = ? WHERE state = ?`,
jobqueue.Failed,
time.Now().UnixNano(),
jobqueue.Working,
)
if err != nil {
return err
}
return nil
}, func(err error) bool {
return internal.IsDeadlock(err)
})
if err != nil {
return s.wrapError(err)
}
}
return nil
}
// Create adds a new job to the store.
func (s *Store) Create(ctx context.Context, job *jobqueue.Job) error {
s.stmtOnce.Do(s.initStmt)
j, err := newJob(job)
if err != nil {
return err
}
j.LastMod = j.Created
err = internal.RunInTxWithRetry(ctx, s.db, func(ctx context.Context, tx *sql.Tx) error {
res, err := tx.Stmt(s.createStmt).ExecContext(
ctx,
j.ID,
j.Topic,
j.State,
j.Args,
j.Rank,
j.Priority,
j.Retry,
j.MaxRetry,
j.CorrelationGroup,
j.CorrelationID,
j.Created,
j.Started,
j.Completed,
j.LastMod,
)
if err != nil {
return err
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return err
}
if rowsAffected != 1 {
return err
}
return nil
}, func(err error) bool {
return internal.IsDeadlock(err)
})
return s.wrapError(err)
}
// Update updates the job in the store.
func (s *Store) Update(ctx context.Context, job *jobqueue.Job) error {
s.stmtOnce.Do(s.initStmt)
j, err := newJob(job)
if err != nil {
return err
}
err = internal.RunInTxWithRetry(ctx, s.db, func(ctx context.Context, tx *sql.Tx) error {
var id string
err := tx.QueryRowContext(
ctx,
`SELECT id FROM jobqueue_jobs WHERE id = ? AND last_mod = ? FOR UPDATE`,
job.ID,
job.Updated,
).Scan(&id)
if err != nil {
return err
}
j.LastMod = time.Now().UnixNano()
res, err := tx.Stmt(s.updateStmt).ExecContext(
ctx,
j.Topic,
j.State,
j.Args,
j.Rank,
j.Priority,
j.Retry,
j.MaxRetry,
j.CorrelationGroup,
j.CorrelationID,
j.Created,
j.Started,
j.Completed,
j.LastMod,
j.ID,
)
if err != nil {
return err
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return err
}
if rowsAffected != 1 {
return err
}
job.Updated = j.LastMod
return nil
}, func(err error) bool {
return internal.IsDeadlock(err)
})
return s.wrapError(err)
}
// Next picks the next job to execute, or nil if no executable job is available.
func (s *Store) Next() (*jobqueue.Job, error) {
s.stmtOnce.Do(s.initStmt)
var j Job
ctx := context.Background()
err := internal.RunWithRetry(ctx, s.db, func(ctx context.Context) error {
err := s.nextStmt.QueryRowContext(ctx, jobqueue.Waiting).Scan(
&j.ID,
&j.Topic,
&j.State,
&j.Args,
&j.Rank,
&j.Priority,
&j.Retry,
&j.MaxRetry,
&j.CorrelationGroup,
&j.CorrelationID,
&j.Created,
&j.Started,
&j.Completed,
&j.LastMod,
)
if err != nil {
return err
}
return nil
}, func(err error) bool {
return internal.IsDeadlock(err)
})
if internal.IsNotFound(err) {
return nil, jobqueue.ErrNotFound
}
if err != nil {
return nil, s.wrapError(err)
}
return j.ToJob()
}
// Delete removes a job from the store.
func (s *Store) Delete(ctx context.Context, job *jobqueue.Job) error {
s.stmtOnce.Do(s.initStmt)
err := internal.RunInTxWithRetry(ctx, s.db, func(ctx context.Context, tx *sql.Tx) error {
_, err := tx.Stmt(s.deleteStmt).ExecContext(ctx, job.ID)
switch {
case err == sql.ErrNoRows:
return nil
default:
return err
}
}, func(err error) bool {
return internal.IsDeadlock(err)
})
return s.wrapError(err)
}
// Lookup retrieves a single job in the store by its identifier.
func (s *Store) Lookup(ctx context.Context, id string) (*jobqueue.Job, error) {
s.stmtOnce.Do(s.initStmt)
var j Job
err := internal.RunWithRetry(ctx, s.db, func(ctx context.Context) error {
err := s.lookupStmt.QueryRowContext(ctx, id).Scan(
&j.ID,
&j.Topic,
&j.State,
&j.Args,
&j.Rank,
&j.Priority,
&j.Retry,
&j.MaxRetry,
&j.CorrelationGroup,
&j.CorrelationID,
&j.Created,
&j.Started,
&j.Completed,
&j.LastMod,
)
if err != nil {
return err
}
return nil
}, func(err error) bool {
return internal.IsDeadlock(err)
})
if err != nil {
return nil, s.wrapError(err)
}
return j.ToJob()
}
// LookupByCorrelationID returns the details of jobs by their correlation identifier.
// If no such job could be found, an empty array is returned.
func (s *Store) LookupByCorrelationID(ctx context.Context, correlationID string) ([]*jobqueue.Job, error) {
s.stmtOnce.Do(s.initStmt)
var jobs []Job
err := internal.RunWithRetry(ctx, s.db, func(ctx context.Context) error {
rows, err := s.lookupByCorrIDStmt.QueryContext(ctx, correlationID)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var j Job
err := rows.Scan(
&j.ID,
&j.Topic,
&j.State,
&j.Args,
&j.Rank,
&j.Priority,
&j.Retry,
&j.MaxRetry,
&j.CorrelationGroup,
&j.CorrelationID,
&j.Created,
&j.Started,
&j.Completed,
&j.LastMod,
)
if err != nil {
return err
}
jobs = append(jobs, j)
}
if err := rows.Err(); err != nil {
return err
}
return nil
}, func(err error) bool {
return internal.IsDeadlock(err)
})
if err != nil {
return nil, s.wrapError(err)
}
result := make([]*jobqueue.Job, len(jobs))
for i, j := range jobs {
job, err := j.ToJob()
if err != nil {
return nil, s.wrapError(err)
}
result[i] = job
}
return result, nil
}
// List returns a list of all jobs stored in the data store.
func (s *Store) List(ctx context.Context, request *jobqueue.ListRequest) (*jobqueue.ListResponse, error) {
s.stmtOnce.Do(s.initStmt)
resp := &jobqueue.ListResponse{}
columns := "id,topic,state,args,`rank`,priority,retry,max_retry,correlation_group,correlation_id,created,started,completed,last_mod"
where := make(map[string]interface{})
countBuilder := sq.Select("COUNT(*)").From("jobqueue_jobs")
queryBuilder := sq.Select(columns).From("jobqueue_jobs")
// Filters
if v := request.Topic; v != "" {
where["topic"] = v
}
if v := request.State; v != "" {
where["state"] = v
}
if v := request.CorrelationGroup; v != "" {
where["correlation_group"] = v
}
if v := request.CorrelationID; v != "" {
where["correlation_id"] = v
}
// Count
countBuilder = sq.Select("COUNT(*)").From("jobqueue_jobs").Where(where)
{
sql, args, err := countBuilder.ToSql()
if err != nil {
return nil, s.wrapError(err)
}
err = s.db.QueryRowContext(ctx, sql, args...).Scan(
&resp.Total,
)
if err != nil {
return nil, s.wrapError(err)
}
}
// Iterate
queryBuilder = sq.Select(columns).
From("jobqueue_jobs").
Where(where).
OrderBy("last_mod DESC").
Offset(uint64(request.Offset)).Limit(uint64(request.Limit))
{
sql, args, err := queryBuilder.ToSql()
if err != nil {
return nil, s.wrapError(err)
}
rows, err := s.db.QueryContext(ctx, sql, args...)
if err != nil {
return nil, s.wrapError(err)
}
defer rows.Close()
for rows.Next() {
var j Job
err := rows.Scan(
&j.ID,
&j.Topic,
&j.State,
&j.Args,
&j.Rank,
&j.Priority,
&j.Retry,
&j.MaxRetry,
&j.CorrelationGroup,
&j.CorrelationID,
&j.Created,
&j.Started,
&j.Completed,
&j.LastMod,
)
if err != nil {
return nil, s.wrapError(err)
}
job, err := j.ToJob()
if err != nil {
return nil, s.wrapError(err)
}
resp.Jobs = append(resp.Jobs, job)
}
if err := rows.Err(); err != nil {
return nil, s.wrapError(err)
}
}
return resp, nil
}
// Stats returns statistics about the jobs in the store.
func (s *Store) Stats(ctx context.Context, req *jobqueue.StatsRequest) (*jobqueue.Stats, error) {
s.stmtOnce.Do(s.initStmt)
stats := new(jobqueue.Stats)
g, ctx := errgroup.WithContext(ctx)
// Waiting
g.Go(func() error {
where := map[string]interface{}{
"state": jobqueue.Waiting,
}
if v := req.Topic; v != "" {
where["topic"] = v
}
if v := req.CorrelationGroup; v != "" {
where["correlation_group"] = v
}
sql, args, err := sq.Select("COUNT(*)").From("jobqueue_jobs").Where(where).ToSql()
if err != nil {
return err
}
return s.db.QueryRowContext(ctx, sql, args...).Scan(&stats.Waiting)
})
// Working
g.Go(func() error {
where := map[string]interface{}{
"state": jobqueue.Working,
}
if v := req.Topic; v != "" {
where["topic"] = v
}
if v := req.CorrelationGroup; v != "" {
where["correlation_group"] = v
}
sql, args, err := sq.Select("COUNT(*)").From("jobqueue_jobs").Where(where).ToSql()
if err != nil {
return err
}
return s.db.QueryRowContext(ctx, sql, args...).Scan(&stats.Working)
})
// Succeeded
g.Go(func() error {
where := map[string]interface{}{
"state": jobqueue.Succeeded,
}
if v := req.Topic; v != "" {
where["topic"] = v
}
if v := req.CorrelationGroup; v != "" {
where["correlation_group"] = v
}
sql, args, err := sq.Select("COUNT(*)").From("jobqueue_jobs").Where(where).ToSql()
if err != nil {
return err
}
return s.db.QueryRowContext(ctx, sql, args...).Scan(&stats.Succeeded)
})
// Failed
g.Go(func() error {
where := map[string]interface{}{
"state": jobqueue.Failed,
}
if v := req.Topic; v != "" {
where["topic"] = v
}
if v := req.CorrelationGroup; v != "" {
where["correlation_group"] = v
}
sql, args, err := sq.Select("COUNT(*)").From("jobqueue_jobs").Where(where).ToSql()
if err != nil {
return err
}
return s.db.QueryRowContext(ctx, sql, args...).Scan(&stats.Failed)
})
if err := g.Wait(); err != nil {
return nil, s.wrapError(err)
}
return stats, nil
}
// -- MySQL-internal representation of a task --
type Job struct {
ID string
Topic string
State string
Args sql.NullString
Rank int
Priority int64
Retry int
MaxRetry int
CorrelationGroup sql.NullString
CorrelationID sql.NullString
Created int64
Started int64
Completed int64
LastMod int64
}
func newJob(job *jobqueue.Job) (*Job, error) {
var args string
if job.Args != nil {
v, err := json.Marshal(job.Args)
if err != nil {
return nil, err
}
args = string(v)
}
return &Job{
ID: job.ID,
Topic: job.Topic,
State: job.State,
Args: sql.NullString{String: args, Valid: args != ""},
Rank: job.Rank,
Priority: job.Priority,
Retry: job.Retry,
MaxRetry: job.MaxRetry,
CorrelationGroup: sql.NullString{String: job.CorrelationGroup, Valid: job.CorrelationGroup != ""},
CorrelationID: sql.NullString{String: job.CorrelationID, Valid: job.CorrelationID != ""},
Created: job.Created,
LastMod: job.Updated,
Started: job.Started,
Completed: job.Completed,
}, nil
}
func (j *Job) ToJob() (*jobqueue.Job, error) {
var args []interface{}
if j.Args.Valid && j.Args.String != "" {
if err := json.Unmarshal([]byte(j.Args.String), &args); err != nil {
return nil, err
}
}
job := &jobqueue.Job{
ID: j.ID,
Topic: j.Topic,
State: j.State,
Args: args,
Rank: j.Rank,
Priority: j.Priority,
Retry: j.Retry,
MaxRetry: j.MaxRetry,
CorrelationGroup: j.CorrelationGroup.String,
CorrelationID: j.CorrelationID.String,
Created: j.Created,
Started: j.Started,
Updated: j.LastMod,
Completed: j.Completed,
}
return job, nil
}