-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjobworker.go
494 lines (419 loc) · 10.2 KB
/
jobworker.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
package jobworker
import (
"context"
"errors"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/go-jwdk/jobworker/internal"
"github.com/hashicorp/go-multierror"
"github.com/vvatanabe/errsgroup"
)
type Setting struct {
Primary Connector
Secondary Connector
DeadConnectorRetryInterval int64 // Seconds
LoggerFunc LoggerFunc
}
var (
ErrPrimaryConnIsRequired = errors.New("primary conn is required")
ErrDuplicateEntryID = errors.New("duplicate entry id")
)
func New(s *Setting) (*JobWorker, error) {
if s.Primary == nil {
return nil, ErrPrimaryConnIsRequired
}
var w JobWorker
w.connProvider.Register(1, s.Primary)
if s.Secondary != nil {
w.connProvider.Register(2, s.Secondary)
}
w.connProvider.SetRetrySeconds(time.Duration(s.DeadConnectorRetryInterval) * time.Second)
w.loggerFunc = s.LoggerFunc
return &w, nil
}
type JobWorker struct {
connProvider ConnectorProvider
queue2worker map[string]*workerWithOption
loggerFunc LoggerFunc
inShutdown int32
mu sync.Mutex
activeJob map[*Job]struct{}
activeJobWg sync.WaitGroup
doneChan chan struct{}
heartBeat internal.HeartBeat
onShutdown []func()
}
type LoggerFunc func(...interface{})
func (jw *JobWorker) Enqueue(ctx context.Context, input *EnqueueInput) (*EnqueueOutput, error) {
conns := jw.connProvider.GetActiveConnsInPriorityOrder()
if len(conns) == 0 {
return nil, ErrNoActiveConn
}
var errs error
for priority, conn := range conns {
_, err := conn.Enqueue(ctx, input)
if err == nil {
// success
return &EnqueueOutput{}, nil
}
if err == ErrJobDuplicationDetected {
// success
jw.debug("skip enqueue a duplication job")
return &EnqueueOutput{}, nil
}
// fail
jw.debug("could not enqueue job. priority:", priority+1, "err:", err)
jw.connProvider.MarkDead(conn)
errs = multierror.Append(errs, err)
}
return nil, errs
}
func (jw *JobWorker) EnqueueBatch(ctx context.Context, input *EnqueueBatchInput) (*EnqueueBatchOutput, error) {
conns := jw.connProvider.GetActiveConnsInPriorityOrder()
if len(conns) == 0 {
return nil, ErrNoActiveConn
}
entryCnt := len(input.Entries)
entrySet := make(map[string]struct{})
for _, entry := range input.Entries {
entrySet[entry.ID] = struct{}{}
}
if len(entrySet) < entryCnt {
return nil, ErrDuplicateEntryID
}
var errs error
for priority, conn := range conns {
var entries []*EnqueueBatchEntry
for _, entry := range input.Entries {
if _, ok := entrySet[entry.ID]; ok {
entries = append(entries, entry)
}
}
output, err := conn.EnqueueBatch(ctx, &EnqueueBatchInput{
Queue: input.Queue,
Entries: entries,
})
if err != nil {
jw.debug("could not batch enqueue job all. priority: ", priority+1, "error: ", err)
errs = multierror.Append(errs, err)
jw.connProvider.MarkDead(conn)
continue
}
for _, id := range output.Successful {
delete(entrySet, id)
}
if len(output.Failed) > 0 {
continue
}
// success
return output, nil
}
var out EnqueueBatchOutput
for _, entry := range input.Entries {
if _, failed := entrySet[entry.ID]; failed {
out.Failed = append(out.Failed, entry.ID)
} else {
out.Successful = append(out.Successful, entry.ID)
}
}
return &out, errs
}
func (jw *JobWorker) RegisterFunc(queue string, f WorkerFunc, opts ...OptionFunc) {
jw.Register(queue, &defaultWorker{
workFunc: f,
}, opts...)
}
func (jw *JobWorker) Register(queue string, worker Worker, opts ...OptionFunc) {
var opt Option
opt.ApplyOptions(opts...)
jw.mu.Lock()
defer jw.mu.Unlock()
if jw.queue2worker == nil {
jw.queue2worker = make(map[string]*workerWithOption)
}
jw.queue2worker[queue] = &workerWithOption{
worker: worker,
opt: &opt,
}
}
const (
workerConcurrencyDefault = 1
)
type WorkSetting struct {
HeartbeatInterval int64 // Sec
OnHeartBeat func(job *Job)
WorkerConcurrency int
}
func (s *WorkSetting) setDefaults() {
if s.WorkerConcurrency == 0 {
s.WorkerConcurrency = workerConcurrencyDefault
}
}
func (jw *JobWorker) Work(s *WorkSetting) error {
s.setDefaults()
var b internal.Broadcaster
go func() {
<-jw.getDoneChan()
b.Broadcast()
}()
if s.HeartbeatInterval > 0 && s.OnHeartBeat != nil {
interval := time.Duration(s.HeartbeatInterval) * time.Second
_ = jw.heartBeat.Start(interval,
jw.newActiveJobHandlerFunc(s.OnHeartBeat))
b.Register(func() {
_ = jw.heartBeat.Stop()
})
}
jobCh := make(chan *Job)
for _, conn := range jw.connProvider.GetConnsInPriorityOrder() {
for name, w := range jw.queue2worker {
ctx := context.Background()
output, err := conn.Subscribe(ctx, &SubscribeInput{
Queue: name,
Metadata: w.opt.SubscribeMetadata,
})
if err != nil {
b.Broadcast()
return err
}
b.Register(func() {
jw.debug("unsubscribe:", name)
err := output.Subscription.UnSubscribe()
if err != nil {
jw.debug("an error occurred during unsubscribe:", name, err)
}
})
go func(sub Subscription) {
for job := range sub.Queue() {
jobCh <- job
}
jw.debug("Completed unsubscribe")
}(output.Subscription)
}
}
var wg sync.WaitGroup
for i := 0; i < s.WorkerConcurrency; i++ {
wg.Add(1)
go func(id int) {
sw := subWorker{id: strconv.Itoa(id), JobWorker: jw}
sw.work(jobCh)
wg.Done()
}(i)
}
wg.Wait()
close(jobCh)
jw.connProvider.Close()
return nil
}
func (jw *JobWorker) WorkOnceSafely(ctx context.Context, job *Job) {
connName := job.Conn.Name()
jw.debug("start work safely:", connName, job.QueueName, job.Content)
w, ok := jw.queue2worker[job.QueueName]
if !ok {
jw.debug("could not found worker. queue:", job.QueueName)
if err := failJob(ctx, job); err != nil {
jw.debug("mark dead connector, because error occurred during job fail:",
connName, job.QueueName, job.Content, err)
jw.connProvider.MarkDead(job.Conn)
}
return
}
if err := w.worker.Work(job); err != nil {
if err = failJob(ctx, job); err != nil {
jw.debug("mark dead connector, because error occurred during job fail:",
connName, job.QueueName, job.Content, err)
jw.connProvider.MarkDead(job.Conn)
}
return
}
if err := completeJob(ctx, job); err != nil {
jw.debug("mark dead connector, because error occurred during job complete:",
connName, job.QueueName, job.Content, err)
jw.connProvider.MarkDead(job.Conn)
return
}
jw.debug("success work safely:", connName, job.QueueName, job.Content)
}
func (jw *JobWorker) RegisterOnShutdown(f func()) {
jw.mu.Lock()
jw.onShutdown = append(jw.onShutdown, f)
jw.mu.Unlock()
}
func (jw *JobWorker) Shutdown(ctx context.Context) error {
atomic.StoreInt32(&jw.inShutdown, 1)
jw.mu.Lock()
jw.closeDoneChanLocked()
for _, f := range jw.onShutdown {
go f()
}
jw.mu.Unlock()
finished := make(chan struct{}, 1)
go func() {
jw.activeJobWg.Wait()
finished <- struct{}{}
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-finished:
return nil
}
}
const logPrefix = "[JWDK]"
func (jw *JobWorker) debug(args ...interface{}) {
if jw.verbose() {
args = append([]interface{}{logPrefix}, args...)
jw.loggerFunc(args...)
}
}
func (jw *JobWorker) verbose() bool {
return jw.loggerFunc != nil
}
func (jw *JobWorker) newActiveJobHandlerFunc(handler func(job *Job)) func() {
return func() {
var jobs []*Job
jw.mu.Lock()
for v := range jw.activeJob {
jobs = append(jobs, v)
}
jw.mu.Unlock()
go func(jobs []*Job) {
for _, job := range jobs {
handler(job)
}
}(jobs)
}
}
type Stats struct {
Jobs []*JobStat
}
type JobStat struct {
Conn string
Queue string
Content string
Metadata map[string]string
CustomAttribute map[string]*CustomAttribute
}
func newJobStat(job *Job) *JobStat {
metadata := make(map[string]string)
for k, v := range job.Metadata {
metadata[k] = v
}
customAttribute := make(map[string]*CustomAttribute)
for k, v := range job.CustomAttribute {
customAttribute[k] = &CustomAttribute{
DataType: v.DataType,
BinaryValue: v.BinaryValue,
StringValue: v.StringValue,
}
}
return &JobStat{
Conn: job.Conn.Name(),
Queue: job.QueueName,
Content: job.Content,
Metadata: metadata,
CustomAttribute: customAttribute,
}
}
func (jw *JobWorker) ForceExitActiveJob(ctx context.Context) error {
g := errsgroup.NewGroup()
for job := range jw.activeJob {
job := job
g.Go(func() error {
if job.IsFinished() {
return nil
}
_, err := job.Conn.FailJob(ctx, &FailJobInput{
Job: job,
})
if err != nil {
return err
}
job.finished()
return nil
})
}
errs := g.Wait()
if len(errs) > 0 {
return &multierror.Error{
Errors: errs,
}
}
return nil
}
func (jw *JobWorker) GetStats() *Stats {
var jobs []*Job
jw.mu.Lock()
for v := range jw.activeJob {
jobs = append(jobs, v)
}
jw.mu.Unlock()
var jobStats []*JobStat
for _, job := range jobs {
jobStats = append(jobStats, newJobStat(job))
}
return &Stats{Jobs: jobStats}
}
func (jw *JobWorker) shuttingDown() bool {
return atomic.LoadInt32(&jw.inShutdown) != 0
}
func (jw *JobWorker) trackJob(job *Job, add bool) {
jw.mu.Lock()
defer jw.mu.Unlock()
if jw.activeJob == nil {
jw.activeJob = make(map[*Job]struct{})
}
if add {
if !jw.shuttingDown() {
jw.activeJob[job] = struct{}{}
jw.activeJobWg.Add(1)
}
} else {
delete(jw.activeJob, job)
jw.activeJobWg.Done()
}
jw.debug("active job size:", len(jw.activeJob))
}
func (jw *JobWorker) getDoneChan() <-chan struct{} {
jw.mu.Lock()
defer jw.mu.Unlock()
return jw.getDoneChanLocked()
}
func (jw *JobWorker) getDoneChanLocked() chan struct{} {
if jw.doneChan == nil {
jw.doneChan = make(chan struct{})
}
return jw.doneChan
}
func (jw *JobWorker) closeDoneChanLocked() {
ch := jw.getDoneChanLocked()
select {
case <-ch:
default:
close(ch)
}
}
func completeJob(ctx context.Context, job *Job) error {
if job.IsFinished() {
return nil
}
_, err := job.Conn.CompleteJob(ctx, &CompleteJobInput{Job: job})
if err != nil {
return err
}
job.finished() // TODO move each connector
return nil
}
func failJob(ctx context.Context, job *Job) error {
if job.IsFinished() {
return nil
}
_, err := job.Conn.FailJob(ctx, &FailJobInput{Job: job})
if err != nil {
return err
}
job.finished() // TODO move each connector
return nil
}