-
Notifications
You must be signed in to change notification settings - Fork 21
/
server.go
577 lines (480 loc) · 13.5 KB
/
server.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
package tasqueue
import (
"context"
"errors"
"fmt"
"log/slog"
"runtime"
"sync"
"time"
"github.com/robfig/cron/v3"
"github.com/vmihailenco/msgpack/v5"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/sdk/trace"
spans "go.opentelemetry.io/otel/trace"
)
const (
// This is the initial state when a job is pushed onto the broker.
StatusStarted = "queued"
// This is the state when a worker has recieved a job.
StatusProcessing = "processing"
// The state when a job completes, but returns an error (and all retries are over).
StatusFailed = "failed"
// The state when a job completes without any error.
StatusDone = "successful"
// The state when a job errors out and is queued again to be retried.
// This state is analogous to statusStarted.
StatusRetrying = "retrying"
// name used to identify this instrumentation library.
tracer = "tasqueue"
)
// handler represents a function that can accept arbitrary payload
// and process it in any manner. A job ctx is passed, which allows the handler access to job details
// and lets it save arbitrary results using JobCtx.Save()
type handler func([]byte, JobCtx) error
// Task is a pre-registered job handler. It stores the callbacks (set through options), which are
// called during different states of a job.
type Task struct {
name string
handler handler
opts TaskOpts
}
type TaskOpts struct {
Concurrency uint32
Queue string
SuccessCB func(JobCtx)
ProcessingCB func(JobCtx)
RetryingCB func(JobCtx, error)
FailedCB func(JobCtx, error)
}
// RegisterTask maps a new task against the tasks map on the server.
// It accepts different options for the task (to set callbacks).
func (s *Server) RegisterTask(name string, fn handler, opts TaskOpts) error {
s.log.Debug("registered handler", "name", name, "options", opts)
if opts.Queue == "" {
opts.Queue = DefaultQueue
}
if opts.Concurrency <= 0 {
opts.Concurrency = uint32(s.defaultConc)
}
s.q.RLock()
conc, ok := s.queues[opts.Queue]
s.q.RUnlock()
if !ok {
s.registerQueue(opts.Queue, opts.Concurrency)
s.registerHandler(name, Task{name: name, handler: fn, opts: opts})
return nil
}
// If the queue is already defined and the passed concurrency optional
// is same (it can be default queue/conc) so simply register the handler
if opts.Concurrency == conc {
s.registerHandler(name, Task{name: name, handler: fn, opts: opts})
return nil
}
// If queue is already registered but a new conc was defined, return an err
return fmt.Errorf("queue is already defined with %d concurrency", conc)
}
// Server is the main store that holds the broker and the results communication interfaces.
// It also stores the registered tasks.
type Server struct {
log *slog.Logger
broker Broker
results Results
cron *cron.Cron
traceProv *trace.TracerProvider
p sync.RWMutex
tasks map[string]Task
q sync.RWMutex
queues map[string]uint32
defaultConc int
}
type ServerOpts struct {
Broker Broker
Results Results
Logger slog.Handler
TraceProvider *trace.TracerProvider
}
// NewServer() returns a new instance of server, with sane defaults.
func NewServer(o ServerOpts) (*Server, error) {
if o.Broker == nil {
return nil, fmt.Errorf("broker missing in options")
}
if o.Results == nil {
return nil, fmt.Errorf("results missing in options")
}
if o.Logger == nil {
o.Logger = slog.Default().Handler()
}
return &Server{
traceProv: o.TraceProvider,
log: slog.New(o.Logger),
cron: cron.New(),
broker: o.Broker,
results: o.Results,
tasks: make(map[string]Task),
defaultConc: runtime.GOMAXPROCS(0),
queues: make(map[string]uint32),
}, nil
}
// GetTasks() returns a list of all tasks registered with the server.
func (s *Server) GetTasks() []string {
s.p.RLock()
tasks := s.tasks
s.p.RUnlock()
var (
t = make([]string, len(tasks))
i = 0
)
for k := range tasks {
t[i] = k
i++
}
return t
}
var ErrNotFound = errors.New("result not found")
// GetResult() accepts a ID and returns the result of the job in the results store.
func (s *Server) GetResult(ctx context.Context, id string) ([]byte, error) {
b, err := s.results.Get(ctx, id)
if err == nil {
return b, nil
}
// Check if error is due to key being invalid
if errors.Is(err, s.results.NilError()) {
return nil, ErrNotFound
}
return nil, err
}
// GetPending() returns the pending job message's in the broker's queue.
func (s *Server) GetPending(ctx context.Context, queue string) ([]JobMessage, error) {
rs, err := s.broker.GetPending(ctx, queue)
if err != nil {
return nil, err
}
var jobMsg = make([]JobMessage, len(rs))
for i, r := range rs {
if err := msgpack.Unmarshal([]byte(r), &jobMsg[i]); err != nil {
return nil, err
}
}
return jobMsg, nil
}
// DeleteJob() removes the stored results of a particular job. It does not "dequeue"
// an unprocessed job. It is useful for removing the status of old finished jobs.
func (s *Server) DeleteJob(ctx context.Context, id string) error {
return s.results.DeleteJob(ctx, id)
}
// GetFailed() returns the list of ids of jobs that failed.
func (s *Server) GetFailed(ctx context.Context) ([]string, error) {
return s.results.GetFailed(ctx)
}
// GetSuccess() returns the list of ids of jobs that were successful.
func (s *Server) GetSuccess(ctx context.Context) ([]string, error) {
return s.results.GetSuccess(ctx)
}
// Start() starts the job consumer and processor. It is a blocking function.
func (s *Server) Start(ctx context.Context) {
go s.cron.Start()
// Loop over each registered queue.
s.q.RLock()
queues := s.queues
s.q.RUnlock()
var wg sync.WaitGroup
for q, conc := range queues {
q := q // Hack to fix the loop variable capture issue.
if s.traceProv != nil {
var span spans.Span
ctx, span = otel.Tracer(tracer).Start(ctx, "start")
defer span.End()
}
work := make(chan []byte)
wg.Add(1)
go func() {
s.consume(ctx, work, q)
wg.Done()
}()
for i := 0; i < int(conc); i++ {
wg.Add(1)
go func() {
s.process(ctx, work)
wg.Done()
}()
}
}
wg.Wait()
}
// consume() listens on the queue for task messages and passes the task to processor.
func (s *Server) consume(ctx context.Context, work chan []byte, queue string) {
s.log.Debug("starting task consumer..")
s.broker.Consume(ctx, work, queue)
}
// process() listens on the work channel for tasks. On receiving a task it checks the
// processors map and passes payload to relevant processor.
func (s *Server) process(ctx context.Context, w chan []byte) {
s.log.Debug("starting processor..")
for {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "process")
defer span.End()
}
select {
case <-ctx.Done():
s.log.Info("shutting down processor..")
return
case work := <-w:
var (
msg JobMessage
err error
)
// Decode the bytes into a job message
if err = msgpack.Unmarshal(work, &msg); err != nil {
s.spanError(span, err)
s.log.Error("error unmarshalling task", "error", err)
break
}
// Fetch the registered task handler.
task, err := s.getHandler(msg.Job.Task)
if err != nil {
s.spanError(span, err)
s.log.Error("handler not found", "error", err)
break
}
// Set the job status as being "processed"
if err := s.statusProcessing(ctx, msg); err != nil {
s.spanError(span, err)
s.log.Error("error setting the status to processing", "error", err)
break
}
if err := s.execJob(ctx, msg, task); err != nil {
s.spanError(span, err)
s.log.Error("could not execute job", "error", err)
}
}
}
}
func (s *Server) execJob(ctx context.Context, msg JobMessage, task Task) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "exec_job")
defer span.End()
}
// Create the task context, which will be passed to the handler.
// TODO: maybe use sync.Pool
taskCtx := JobCtx{Meta: msg.Meta, store: s.results}
var (
// errChan is to receive the error returned by the handler.
errChan = make(chan error, 1)
err error
// jctx is the context passed to the job.
jctx, cancelFunc = context.WithCancel(ctx)
)
// If there is a deadline given, set that on jctx and not ctx
// because we don't want to cancel the entire context in case deadline exceeded.
if !(msg.Job.Opts.Timeout == 0) {
jctx, cancelFunc = context.WithDeadline(ctx, time.Now().Add(msg.Job.Opts.Timeout))
}
// Set jctx as the context for the task.
taskCtx.Context = jctx
if task.opts.ProcessingCB != nil {
task.opts.ProcessingCB(taskCtx)
}
go func() {
errChan <- task.handler(msg.Job.Payload, taskCtx)
close(errChan)
}()
select {
case <-jctx.Done():
cancelFunc()
err = jctx.Err()
if jctx.Err() == context.Canceled {
err = nil
}
case jerr := <-errChan:
cancelFunc()
err = jerr
if jerr == context.Canceled {
err = nil
}
}
if err != nil {
// Set the job's error
msg.PrevErr = err.Error()
// Try queueing the job again.
if msg.MaxRetry != msg.Retried {
if task.opts.RetryingCB != nil {
task.opts.RetryingCB(taskCtx, err)
}
return s.retryJob(ctx, msg)
} else {
if task.opts.FailedCB != nil {
task.opts.FailedCB(taskCtx, err)
}
// If there are jobs to enqueued after failure, enqueue them.
if msg.Job.OnError != nil {
// Extract OnErrorJob into a variable to get opts.
for _, j := range msg.Job.OnError {
nj := *j
meta := DefaultMeta(nj.Opts)
if _, err = s.enqueueWithMeta(ctx, nj, meta); err != nil {
return fmt.Errorf("error enqueuing jobs after failure: %w", err)
}
}
}
// If we hit max retries, set the task status as failed.
return s.statusFailed(ctx, msg)
}
}
if task.opts.SuccessCB != nil {
task.opts.SuccessCB(taskCtx)
}
// If the task contains OnSuccess task (part of a chain), enqueue them.
if msg.Job.OnSuccess != nil {
for _, j := range msg.Job.OnSuccess {
// Extract OnSuccessJob into a variable to get opts.
nj := *j
meta := DefaultMeta(nj.Opts)
meta.PrevJobResult, err = s.GetResult(ctx, msg.ID)
if err != nil {
return err
}
// Set the ID of the next job in the chain
onSuccessID, err := s.enqueueWithMeta(ctx, nj, meta)
if err != nil {
return err
}
msg.OnSuccessIDs = append(msg.OnSuccessIDs, onSuccessID)
}
}
if err := s.statusDone(ctx, msg); err != nil {
s.spanError(span, err)
return err
}
return nil
}
// retryJob() increments the retried count and re-queues the task message.
func (s *Server) retryJob(ctx context.Context, msg JobMessage) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "retry_job")
defer span.End()
}
msg.Retried += 1
b, err := msgpack.Marshal(msg)
if err != nil {
s.spanError(span, err)
return err
}
if err := s.statusRetrying(ctx, msg); err != nil {
s.spanError(span, err)
return err
}
if err := s.broker.Enqueue(ctx, b, msg.Queue); err != nil {
s.spanError(span, err)
return err
}
return nil
}
func (s *Server) registerQueue(name string, conc uint32) {
s.q.Lock()
s.queues[name] = conc
s.q.Unlock()
}
func (s *Server) registerHandler(name string, t Task) {
s.p.Lock()
s.tasks[name] = t
s.p.Unlock()
}
func (s *Server) getHandler(name string) (Task, error) {
s.p.RLock()
fn, ok := s.tasks[name]
s.p.RUnlock()
if !ok {
return Task{}, fmt.Errorf("handler %v not found", name)
}
return fn, nil
}
func (s *Server) statusStarted(ctx context.Context, t JobMessage) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "status_started")
defer span.End()
}
t.ProcessedAt = time.Now()
t.Status = StatusStarted
if err := s.setJobMessage(ctx, t); err != nil {
s.spanError(span, err)
return err
}
return nil
}
func (s *Server) statusProcessing(ctx context.Context, t JobMessage) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "status_processing")
defer span.End()
}
t.ProcessedAt = time.Now()
t.Status = StatusProcessing
if err := s.setJobMessage(ctx, t); err != nil {
s.spanError(span, err)
return err
}
return nil
}
func (s *Server) statusDone(ctx context.Context, t JobMessage) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "status_done")
defer span.End()
}
t.ProcessedAt = time.Now()
t.Status = StatusDone
if err := s.results.SetSuccess(ctx, t.ID); err != nil {
return err
}
if err := s.setJobMessage(ctx, t); err != nil {
s.spanError(span, err)
return err
}
return nil
}
func (s *Server) statusFailed(ctx context.Context, t JobMessage) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "status_failed")
defer span.End()
}
t.ProcessedAt = time.Now()
t.Status = StatusFailed
if err := s.results.SetFailed(ctx, t.ID); err != nil {
return err
}
if err := s.setJobMessage(ctx, t); err != nil {
s.spanError(span, err)
return err
}
return nil
}
func (s *Server) statusRetrying(ctx context.Context, t JobMessage) error {
var span spans.Span
if s.traceProv != nil {
ctx, span = otel.Tracer(tracer).Start(ctx, "status_retrying")
defer span.End()
}
t.ProcessedAt = time.Now()
t.Status = StatusRetrying
if err := s.setJobMessage(ctx, t); err != nil {
s.spanError(span, err)
return err
}
return nil
}
// spanError checks if tracing is enabled & adds an error to
// supplied span.
func (s *Server) spanError(sp spans.Span, err error) {
if s.traceProv != nil {
sp.RecordError(err)
sp.SetStatus(codes.Error, err.Error())
}
}