-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
752 lines (667 loc) · 19.5 KB
/
queue.go
File metadata and controls
752 lines (667 loc) · 19.5 KB
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
package queue
import (
"context"
"encoding/json"
"fmt"
"reflect"
"sync"
"time"
"github.com/goforj/queue/busruntime"
)
type queueRuntime interface {
// Driver returns the active queue driver.
// @group Driver Integration
Driver() Driver
// Dispatch submits a typed job payload using the default queue.
// @group Driver Integration
Dispatch(job any) error
// DispatchCtx submits a typed job payload using the provided context.
// @group Driver Integration
DispatchCtx(ctx context.Context, job any) error
// Register associates a handler with a job type.
// @group Driver Integration
Register(jobType string, handler Handler)
// StartWorkers starts worker execution.
// @group Driver Integration
StartWorkers(ctx context.Context) error
// Workers sets desired worker concurrency before StartWorkers.
// @group Driver Integration
Workers(count int) queueRuntime
// Shutdown drains running work and releases resources.
// @group Driver Integration
Shutdown(ctx context.Context) error
// Ready checks backend readiness for dispatch/worker operation.
// @group Driver Integration
Ready(ctx context.Context) error
}
// WorkerpoolConfig configures the in-memory workerpool q.
// @group Config
type WorkerpoolConfig struct {
Workers int
QueueCapacity int
DefaultJobTimeout time.Duration
}
func (c WorkerpoolConfig) normalize() WorkerpoolConfig {
c.Workers = defaultWorkerCount(c.Workers)
if c.QueueCapacity <= 0 {
c.QueueCapacity = c.Workers
}
return c
}
// Config configures queue creation for New (and advanced driver/runtime interop).
// @group Config
type Config struct {
Driver Driver
Observer Observer
DefaultQueue string
}
type queueBackend interface {
Driver() Driver
Dispatch(ctx context.Context, job Job) error
Shutdown(ctx context.Context) error
}
type runtimeQueueBackend interface {
queueBackend
Register(jobType string, handler Handler)
StartWorkers(ctx context.Context) error
}
func newSyncQueue() queueBackend {
return newLocalQueueWithConfig(DriverSync, WorkerpoolConfig{})
}
// New creates the high-level Queue API based on Config.Driver.
// @group Constructors
//
// Example: create a queue and dispatch a workflow-capable job
//
// q, err := queue.New(queue.Config{Driver: queue.DriverWorkerpool})
// if err != nil {
// return
// }
// type EmailPayload struct {
// ID int `json:"id"`
// }
// q.Register("emails:send", func(ctx context.Context, m queue.Message) error {
// var payload EmailPayload
// if err := m.Bind(&payload); err != nil {
// return err
// }
// _ = payload
// return nil
// })
// _ = q.WithWorkers(1).StartWorkers(context.Background()) // optional; default: runtime.NumCPU() (min 1)
// defer q.Shutdown(context.Background())
// _, _ = q.Dispatch(
// queue.NewJob("emails:send").
// Payload(EmailPayload{ID: 1}).
// OnQueue("default"),
// )
func New(cfg Config, opts ...Option) (*Queue, error) {
return newHighLevelQueue(cfg, opts...)
}
func newRuntime(cfg Config) (queueRuntime, error) {
cfg = cfg.normalize()
var q queueBackend
var err error
switch cfg.Driver {
case DriverNull:
q = newNullQueue()
case DriverSync:
q = newSyncQueue()
case DriverWorkerpool:
q = newLocalQueueWithConfig(DriverWorkerpool, WorkerpoolConfig{})
case DriverDatabase:
return nil, optionalDriverMovedError(cfg.Driver)
case DriverRedis:
return nil, optionalDriverMovedError(cfg.Driver)
case DriverNATS:
return nil, optionalDriverMovedError(cfg.Driver)
case DriverSQS:
return nil, optionalDriverMovedError(cfg.Driver)
case DriverRabbitMQ:
return nil, optionalDriverMovedError(cfg.Driver)
default:
return nil, fmt.Errorf("unsupported queue driver %q", cfg.Driver)
}
if err != nil {
return nil, err
}
var runtime runtimeQueueBackend
if native, ok := q.(runtimeQueueBackend); ok {
runtime = native
}
common := &queueCommon{
inner: newObservedQueue(q, cfg.Driver, cfg.Observer),
cfg: cfg,
driver: cfg.Driver,
}
if runtime != nil {
return &nativeQueueRuntime{
common: common,
runtime: runtime,
registered: make(map[string]Handler),
}, nil
}
return &externalQueueRuntime{
common: common,
registered: make(map[string]Handler),
}, nil
}
func (cfg Config) normalize() Config {
if cfg.DefaultQueue == "" {
cfg.DefaultQueue = "default"
}
return cfg
}
type queueCommon struct {
inner queueBackend
cfg Config
driver Driver
}
type nativeQueueRuntime struct {
common *queueCommon
runtime runtimeQueueBackend
mu sync.Mutex
registered map[string]Handler
started bool
workers int
}
type externalQueueRuntime struct {
common *queueCommon
mu sync.Mutex
registered map[string]Handler
worker runtimeWorkerBackend
started bool
workers int
newWorker driverWorkerFactory
}
type runtimeWorkerBackend interface {
Register(jobType string, handler Handler)
StartWorkers(ctx context.Context) error
Shutdown(ctx context.Context) error
}
func (q *queueCommon) Driver() Driver {
return q.driver
}
func (q *queueCommon) Dispatch(job any) error {
return q.DispatchCtx(context.Background(), job)
}
func (q *queueCommon) DispatchCtx(ctx context.Context, job any) error {
dispatchJob, err := q.jobFromAny(job)
if err != nil {
return err
}
return q.inner.Dispatch(ctx, dispatchJob)
}
func (q *nativeQueueRuntime) Driver() Driver { return q.common.Driver() }
func (q *nativeQueueRuntime) Dispatch(job any) error { return q.common.Dispatch(job) }
func (q *nativeQueueRuntime) DispatchCtx(ctx context.Context, job any) error {
return q.common.DispatchCtx(ctx, job)
}
func (q *externalQueueRuntime) Driver() Driver { return q.common.Driver() }
func (q *externalQueueRuntime) Dispatch(job any) error { return q.common.Dispatch(job) }
func (q *externalQueueRuntime) DispatchCtx(ctx context.Context, job any) error {
return q.common.DispatchCtx(ctx, job)
}
func (q *nativeQueueRuntime) BusRegister(jobType string, handler busruntime.Handler) {
if handler == nil {
q.Register(jobType, nil)
return
}
q.Register(jobType, func(ctx context.Context, job Job) error {
return handler(ctx, job)
})
}
func (q *externalQueueRuntime) BusRegister(jobType string, handler busruntime.Handler) {
if handler == nil {
q.Register(jobType, nil)
return
}
q.Register(jobType, func(ctx context.Context, job Job) error {
return handler(ctx, job)
})
}
func (q *nativeQueueRuntime) BusDispatch(ctx context.Context, jobType string, payload []byte, opts busruntime.JobOptions) error {
return q.common.dispatchBusJob(ctx, jobType, payload, opts)
}
func (q *externalQueueRuntime) BusDispatch(ctx context.Context, jobType string, payload []byte, opts busruntime.JobOptions) error {
return q.common.dispatchBusJob(ctx, jobType, payload, opts)
}
func (q *nativeQueueRuntime) Register(jobType string, handler Handler) {
q.mu.Lock()
if q.registered == nil {
q.registered = make(map[string]Handler)
}
q.registered[jobType] = handler
started := q.started
q.mu.Unlock()
if started {
q.runtime.Register(jobType, q.common.wrapRegisteredHandler(jobType, handler))
}
}
func (q *externalQueueRuntime) Register(jobType string, handler Handler) {
q.mu.Lock()
if q.registered == nil {
q.registered = make(map[string]Handler)
}
q.registered[jobType] = handler
w := q.worker
started := q.started
q.mu.Unlock()
if started && w != nil {
w.Register(jobType, q.common.wrapRegisteredHandler(jobType, handler))
}
}
func (q *nativeQueueRuntime) StartWorkers(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
if q.started {
q.mu.Unlock()
return nil
}
registered := make(map[string]Handler, len(q.registered))
for jobType, handler := range q.registered {
registered[jobType] = handler
}
q.mu.Unlock()
for jobType, handler := range registered {
q.runtime.Register(jobType, q.common.wrapRegisteredHandler(jobType, handler))
}
if err := q.runtime.StartWorkers(ctx); err != nil {
return err
}
q.mu.Lock()
q.started = true
q.mu.Unlock()
return nil
}
func (q *externalQueueRuntime) StartWorkers(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
if q.started {
q.mu.Unlock()
return nil
}
workers := q.workers
registered := make(map[string]Handler, len(q.registered))
for jobType, handler := range q.registered {
registered[jobType] = handler
}
q.mu.Unlock()
var (
w runtimeWorkerBackend
err error
)
if q.newWorker != nil {
driverWorker, e := q.newWorker(defaultWorkerCount(workers))
if e != nil {
return e
}
w = driverWorkerBackendAdapter{driverWorker}
} else {
w, err = newExternalWorker(q.common.cfg, workers)
if err != nil {
return err
}
}
for jobType, handler := range registered {
w.Register(jobType, q.common.wrapRegisteredHandler(jobType, handler))
}
if err := w.StartWorkers(ctx); err != nil {
return err
}
q.mu.Lock()
q.worker = w
q.started = true
q.mu.Unlock()
return nil
}
func (q *nativeQueueRuntime) Workers(count int) queueRuntime {
q.mu.Lock()
defer q.mu.Unlock()
if !q.started && count > 0 {
q.workers = count
}
return q
}
func (q *externalQueueRuntime) Workers(count int) queueRuntime {
q.mu.Lock()
defer q.mu.Unlock()
if !q.started && count > 0 {
q.workers = count
}
return q
}
func (q *nativeQueueRuntime) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
wasStarted := q.started
q.started = false
q.mu.Unlock()
if wasStarted {
return q.runtime.Shutdown(ctx)
}
return nil
}
func (q *externalQueueRuntime) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
w := q.worker
wasStarted := q.started
q.started = false
q.worker = nil
q.mu.Unlock()
if wasStarted {
if w != nil {
if err := w.Shutdown(ctx); err != nil {
return err
}
}
}
return q.common.inner.Shutdown(ctx)
}
func (q *queueCommon) Pause(ctx context.Context, queueName string) error {
controller, ok := q.inner.(QueueController)
if !ok {
return ErrPauseUnsupported
}
return controller.Pause(ctx, queueName)
}
func (q *queueCommon) Resume(ctx context.Context, queueName string) error {
controller, ok := q.inner.(QueueController)
if !ok {
return ErrPauseUnsupported
}
return controller.Resume(ctx, queueName)
}
func (q *queueCommon) Stats(ctx context.Context) (StatsSnapshot, error) {
provider, ok := q.inner.(StatsProvider)
if !ok {
return StatsSnapshot{}, fmt.Errorf("stats provider is not available for driver %q", q.Driver())
}
return provider.Stats(ctx)
}
func (q *queueCommon) Ready(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
if err := ctx.Err(); err != nil {
return err
}
return runtimeReadyCheck(ctx, q.inner)
}
func (q *nativeQueueRuntime) Pause(ctx context.Context, queueName string) error {
return q.common.Pause(ctx, queueName)
}
func (q *nativeQueueRuntime) Resume(ctx context.Context, queueName string) error {
return q.common.Resume(ctx, queueName)
}
func (q *nativeQueueRuntime) Stats(ctx context.Context) (StatsSnapshot, error) {
return q.common.Stats(ctx)
}
func (q *nativeQueueRuntime) Ready(ctx context.Context) error {
return q.common.Ready(ctx)
}
func (q *externalQueueRuntime) Pause(ctx context.Context, queueName string) error {
return q.common.Pause(ctx, queueName)
}
func (q *externalQueueRuntime) Resume(ctx context.Context, queueName string) error {
return q.common.Resume(ctx, queueName)
}
func (q *externalQueueRuntime) Stats(ctx context.Context) (StatsSnapshot, error) {
return q.common.Stats(ctx)
}
func (q *externalQueueRuntime) Ready(ctx context.Context) error {
return q.common.Ready(ctx)
}
func (q *queueCommon) wrapRegisteredHandler(jobType string, handler Handler) Handler {
if handler == nil || q.cfg.Observer == nil {
return handler
}
// Redis worker emits process lifecycle events natively.
// Skip shared handler wrapping to avoid duplicate process_* events.
if q.cfg.Driver == DriverRedis {
return handler
}
return wrapObservedHandler(q.cfg.Observer, q.cfg.Driver, "", jobType, handler)
}
func (q *queueCommon) dispatchBusJob(ctx context.Context, jobType string, payload []byte, opts busruntime.JobOptions) error {
job := NewJob(jobType).Payload(payload)
if opts.Queue != "" {
job = job.OnQueue(opts.Queue)
}
if opts.Delay > 0 {
job = job.Delay(opts.Delay)
}
if opts.Timeout > 0 {
job = job.Timeout(opts.Timeout)
}
if opts.Retry > 0 {
job = job.Retry(opts.Retry)
}
if opts.Backoff > 0 {
job = job.Backoff(opts.Backoff)
}
if opts.UniqueFor > 0 {
job = job.UniqueFor(opts.UniqueFor)
}
return q.inner.Dispatch(ctx, job)
}
func newExternalWorker(cfg Config, concurrency int) (runtimeWorkerBackend, error) {
switch cfg.Driver {
default:
return nil, fmt.Errorf("unsupported queue driver %q", cfg.Driver)
}
}
type driverQueueBackendAdapter struct {
driverQueueBackend
}
type driverRuntimeQueueBackendAdapter struct {
driverRuntimeQueueBackend
}
type driverWorkerBackendAdapter struct {
driverWorkerBackend
}
func (a driverQueueBackendAdapter) Pause(ctx context.Context, queueName string) error {
controller, ok := a.driverQueueBackend.(QueueController)
if !ok {
return ErrPauseUnsupported
}
return controller.Pause(ctx, queueName)
}
func (a driverQueueBackendAdapter) Resume(ctx context.Context, queueName string) error {
controller, ok := a.driverQueueBackend.(QueueController)
if !ok {
return ErrPauseUnsupported
}
return controller.Resume(ctx, queueName)
}
func (a driverQueueBackendAdapter) Stats(ctx context.Context) (StatsSnapshot, error) {
provider, ok := a.driverQueueBackend.(StatsProvider)
if !ok {
return StatsSnapshot{}, fmt.Errorf("stats provider is not available for driver %q", a.Driver())
}
return provider.Stats(ctx)
}
func (a driverQueueBackendAdapter) Ready(ctx context.Context) error {
return runtimeReadyCheck(ctx, a.driverQueueBackend)
}
func (a driverQueueBackendAdapter) ListJobs(ctx context.Context, opts ListJobsOptions) (ListJobsResult, error) {
admin, ok := a.driverQueueBackend.(QueueAdmin)
if !ok {
return ListJobsResult{}, ErrQueueAdminUnsupported
}
return admin.ListJobs(ctx, opts)
}
func (a driverQueueBackendAdapter) RetryJob(ctx context.Context, queueName, jobID string) error {
admin, ok := a.driverQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.RetryJob(ctx, queueName, jobID)
}
func (a driverQueueBackendAdapter) CancelJob(ctx context.Context, jobID string) error {
admin, ok := a.driverQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.CancelJob(ctx, jobID)
}
func (a driverQueueBackendAdapter) DeleteJob(ctx context.Context, queueName, jobID string) error {
admin, ok := a.driverQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.DeleteJob(ctx, queueName, jobID)
}
func (a driverQueueBackendAdapter) ClearQueue(ctx context.Context, queueName string) error {
admin, ok := a.driverQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.ClearQueue(ctx, queueName)
}
func (a driverQueueBackendAdapter) History(ctx context.Context, queueName string, window QueueHistoryWindow) ([]QueueHistoryPoint, error) {
admin, ok := a.driverQueueBackend.(QueueAdmin)
if !ok {
return nil, ErrQueueAdminUnsupported
}
return admin.History(ctx, queueName, window)
}
func (a driverRuntimeQueueBackendAdapter) Pause(ctx context.Context, queueName string) error {
controller, ok := a.driverRuntimeQueueBackend.(QueueController)
if !ok {
return ErrPauseUnsupported
}
return controller.Pause(ctx, queueName)
}
func (a driverRuntimeQueueBackendAdapter) Resume(ctx context.Context, queueName string) error {
controller, ok := a.driverRuntimeQueueBackend.(QueueController)
if !ok {
return ErrPauseUnsupported
}
return controller.Resume(ctx, queueName)
}
func (a driverRuntimeQueueBackendAdapter) Stats(ctx context.Context) (StatsSnapshot, error) {
provider, ok := a.driverRuntimeQueueBackend.(StatsProvider)
if !ok {
return StatsSnapshot{}, fmt.Errorf("stats provider is not available for driver %q", a.Driver())
}
return provider.Stats(ctx)
}
func (a driverRuntimeQueueBackendAdapter) Ready(ctx context.Context) error {
return runtimeReadyCheck(ctx, a.driverRuntimeQueueBackend)
}
func (a driverRuntimeQueueBackendAdapter) ListJobs(ctx context.Context, opts ListJobsOptions) (ListJobsResult, error) {
admin, ok := a.driverRuntimeQueueBackend.(QueueAdmin)
if !ok {
return ListJobsResult{}, ErrQueueAdminUnsupported
}
return admin.ListJobs(ctx, opts)
}
func (a driverRuntimeQueueBackendAdapter) RetryJob(ctx context.Context, queueName, jobID string) error {
admin, ok := a.driverRuntimeQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.RetryJob(ctx, queueName, jobID)
}
func (a driverRuntimeQueueBackendAdapter) CancelJob(ctx context.Context, jobID string) error {
admin, ok := a.driverRuntimeQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.CancelJob(ctx, jobID)
}
func (a driverRuntimeQueueBackendAdapter) DeleteJob(ctx context.Context, queueName, jobID string) error {
admin, ok := a.driverRuntimeQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.DeleteJob(ctx, queueName, jobID)
}
func (a driverRuntimeQueueBackendAdapter) ClearQueue(ctx context.Context, queueName string) error {
admin, ok := a.driverRuntimeQueueBackend.(QueueAdmin)
if !ok {
return ErrQueueAdminUnsupported
}
return admin.ClearQueue(ctx, queueName)
}
func (a driverRuntimeQueueBackendAdapter) History(ctx context.Context, queueName string, window QueueHistoryWindow) ([]QueueHistoryPoint, error) {
admin, ok := a.driverRuntimeQueueBackend.(QueueAdmin)
if !ok {
return nil, ErrQueueAdminUnsupported
}
return admin.History(ctx, queueName, window)
}
func runtimeReadyCheck(ctx context.Context, raw any) error {
if checker, ok := raw.(interface{ Ready(context.Context) error }); ok {
return checker.Ready(ctx)
}
// Backward-compatible bridge for older backend implementations.
if checker, ok := raw.(interface{ Preflight(context.Context) error }); ok {
return checker.Preflight(ctx)
}
return nil
}
func optionalDriverMovedError(driver Driver) error {
switch driver {
case DriverRedis:
return fmt.Errorf("redis driver moved; use github.com/goforj/queue/driver/redisqueue")
case DriverNATS:
return fmt.Errorf("nats driver moved; use github.com/goforj/queue/driver/natsqueue")
case DriverSQS:
return fmt.Errorf("sqs driver moved; use github.com/goforj/queue/driver/sqsqueue")
case DriverRabbitMQ:
return fmt.Errorf("rabbitmq driver moved; use github.com/goforj/queue/driver/rabbitmqqueue")
case DriverDatabase:
return fmt.Errorf("database drivers moved; use github.com/goforj/queue/driver/{mysqlqueue,postgresqueue,sqlitequeue}")
default:
return fmt.Errorf("unsupported queue driver %q", driver)
}
}
func (q *queueCommon) jobFromAny(job any) (Job, error) {
if job, ok := job.(Job); ok {
if job.Type == "" {
return Job{}, fmt.Errorf("dispatch job type is required")
}
return job, nil
}
if job == nil {
return Job{}, fmt.Errorf("dispatch job is nil")
}
jobType := jobTypeFromValue(job)
if jobType == "" {
return Job{}, fmt.Errorf("dispatch job type could not be inferred")
}
if marshaler, ok := job.(interface{ JobType() string }); ok {
if t := marshaler.JobType(); t != "" {
jobType = t
}
}
payload, err := json.Marshal(job)
if err != nil {
return Job{}, fmt.Errorf("marshal dispatch job: %w", err)
}
return NewJob(jobType).Payload(payload).OnQueue(q.cfg.DefaultQueue), nil
}
func jobTypeFromValue(v any) string {
t := reflect.TypeOf(v)
if t == nil {
return ""
}
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Name() == "" {
return ""
}
return t.Name()
}