-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
1545 lines (1405 loc) · 44.5 KB
/
Copy pathqueue.go
File metadata and controls
1545 lines (1405 loc) · 44.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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package queue
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
"sync"
"time"
"github.com/goforj/queue/busruntime"
)
type queueRuntime interface {
// Driver returns the active queue driver.
// @group Driver Integration
Driver() Driver
// WithContext returns a derived queue runtime handle bound to ctx.
// @group Driver Integration
WithContext(ctx context.Context) queueRuntime
// Dispatch submits a typed job payload using the default queue.
// @group Driver Integration
Dispatch(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
// physicalQueueNameOrDefault resolves the effective backend queue name used in canonical events.
physicalQueueNameOrDefault(queueName string) string
// setHandlerContextDecorator decorates handler execution context at registration time.
setHandlerContextDecorator(func(context.Context) context.Context)
}
// 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 is a compatibility attachment path for queue lifecycle events.
// Deprecated: use WithObserver so all event layers share one constructor option.
Observer Observer
Logger Logger
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
DrainWorkers(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()
cfg.Observer = ensureObserverSink(cfg.Observer)
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,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: make(map[string]Handler),
continuation: busruntime.NewContinuationScope(),
},
}, nil
}
return &externalQueueRuntime{
common: common,
externalQueueRuntimeState: &externalQueueRuntimeState{
registered: make(map[string]Handler),
continuation: busruntime.NewContinuationScope(),
},
}, nil
}
func (cfg Config) normalize() Config {
if cfg.DefaultQueue == "" {
cfg.DefaultQueue = "default"
}
return cfg
}
type queueCommon struct {
inner queueBackend
cfg Config
driver Driver
ctx context.Context
handlerContextDecorator func(context.Context) context.Context
}
type nativeQueueRuntime struct {
common *queueCommon
runtime runtimeQueueBackend
*nativeQueueRuntimeState
}
// nativeQueueRuntimeState stays shared by context-bound handles because worker registration and lifecycle belong to the runtime, not an individual dispatch context.
type nativeQueueRuntimeState struct {
mu sync.Mutex
registered map[string]Handler
handlerSlots map[string]*runtimeHandlerSlot
runtimeRegistrations map[string]struct{}
started bool
draining bool
closed bool
start *runtimeStartAttempt
shutdown *runtimeShutdownAttempt
operations runtimeOperationState
continuation *busruntime.ContinuationScope
workers int
}
type externalQueueRuntime struct {
common *queueCommon
newWorker driverWorkerFactory
*externalQueueRuntimeState
}
// externalQueueRuntimeState keeps the constructed worker and lifecycle state synchronized across derived queue handles.
type externalQueueRuntimeState struct {
mu sync.Mutex
registered map[string]Handler
handlerSlots map[string]*runtimeHandlerSlot
worker runtimeWorkerBackend
workerRegistrations map[string]struct{}
started bool
draining bool
closed bool
start *runtimeStartAttempt
shutdown *runtimeShutdownAttempt
operations runtimeOperationState
continuation *busruntime.ContinuationScope
workers int
}
type runtimeOperationState struct {
active int
idle chan struct{}
}
// acquire reserves backend resources while the owning lifecycle mutex is held.
func (s *runtimeOperationState) acquire() {
if s.active == 0 {
s.idle = make(chan struct{})
}
s.active++
}
// release returns true when the final operation completed and an idle waiter should be released.
func (s *runtimeOperationState) release() bool {
s.active--
return s.active == 0 && s.idle != nil
}
// markIdle closes the current idle generation after release identifies the final operation.
func (s *runtimeOperationState) markIdle() {
close(s.idle)
s.idle = nil
}
type runtimeShutdownAttempt struct {
done chan struct{}
err error
}
type runtimeStartAttempt struct {
done chan struct{}
err error
}
type runtimeHandlerSlot struct {
mu sync.RWMutex
handler Handler
}
// replace changes the application handler behind one stable backend registration.
func (s *runtimeHandlerSlot) replace(handler Handler) {
s.mu.Lock()
s.handler = handler
s.mu.Unlock()
}
// invoke resolves the latest handler without holding the slot lock during application execution.
func (s *runtimeHandlerSlot) invoke(ctx context.Context, job Job) error {
s.mu.RLock()
handler := s.handler
s.mu.RUnlock()
return handler(ctx, job)
}
// updateRuntimeHandlerSlot creates or updates the stable target used for one non-nil job registration.
func updateRuntimeHandlerSlot(slots map[string]*runtimeHandlerSlot, jobType string, handler Handler) (map[string]*runtimeHandlerSlot, *runtimeHandlerSlot) {
if handler == nil {
return slots, nil
}
if slots == nil {
slots = make(map[string]*runtimeHandlerSlot)
}
slot := slots[jobType]
if slot == nil {
slot = &runtimeHandlerSlot{}
slots[jobType] = slot
}
slot.replace(handler)
return slots, slot
}
// installRuntimeHandler installs one stable trampoline per non-nil job type on a backend.
func installRuntimeHandler(backend interface{ Register(string, Handler) }, common *queueCommon, registrations map[string]struct{}, jobType string, handler Handler, slot *runtimeHandlerSlot) map[string]struct{} {
if handler == nil {
backend.Register(jobType, nil)
return registrations
}
if _, installed := registrations[jobType]; installed {
return registrations
}
backend.Register(jobType, common.wrapRegisteredHandler(jobType, slot.invoke))
if registrations == nil {
registrations = make(map[string]struct{})
}
registrations[jobType] = struct{}{}
return registrations
}
type runtimeWorkerBackend interface {
Register(jobType string, handler Handler)
StartWorkers(ctx context.Context) error
Shutdown(ctx context.Context) error
}
type runtimeWorkerContextDecoratorSetter interface {
SetHandlerContextDecorator(func(context.Context) context.Context)
}
func (q *queueCommon) Driver() Driver {
return q.driver
}
func (q *queueCommon) context() context.Context {
if q == nil || q.ctx == nil {
return context.Background()
}
return q.ctx
}
// addObserver composes observers at construction time so queue and workflow layers publish to the same application sink.
func (q *queueCommon) addObserver(observer Observer) {
if q == nil || observer == nil {
return
}
q.cfg.Observer = addObserverToSink(q.cfg.Observer, observer)
if observed, ok := q.inner.(*observedQueue); ok {
observed.observer = q.cfg.Observer
return
}
q.inner = newObservedQueue(q.inner, q.driver, q.cfg.Observer)
}
// observer returns the composed application observer shared by execution and workflow adapters.
func (q *queueCommon) observer() Observer {
if q == nil || !observerHasRecipients(q.cfg.Observer) {
return nil
}
return q.cfg.Observer
}
func (q *queueCommon) WithContext(ctx context.Context) *queueCommon {
if q == nil {
return nil
}
clone := *q
clone.ctx = ctx
return &clone
}
func (q *queueCommon) setHandlerContextDecorator(fn func(context.Context) context.Context) {
if q == nil {
return
}
q.handlerContextDecorator = fn
}
func (q *queueCommon) Dispatch(job any) error {
dispatchJob, err := q.jobFromAny(job)
if err != nil {
return err
}
dispatchJob = q.physicalJob(dispatchJob)
ctx, _ := newDispatchAcceptance(q.context())
return q.inner.Dispatch(ctx, dispatchJob)
}
// physicalJob namespaces explicit targets while preserving the current
// backend-specific contract for jobs that omit a queue.
func (q *queueCommon) physicalJob(job Job) Job {
if job.options.queueName == "" {
return job
}
job.options.queueName = q.physicalQueueName(job.options.queueName)
return job
}
func (q *queueCommon) physicalQueueName(queueName string) string {
if q == nil {
return PhysicalQueueName("", queueName)
}
return PhysicalQueueName(q.cfg.DefaultQueue, queueName)
}
// physicalQueueNameOrDefault resolves the configured default and namespace before a queue name reaches the backend.
func (q *queueCommon) physicalQueueNameOrDefault(queueName string) string {
queueName = strings.TrimSpace(queueName)
if queueName == "" && q != nil {
queueName = q.cfg.DefaultQueue
}
return q.physicalQueueName(queueName)
}
// PhysicalQueueName maps a logical queue name into the physical name used by the backing queue driver.
func PhysicalQueueName(defaultQueue string, queueName string) string {
defaultQueue = strings.TrimSpace(defaultQueue)
queueName = strings.TrimSpace(queueName)
if queueName == "" {
return defaultQueue
}
prefix := queueNamePrefix(defaultQueue)
if prefix == "" {
return queueName
}
if strings.HasPrefix(queueName, prefix) {
return queueName
}
return prefix + queueName
}
// PhysicalQueueWeights maps logical weighted queue names into their physical backend names.
func PhysicalQueueWeights(defaultQueue string, weights map[string]int) map[string]int {
if len(weights) == 0 {
return weights
}
out := make(map[string]int, len(weights))
for queueName, weight := range weights {
out[PhysicalQueueName(defaultQueue, queueName)] = weight
}
return out
}
func queueNamePrefix(defaultQueue string) string {
defaultQueue = strings.TrimSpace(defaultQueue)
const suffix = "_default"
if !strings.HasSuffix(defaultQueue, suffix) {
return ""
}
prefix := strings.TrimSuffix(defaultQueue, suffix)
if prefix == "" {
return ""
}
return prefix + "_"
}
// Driver returns the native runtime's configured backend identifier.
func (q *nativeQueueRuntime) Driver() Driver { return q.common.Driver() }
// physicalQueueNameOrDefault keeps canonical event labels aligned with native backend queue names.
func (q *nativeQueueRuntime) physicalQueueNameOrDefault(queueName string) string {
if q == nil || q.common == nil {
return PhysicalQueueName("default", queueName)
}
return q.common.physicalQueueNameOrDefault(queueName)
}
// Dispatch rejects new application work once native runtime draining begins.
func (q *nativeQueueRuntime) Dispatch(job any) error {
release, err := q.acquireOperation(q.common.context(), true)
if err != nil {
return err
}
defer release()
return q.common.Dispatch(job)
}
func (q *nativeQueueRuntime) WithContext(ctx context.Context) queueRuntime {
if q == nil {
return nil
}
clone := *q
clone.common = q.common.WithContext(ctx)
return &clone
}
// Driver returns the external runtime's configured backend identifier.
func (q *externalQueueRuntime) Driver() Driver { return q.common.Driver() }
// physicalQueueNameOrDefault keeps canonical event labels aligned with external backend queue names.
func (q *externalQueueRuntime) physicalQueueNameOrDefault(queueName string) string {
if q == nil || q.common == nil {
return PhysicalQueueName("default", queueName)
}
return q.common.physicalQueueNameOrDefault(queueName)
}
// Dispatch rejects new application work once external runtime draining begins.
func (q *externalQueueRuntime) Dispatch(job any) error {
release, err := q.acquireOperation(q.common.context(), true)
if err != nil {
return err
}
defer release()
return q.common.Dispatch(job)
}
func (q *externalQueueRuntime) WithContext(ctx context.Context) queueRuntime {
if q == nil {
return nil
}
clone := *q
clone.common = q.common.WithContext(ctx)
return &clone
}
func (q *nativeQueueRuntime) setHandlerContextDecorator(fn func(context.Context) context.Context) {
if q == nil {
return
}
q.common.setHandlerContextDecorator(fn)
}
func (q *externalQueueRuntime) setHandlerContextDecorator(fn func(context.Context) context.Context) {
if q == nil {
return
}
q.common.setHandlerContextDecorator(fn)
}
func (q *nativeQueueRuntime) BusRegister(jobType string, handler busruntime.Handler) {
if handler == nil {
q.Register(jobType, nil)
return
}
scope := q.continuationScope()
q.Register(jobType, func(ctx context.Context, job Job) error {
handlerCtx, release := withBusDeliveryContext(ctx, job, scope)
defer release()
return handler(handlerCtx, job)
})
}
func (q *externalQueueRuntime) BusRegister(jobType string, handler busruntime.Handler) {
if handler == nil {
q.Register(jobType, nil)
return
}
scope := q.continuationScope()
q.Register(jobType, func(ctx context.Context, job Job) error {
handlerCtx, release := withBusDeliveryContext(ctx, job, scope)
defer release()
return handler(handlerCtx, job)
})
}
// withBusDeliveryContext attaches physical attempt and correlation metadata to
// one invocation while keeping both channels out of the application payload.
func withBusDeliveryContext(ctx context.Context, job Job, scope *busruntime.ContinuationScope) (context.Context, func()) {
if ctx == nil {
ctx = context.Background()
}
opts := job.jobOptions()
ctx, release := scope.Permit(ctx)
metadata := DriverMetadata(job)
// Every physical invocation shadows parent metadata so nested legacy or
// low-level jobs cannot inherit correlation from the job that dispatched them.
ctx = busruntime.WithDeliveryMetadata(ctx, metadata)
return busruntime.WithDeliveryAttempt(ctx, busruntime.DeliveryAttempt{
Number: opts.attempt,
MaxRetry: optionInt(opts.maxRetry),
}), release
}
func (q *nativeQueueRuntime) BusDispatch(ctx context.Context, jobType string, payload []byte, opts busruntime.JobOptions) error {
release, err := q.acquireOperation(ctx, true)
if err != nil {
return err
}
defer release()
return q.common.dispatchBusJob(ctx, jobType, payload, opts)
}
func (q *externalQueueRuntime) BusDispatch(ctx context.Context, jobType string, payload []byte, opts busruntime.JobOptions) error {
release, err := q.acquireOperation(ctx, true)
if err != nil {
return err
}
defer release()
return q.common.dispatchBusJob(ctx, jobType, payload, opts)
}
// BusDispatchDirect submits an ordinary application job without a workflow envelope.
func (q *nativeQueueRuntime) BusDispatchDirect(ctx context.Context, jobType string, payload []byte, metadata busruntime.DeliveryMetadata, opts busruntime.JobOptions) error {
release, err := q.acquireOperation(ctx, true)
if err != nil {
return err
}
defer release()
return q.common.dispatchDirectJob(ctx, jobType, payload, metadata, opts)
}
// BusDispatchDirect submits an ordinary application job without a workflow envelope.
func (q *externalQueueRuntime) BusDispatchDirect(ctx context.Context, jobType string, payload []byte, metadata busruntime.DeliveryMetadata, opts busruntime.JobOptions) error {
release, err := q.acquireOperation(ctx, true)
if err != nil {
return err
}
defer release()
return q.common.dispatchDirectJob(ctx, jobType, payload, metadata, opts)
}
// acquireOperation leases native backend resources through one complete operation.
func (q *nativeQueueRuntime) acquireOperation(ctx context.Context, allowContinuation bool) (func(), error) {
q.mu.Lock()
scope := q.continuationScopeLocked()
if q.closed || (q.draining && (!allowContinuation || !scope.Owns(ctx))) {
q.mu.Unlock()
return nil, ErrQueuerShuttingDown
}
q.operations.acquire()
q.mu.Unlock()
return q.releaseOperation, nil
}
// releaseOperation ends one native lease and wakes a waiting shutdown when the backend becomes idle.
func (q *nativeQueueRuntime) releaseOperation() {
q.mu.Lock()
if q.operations.release() {
q.operations.markIdle()
}
q.mu.Unlock()
}
// acquireOperation leases external producer resources through one complete operation.
func (q *externalQueueRuntime) acquireOperation(ctx context.Context, allowContinuation bool) (func(), error) {
q.mu.Lock()
scope := q.continuationScopeLocked()
if q.closed || (q.draining && (!allowContinuation || !scope.Owns(ctx))) {
q.mu.Unlock()
return nil, ErrQueuerShuttingDown
}
q.operations.acquire()
q.mu.Unlock()
return q.releaseOperation, nil
}
// releaseOperation ends one external lease and wakes a waiting shutdown when the producer becomes idle.
func (q *externalQueueRuntime) releaseOperation() {
q.mu.Lock()
if q.operations.release() {
q.operations.markIdle()
}
q.mu.Unlock()
}
// continuationScope returns the native runtime's stable permission owner.
func (q *nativeQueueRuntime) continuationScope() *busruntime.ContinuationScope {
q.mu.Lock()
defer q.mu.Unlock()
return q.continuationScopeLocked()
}
// continuationScopeLocked lazily initializes test-constructed native states while the lifecycle mutex is held.
func (q *nativeQueueRuntime) continuationScopeLocked() *busruntime.ContinuationScope {
if q.continuation == nil {
q.continuation = busruntime.NewContinuationScope()
}
return q.continuation
}
// continuationScope returns the external runtime's stable permission owner.
func (q *externalQueueRuntime) continuationScope() *busruntime.ContinuationScope {
q.mu.Lock()
defer q.mu.Unlock()
return q.continuationScopeLocked()
}
// continuationScopeLocked lazily initializes test-constructed external states while the lifecycle mutex is held.
func (q *externalQueueRuntime) continuationScopeLocked() *busruntime.ContinuationScope {
if q.continuation == nil {
q.continuation = busruntime.NewContinuationScope()
}
return q.continuation
}
// Register linearizes logical and physical state so an activating backend cannot consume a newly registered type without its handler.
func (q *nativeQueueRuntime) Register(jobType string, handler Handler) {
if jobType == "" || handler == nil {
return
}
q.mu.Lock()
defer q.mu.Unlock()
if q.registered == nil {
q.registered = make(map[string]Handler)
}
q.registered[jobType] = handler
var slot *runtimeHandlerSlot
q.handlerSlots, slot = updateRuntimeHandlerSlot(q.handlerSlots, jobType, handler)
if !q.draining && (q.start != nil || q.started) {
q.runtimeRegistrations = installRuntimeHandler(q.runtime, q.common, q.runtimeRegistrations, jobType, handler, slot)
}
}
// Register linearizes logical and physical state once the external worker generation has been published for activation.
func (q *externalQueueRuntime) Register(jobType string, handler Handler) {
if jobType == "" || handler == nil {
return
}
q.mu.Lock()
defer q.mu.Unlock()
if q.registered == nil {
q.registered = make(map[string]Handler)
}
q.registered[jobType] = handler
var slot *runtimeHandlerSlot
q.handlerSlots, slot = updateRuntimeHandlerSlot(q.handlerSlots, jobType, handler)
if !q.draining && q.worker != nil && (q.start != nil || q.started) {
q.workerRegistrations = installRuntimeHandler(q.worker, q.common, q.workerRegistrationsLocked(), jobType, handler, slot)
}
}
// workerRegistrationsLocked returns the handler types already installed on the retained external worker.
func (q *externalQueueRuntime) workerRegistrationsLocked() map[string]struct{} {
if q.workerRegistrations == nil {
q.workerRegistrations = make(map[string]struct{})
}
return q.workerRegistrations
}
// StartWorkers installs the current handler generation before activating the backend and serializes concurrent lifecycle calls.
func (q *nativeQueueRuntime) StartWorkers(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
if q.closed || q.draining {
q.mu.Unlock()
return ErrQueuerShuttingDown
}
if q.started {
q.mu.Unlock()
return nil
}
if q.start != nil {
attempt := q.start
q.mu.Unlock()
return waitForRuntimeStart(ctx, attempt)
}
attempt := &runtimeStartAttempt{done: make(chan struct{})}
q.start = attempt
for jobType, handler := range q.registered {
var slot *runtimeHandlerSlot
q.handlerSlots, slot = updateRuntimeHandlerSlot(q.handlerSlots, jobType, handler)
q.runtimeRegistrations = installRuntimeHandler(q.runtime, q.common, q.runtimeRegistrations, jobType, handler, slot)
}
q.mu.Unlock()
err := q.runtime.StartWorkers(ctx)
q.mu.Lock()
if err == nil {
q.started = true
}
attempt.err = err
q.start = nil
close(attempt.done)
q.mu.Unlock()
return err
}
// StartWorkers publishes and catches up a worker before activation so registrations cannot complete against a stale startup snapshot.
func (q *externalQueueRuntime) StartWorkers(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
if q.closed || q.draining {
q.mu.Unlock()
return ErrQueuerShuttingDown
}
if q.started {
q.mu.Unlock()
return nil
}
if q.start != nil {
attempt := q.start
q.mu.Unlock()
return waitForRuntimeStart(ctx, attempt)
}
attempt := &runtimeStartAttempt{done: make(chan struct{})}
q.start = attempt
w := q.worker
workers := q.workers
q.mu.Unlock()
var err error
if w == nil {
if q.newWorker != nil {
driverWorker, e := q.newWorker(defaultWorkerCount(workers))
if e != nil {
err = e
} else {
w = driverWorkerBackendAdapter{driverWorker}
}
} else {
w, err = newExternalWorker(q.common.cfg, workers)
}
}
if err == nil {
q.mu.Lock()
q.worker = w
if setter, ok := w.(runtimeWorkerContextDecoratorSetter); ok {
setter.SetHandlerContextDecorator(q.common.handlerContextDecorator)
}
for jobType, handler := range q.registered {
var slot *runtimeHandlerSlot
q.handlerSlots, slot = updateRuntimeHandlerSlot(q.handlerSlots, jobType, handler)
q.workerRegistrations = installRuntimeHandler(w, q.common, q.workerRegistrationsLocked(), jobType, handler, slot)
}
q.mu.Unlock()
err = w.StartWorkers(ctx)
}
q.mu.Lock()
if w != nil {
// A partially started worker remains owned so Shutdown can finish cleanup instead of leaking factory resources.
q.worker = w
}
if err == nil {
q.started = true
}
attempt.err = err
q.start = nil
close(attempt.done)
q.mu.Unlock()
return err
}
func (q *nativeQueueRuntime) Workers(count int) queueRuntime {
q.mu.Lock()
defer q.mu.Unlock()
if !q.started && !q.draining && !q.closed && q.start == nil && count > 0 {
q.workers = count
if setter, ok := q.runtime.(interface{ setWorkers(int) }); ok {
setter.setWorkers(count)
}
}
return q
}
func (q *externalQueueRuntime) Workers(count int) queueRuntime {
q.mu.Lock()
defer q.mu.Unlock()
if !q.started && !q.draining && !q.closed && q.start == nil && count > 0 {
q.workers = count
}
return q
}
// Shutdown retains native runtime state until cleanup succeeds so timed-out drains remain retryable.
func (q *nativeQueueRuntime) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
if q.start != nil {
q.draining = true
attempt := q.start
q.mu.Unlock()
if err := waitForRuntimeStartCompletion(ctx, attempt); err != nil {
return err
}
return q.Shutdown(ctx)
}
if q.shutdown != nil {
attempt := q.shutdown
q.mu.Unlock()
return waitForRuntimeShutdown(ctx, attempt)
}
if q.closed {
q.mu.Unlock()
return nil
}
q.draining = true
attempt := &runtimeShutdownAttempt{done: make(chan struct{})}
q.shutdown = attempt
idle := q.operations.idle
q.mu.Unlock()
err := waitForRuntimeOperations(ctx, idle)
if err == nil {
err = q.runtime.DrainWorkers(ctx)
}
if err == nil {
// Worker drain expires every handler-issued continuation permit. A second
// operation snapshot is therefore stable and must finish before resources close.
q.mu.Lock()
idle = q.operations.idle
q.mu.Unlock()
err = waitForRuntimeOperations(ctx, idle)
}
if err == nil {
err = q.common.inner.Shutdown(ctx)
}
q.mu.Lock()
attempt.err = err
q.shutdown = nil
if err == nil {
q.started = false
q.draining = false
q.closed = true
}
close(attempt.done)
q.mu.Unlock()
return err
}
// Shutdown drains the worker before producer resources and retains both until every cleanup succeeds.
func (q *externalQueueRuntime) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
q.mu.Lock()
if q.start != nil {
q.draining = true
attempt := q.start
q.mu.Unlock()
if err := waitForRuntimeStartCompletion(ctx, attempt); err != nil {
return err
}
return q.Shutdown(ctx)
}
if q.shutdown != nil {
attempt := q.shutdown
q.mu.Unlock()
return waitForRuntimeShutdown(ctx, attempt)
}
if q.closed {
q.mu.Unlock()
return nil
}
w := q.worker
q.draining = true
attempt := &runtimeShutdownAttempt{done: make(chan struct{})}
q.shutdown = attempt
idle := q.operations.idle
q.mu.Unlock()
err := waitForRuntimeOperations(ctx, idle)
if w != nil {
if err == nil {
err = w.Shutdown(ctx)
}
if err == nil {
q.mu.Lock()
q.worker = nil
q.workerRegistrations = nil
q.started = false
q.mu.Unlock()
}
}
if err == nil {
// A handler may admit a descendant after the initial snapshot. Once worker drain returns, its scoped permit has expired, so this generation is stable.
q.mu.Lock()
idle = q.operations.idle
q.mu.Unlock()
err = waitForRuntimeOperations(ctx, idle)
}
if err == nil {
err = q.common.inner.Shutdown(ctx)
}
q.mu.Lock()
attempt.err = err
q.shutdown = nil
if err == nil {
q.draining = false
q.closed = true
}
close(attempt.done)
q.mu.Unlock()
return err
}
// waitForRuntimeOperations prevents resource cleanup from overtaking an operation that already passed the lifecycle gate.
func waitForRuntimeOperations(ctx context.Context, idle <-chan struct{}) error {
if idle == nil {
return nil