-
Notifications
You must be signed in to change notification settings - Fork 3
/
queue.go
252 lines (209 loc) · 5.16 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
package axe
import (
"fmt"
"math/rand"
"sync"
"time"
"gopkg.in/tomb.v2"
"github.com/256dpi/fire"
"github.com/256dpi/fire/coal"
)
type board struct {
sync.Mutex
jobs map[coal.ID]*Job
}
// Queue manages the queueing of jobs.
type Queue struct {
// MaxLag defines the maximum amount of lag that should be applied to every
// dequeue attempt.
//
// By default multiple processes compete with each other when getting jobs
// from the same queue. An artificial lag prevents multiple simultaneous
// dequeue attempts and allows the worker with the smallest lag to dequeue
// the job and inform the other processes to prevent another dequeue attempt.
//
// Default: 100ms.
MaxLag time.Duration
// DequeueInterval defines the time after a worker might try to dequeue a job
// again that has not yet been associated.
//
// Default: 2s.
DequeueInterval time.Duration
store *coal.Store
reporter func(error)
tasks map[string]*Task
boards map[string]*board
tomb tomb.Tomb
}
// NewQueue creates and returns a new queue.
func NewQueue(store *coal.Store, reporter func(error)) *Queue {
return &Queue{
store: store,
reporter: reporter,
tasks: make(map[string]*Task),
}
}
// Add will add the specified task to the queue.
func (q *Queue) Add(task *Task) {
// check existence
if q.tasks[task.Name] != nil {
panic(fmt.Sprintf(`axe: task with name "%s" already exists`, task.Name))
}
// save task
q.tasks[task.Name] = task
}
// Enqueue will enqueue a job using the specified blueprint.
func (q *Queue) Enqueue(bp Blueprint) (*Job, error) {
// enqueue job
job, err := Enqueue(q.store, nil, bp)
if err != nil {
return nil, err
}
return job, nil
}
// Callback is a factory to create callbacks that can be used to enqueue jobs
// during request processing.
func (q *Queue) Callback(matcher fire.Matcher, cb func(ctx *fire.Context) Blueprint) *fire.Callback {
return fire.C("axe/Queue.Callback", matcher, func(ctx *fire.Context) error {
// get blueprint
bp := cb(ctx)
// check if controller uses same store
if q.store == ctx.Controller.Store {
// enqueue job using context store
_, err := Enqueue(ctx.Store, ctx, bp)
if err != nil {
return err
}
} else {
// enqueue job using queue store
_, err := q.Enqueue(bp)
if err != nil {
return err
}
}
return nil
})
}
// Action is a factory to create an action that can be used to enqueue jobs.
func (q *Queue) Action(methods []string, cb func(ctx *fire.Context) Blueprint) *fire.Action {
return fire.A("axe/Queue.Callback", methods, 0, func(ctx *fire.Context) error {
// get blueprint
bp := cb(ctx)
// check if controller uses same store
if q.store == ctx.Controller.Store {
// enqueue job using context store
_, err := Enqueue(ctx.Store, ctx, bp)
if err != nil {
return err
}
} else {
// enqueue job using queue store
_, err := q.Enqueue(bp)
if err != nil {
return err
}
}
// respond with an empty object
err := ctx.Respond(fire.Map{})
if err != nil {
return err
}
return nil
})
}
// Run will start fetching jobs from the queue and process them.
func (q *Queue) Run() {
// set default max lag
if q.MaxLag == 0 {
q.MaxLag = 100 * time.Millisecond
}
// set default dequeue interval
if q.DequeueInterval == 0 {
q.DequeueInterval = 2 * time.Second
}
// initialize boards
q.boards = make(map[string]*board)
// create boards
for _, task := range q.tasks {
q.boards[task.Name] = &board{
jobs: make(map[coal.ID]*Job),
}
}
// run process
q.tomb.Go(q.process)
}
// Close will close the queue.
func (q *Queue) Close() {
// kill and wait
q.tomb.Kill(nil)
_ = q.tomb.Wait()
}
func (q *Queue) process() error {
// start tasks
for _, task := range q.tasks {
task.start(q)
}
// reconcile jobs
stream := coal.Reconcile(q.store, &Job{}, func(model coal.Model) {
q.update(model.(*Job))
}, func(model coal.Model) {
q.update(model.(*Job))
}, nil, q.reporter)
// await close
<-q.tomb.Dying()
// close stream
stream.Close()
return tomb.ErrDying
}
func (q *Queue) update(job *Job) {
// get board
board, ok := q.boards[job.Name]
if !ok {
return
}
// lock board
board.Lock()
defer board.Unlock()
// handle job
switch job.Status {
case StatusEnqueued, StatusDequeued, StatusFailed:
// apply random lag if configured
if q.MaxLag > 0 {
lag := time.Duration(rand.Int63n(int64(q.MaxLag)))
job.Available = job.Available.Add(lag)
}
// updated job
board.jobs[job.ID()] = job
case StatusCompleted, StatusCancelled:
// remove job
delete(board.jobs, job.ID())
}
}
func (q *Queue) get(name string) *Job {
// get board
board := q.boards[name]
// acquire mutex
board.Lock()
defer board.Unlock()
// get time
now := time.Now()
// get a random job
var job *Job
for _, job = range board.jobs {
// ignore jobs that are not yet available
if job.Available.After(now) {
job = nil
continue
}
break
}
// check job
if job == nil {
return nil
}
// make job unavailable until the specified timeout has been reached. this
// ensures that a job dequeued by a crashed worker will be picked up by
// another worker at some point
job.Available = job.Available.Add(q.DequeueInterval)
return job
}