-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_runtime_unit_test.go
More file actions
1960 lines (1844 loc) · 69.8 KB
/
Copy pathqueue_runtime_unit_test.go
File metadata and controls
1960 lines (1844 loc) · 69.8 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"
"errors"
"sync"
"testing"
"time"
"github.com/goforj/queue/busruntime"
)
type runtimeBackendStub struct {
registered map[string]Handler
startCalls int
drainCalls int
stopCalls int
startErr error
stopErr error
dispatchEntered chan struct{}
releaseDispatch chan struct{}
dispatchOnce sync.Once
}
type blockingRuntimeBackendStub struct {
runtimeBackendStub
startEntered chan struct{}
releaseStart chan struct{}
startOnce sync.Once
}
type blockingStrictRegistrationRuntimeBackendStub struct {
strictRegistrationRuntimeBackendStub
startEntered chan struct{}
releaseStart chan struct{}
startOnce sync.Once
}
type blockingReadyRuntimeBackendStub struct {
runtimeBackendStub
readyEntered chan struct{}
releaseReady chan struct{}
readyOnce sync.Once
readyCalls int
}
type blockingShutdownRuntimeBackendStub struct {
runtimeBackendStub
shutdownEntered chan struct{}
releaseShutdown chan struct{}
shutdownOnce sync.Once
}
type phasedShutdownRuntimeBackendStub struct {
runtimeBackendStub
drainEntered chan struct{}
releaseDrain chan struct{}
drainOnce sync.Once
}
type strictRegistrationRuntimeBackendStub struct {
runtimeBackendStub
registrations map[string]int
}
// Register panics when one worker receives the same pattern twice, matching Asynq ServeMux behavior.
func (s *strictRegistrationRuntimeBackendStub) Register(jobType string, handler Handler) {
if s.registrations == nil {
s.registrations = make(map[string]int)
}
s.registrations[jobType]++
if s.registrations[jobType] > 1 {
panic("duplicate worker registration: " + jobType)
}
s.runtimeBackendStub.Register(jobType, handler)
}
// StartWorkers rejects a canceled attempt before accepting a later live retry.
func (s *strictRegistrationRuntimeBackendStub) StartWorkers(ctx context.Context) error {
s.startCalls++
return ctx.Err()
}
// Shutdown exposes the worker-drained boundary while deliberately ignoring cancellation like a backend cleanup that already committed.
func (s *blockingShutdownRuntimeBackendStub) Shutdown(context.Context) error {
s.stopCalls++
s.shutdownOnce.Do(func() { close(s.shutdownEntered) })
<-s.releaseShutdown
return s.stopErr
}
// DrainWorkers exposes the pre-resource-close boundary of a native shutdown.
func (s *phasedShutdownRuntimeBackendStub) DrainWorkers(context.Context) error {
s.drainOnce.Do(func() { close(s.drainEntered) })
<-s.releaseDrain
return nil
}
// Ready exposes a deterministic producer-resource boundary for shutdown lease tests.
func (s *blockingReadyRuntimeBackendStub) Ready(ctx context.Context) error {
s.readyCalls++
s.readyOnce.Do(func() { close(s.readyEntered) })
select {
case <-s.releaseReady:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// StartWorkers exposes a deterministic startup boundary for lifecycle race tests.
func (s *blockingRuntimeBackendStub) StartWorkers(context.Context) error {
s.startCalls++
s.startOnce.Do(func() { close(s.startEntered) })
<-s.releaseStart
return s.startErr
}
// StartWorkers exposes the live-start boundary while retaining strict registration counts across retries.
func (s *blockingStrictRegistrationRuntimeBackendStub) StartWorkers(context.Context) error {
s.startCalls++
s.startOnce.Do(func() { close(s.startEntered) })
<-s.releaseStart
return s.startErr
}
// waitForRuntimeDraining waits until a shutdown goroutine has crossed the lifecycle gate.
func waitForRuntimeDraining(t *testing.T, draining func() bool) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for !draining() {
if time.Now().After(deadline) {
t.Fatal("timed out waiting for runtime to begin draining")
}
time.Sleep(time.Millisecond)
}
}
func (s *runtimeBackendStub) Driver() Driver { return DriverSync }
func (s *runtimeBackendStub) Dispatch(context.Context, Job) error {
if s.dispatchEntered != nil {
s.dispatchOnce.Do(func() { close(s.dispatchEntered) })
<-s.releaseDispatch
}
return nil
}
func (s *runtimeBackendStub) Register(jobType string, handler Handler) {
if s.registered == nil {
s.registered = make(map[string]Handler)
}
s.registered[jobType] = handler
}
func (s *runtimeBackendStub) StartWorkers(context.Context) error {
s.startCalls++
return s.startErr
}
// DrainWorkers completes the stub's distinct worker-drain lifecycle phase.
func (s *runtimeBackendStub) DrainWorkers(context.Context) error {
s.drainCalls++
return nil
}
func (s *runtimeBackendStub) Shutdown(context.Context) error {
s.stopCalls++
return s.stopErr
}
type queueBackendRecorder struct {
dispatched []Job
shutdowns int
shutdownErr error
dispatchEntered chan struct{}
releaseDispatch chan struct{}
dispatchOnce sync.Once
}
func (q *queueBackendRecorder) Driver() Driver { return DriverNull }
func (q *queueBackendRecorder) Dispatch(_ context.Context, job Job) error {
q.dispatched = append(q.dispatched, job)
if q.dispatchEntered != nil {
q.dispatchOnce.Do(func() { close(q.dispatchEntered) })
<-q.releaseDispatch
}
return nil
}
func (q *queueBackendRecorder) Shutdown(context.Context) error {
q.shutdowns++
return q.shutdownErr
}
type driverQueueBackendStub struct {
driver Driver
dispatched []Job
shutdowns int
pauseErr error
resumeErr error
stats StatsSnapshot
statsErr error
lastQueueArg string
}
func (s *driverQueueBackendStub) Driver() Driver { return s.driver }
func (s *driverQueueBackendStub) Dispatch(_ context.Context, job Job) error {
s.dispatched = append(s.dispatched, job)
return nil
}
func (s *driverQueueBackendStub) Shutdown(context.Context) error {
s.shutdowns++
return nil
}
func (s *driverQueueBackendStub) Pause(_ context.Context, queueName string) error {
s.lastQueueArg = queueName
return s.pauseErr
}
func (s *driverQueueBackendStub) Resume(_ context.Context, queueName string) error {
s.lastQueueArg = queueName
return s.resumeErr
}
func (s *driverQueueBackendStub) Stats(context.Context) (StatsSnapshot, error) {
return s.stats, s.statsErr
}
type driverRuntimeBackendStub struct {
*driverQueueBackendStub
registered map[string]Handler
startErr error
startCalls int
}
func (s *driverRuntimeBackendStub) Register(jobType string, h Handler) {
if s.registered == nil {
s.registered = map[string]Handler{}
}
s.registered[jobType] = h
}
func (s *driverRuntimeBackendStub) StartWorkers(context.Context) error {
s.startCalls++
return s.startErr
}
// DrainWorkers completes the driver stub's distinct worker-drain phase.
func (s *driverRuntimeBackendStub) DrainWorkers(context.Context) error {
return nil
}
func TestQueueCommon_JobFromAnyAndHelpers(t *testing.T) {
common := &queueCommon{cfg: Config{DefaultQueue: "default"}}
if _, err := common.jobFromAny(nil); err == nil {
t.Fatal("expected nil job error")
}
if _, err := common.jobFromAny(NewJob("")); err == nil {
t.Fatal("expected empty job type error")
}
if _, err := common.jobFromAny(NewJob("deferred:validation").Retry(-1)); err != nil {
t.Fatalf("jobFromAny changed backend validation timing: %v", err)
}
if _, err := common.jobFromAny(struct{ F func() }{}); err == nil {
t.Fatal("expected marshal error for func field")
}
type namedJob struct{}
if got := jobTypeFromValue(namedJob{}); got != "namedJob" {
t.Fatalf("expected inferred type namedJob, got %q", got)
}
if got := jobTypeFromValue(&namedJob{}); got != "namedJob" {
t.Fatalf("expected inferred pointer type namedJob, got %q", got)
}
if got := jobTypeFromValue(map[string]any{}); got != "" {
t.Fatalf("expected anonymous type to return empty, got %q", got)
}
}
func TestQueueCommonDispatchAndNativeRuntimeWrappers(t *testing.T) {
inner := &queueBackendRecorder{}
worker := &runtimeBackendStub{}
common := &queueCommon{inner: inner, cfg: Config{DefaultQueue: "default"}, driver: DriverSync}
q := &nativeQueueRuntime{
common: common,
runtime: worker,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
if q.Driver() != DriverSync {
t.Fatalf("expected driver sync, got %q", q.Driver())
}
type emailJob struct{ ID int }
if err := q.Dispatch(emailJob{ID: 1}); err != nil {
t.Fatalf("dispatch wrapper failed: %v", err)
}
if len(inner.dispatched) != 1 || inner.dispatched[0].Type != "emailJob" {
t.Fatalf("expected one inferred job dispatch, got %+v", inner.dispatched)
}
q.Register("job:one", func(context.Context, Job) error { return nil })
if err := q.StartWorkers(nil); err != nil {
t.Fatalf("start workers failed: %v", err)
}
if worker.startCalls != 1 {
t.Fatalf("expected start called once, got %d", worker.startCalls)
}
if _, ok := worker.registered["job:one"]; !ok {
t.Fatal("expected registered handler to be forwarded on start")
}
q.Register("job:two", func(context.Context, Job) error { return nil })
if _, ok := worker.registered["job:two"]; !ok {
t.Fatal("expected register after start to forward immediately")
}
if err := q.Shutdown(nil); err != nil {
t.Fatalf("shutdown failed: %v", err)
}
if worker.drainCalls != 1 || worker.stopCalls != 0 || inner.shutdowns != 1 {
t.Fatalf("native drain/runtime close/inner close calls = %d/%d/%d, want 1/0/1", worker.drainCalls, worker.stopCalls, inner.shutdowns)
}
}
func TestRuntimeWithContextSharesLifecycleState(t *testing.T) {
native := &nativeQueueRuntime{
common: &queueCommon{cfg: Config{DefaultQueue: "default"}},
runtime: &runtimeBackendStub{},
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
nativeDerived, ok := native.WithContext(context.Background()).(*nativeQueueRuntime)
if !ok {
t.Fatal("expected a derived native runtime")
}
if nativeDerived.nativeQueueRuntimeState != native.nativeQueueRuntimeState {
t.Fatal("derived native runtime does not share lifecycle state")
}
nativeDerived.Workers(3)
if native.workers != 3 {
t.Fatalf("native worker count = %d, want shared value 3", native.workers)
}
external := &externalQueueRuntime{
common: &queueCommon{cfg: Config{DefaultQueue: "default"}},
externalQueueRuntimeState: &externalQueueRuntimeState{
registered: map[string]Handler{},
},
}
externalDerived, ok := external.WithContext(context.Background()).(*externalQueueRuntime)
if !ok {
t.Fatal("expected a derived external runtime")
}
if externalDerived.externalQueueRuntimeState != external.externalQueueRuntimeState {
t.Fatal("derived external runtime does not share lifecycle state")
}
externalDerived.Workers(5)
if external.workers != 5 {
t.Fatalf("external worker count = %d, want shared value 5", external.workers)
}
}
// TestRuntimeEventQueueResolvers verifies every runtime shape exposes the same
// namespace mapping without requiring a live backend.
func TestRuntimeEventQueueResolvers(t *testing.T) {
common := &queueCommon{cfg: Config{DefaultQueue: "billing_default"}}
if got := common.physicalQueueNameOrDefault(""); got != "billing_default" {
t.Fatalf("common default queue = %q, want billing_default", got)
}
if got := common.physicalQueueNameOrDefault("critical"); got != "billing_critical" {
t.Fatalf("common explicit queue = %q, want billing_critical", got)
}
native := &nativeQueueRuntime{common: common}
if got := native.physicalQueueNameOrDefault("critical"); got != "billing_critical" {
t.Fatalf("native explicit queue = %q, want billing_critical", got)
}
if got := (*nativeQueueRuntime)(nil).physicalQueueNameOrDefault(""); got != "default" {
t.Fatalf("nil native default queue = %q, want default", got)
}
external := &externalQueueRuntime{common: common}
if got := external.physicalQueueNameOrDefault("critical"); got != "billing_critical" {
t.Fatalf("external explicit queue = %q, want billing_critical", got)
}
if got := (*externalQueueRuntime)(nil).physicalQueueNameOrDefault(""); got != "default" {
t.Fatalf("nil external default queue = %q, want default", got)
}
fake := NewFake()
if got := fake.physicalQueueNameOrDefault(""); got != "default" {
t.Fatalf("fake default queue = %q, want default", got)
}
if got := fake.physicalQueueNameOrDefault("critical"); got != "critical" {
t.Fatalf("fake explicit queue = %q, want critical", got)
}
if got := (*FakeQueue)(nil).physicalQueueNameOrDefault(""); got != "default" {
t.Fatalf("nil fake default queue = %q, want default", got)
}
}
func TestPhysicalQueueNameInfersTargetPrefixFromDefaultQueue(t *testing.T) {
tests := []struct {
defaultQueue string
queueName string
want string
}{
{defaultQueue: "default", queueName: "default", want: "default"},
{defaultQueue: "default", queueName: "reports", want: "reports"},
{defaultQueue: "billing_default", queueName: "default", want: "billing_default"},
{defaultQueue: "billing_default", queueName: "reports", want: "billing_reports"},
{defaultQueue: "billing_default", queueName: "billing_reports", want: "billing_reports"},
{defaultQueue: "critical", queueName: "reports", want: "reports"},
{defaultQueue: "billing_default", queueName: "", want: "billing_default"},
}
for _, tc := range tests {
if got := PhysicalQueueName(tc.defaultQueue, tc.queueName); got != tc.want {
t.Fatalf("PhysicalQueueName(%q, %q) = %q, want %q", tc.defaultQueue, tc.queueName, got, tc.want)
}
}
}
func TestQueueCommonDispatchPhysicalizesTargetQueues(t *testing.T) {
inner := &queueBackendRecorder{}
q := &nativeQueueRuntime{
common: &queueCommon{inner: inner, cfg: Config{DefaultQueue: "billing_default"}, driver: DriverSync},
runtime: &runtimeBackendStub{},
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
if err := q.Dispatch(NewJob("job:explicit").OnQueue("reports")); err != nil {
t.Fatalf("dispatch explicit queue: %v", err)
}
type inferredJob struct{ ID int }
if err := q.Dispatch(inferredJob{ID: 7}); err != nil {
t.Fatalf("dispatch inferred job: %v", err)
}
if len(inner.dispatched) != 2 {
t.Fatalf("expected 2 dispatched jobs, got %d", len(inner.dispatched))
}
if got := inner.dispatched[0].jobOptions().queueName; got != "billing_reports" {
t.Fatalf("expected explicit queue billing_reports, got %q", got)
}
if got := inner.dispatched[1].jobOptions().queueName; got != "billing_default" {
t.Fatalf("expected default queue billing_default, got %q", got)
}
}
func TestExternalQueueRuntimeRegisterShutdownAndWorkers(t *testing.T) {
inner := &queueBackendRecorder{}
worker := &runtimeBackendStub{}
common := &queueCommon{inner: inner, cfg: Config{DefaultQueue: "default"}, driver: DriverNATS}
q := &externalQueueRuntime{
common: common,
externalQueueRuntimeState: &externalQueueRuntimeState{
registered: map[string]Handler{},
worker: worker,
started: true,
},
}
q.Workers(3)
if q.workers != 0 {
t.Fatalf("expected workers unchanged when started, got %d", q.workers)
}
q.started = false
q.Workers(3)
if q.workers != 3 {
t.Fatalf("expected workers=3 before start, got %d", q.workers)
}
q.started = true
q.Register("job:external", func(context.Context, Job) error { return nil })
if q.Driver() != DriverNATS {
t.Fatalf("expected external driver nats, got %q", q.Driver())
}
if _, ok := worker.registered["job:external"]; !ok {
t.Fatal("expected register to forward to started external worker")
}
if err := q.Dispatch(NewJob("job:external").OnQueue("default")); err != nil {
t.Fatalf("dispatch wrapper failed: %v", err)
}
if err := q.Dispatch(NewJob("job:external").OnQueue("default")); err != nil {
t.Fatalf("dispatch ctx failed: %v", err)
}
if err := q.Shutdown(nil); err != nil {
t.Fatalf("shutdown failed: %v", err)
}
if worker.stopCalls != 1 {
t.Fatalf("expected worker shutdown once, got %d", worker.stopCalls)
}
if inner.shutdowns != 1 {
t.Fatalf("expected inner shutdown once, got %d", inner.shutdowns)
}
}
// TestRuntimeSameKeyReplacementDuringBlockedStart verifies a completed registration remains current while startup is in flight.
func TestRuntimeSameKeyReplacementDuringBlockedStart(t *testing.T) {
for _, external := range []bool{false, true} {
name := "native"
if external {
name = "external"
}
t.Run(name, func(t *testing.T) {
worker := &blockingStrictRegistrationRuntimeBackendStub{
startEntered: make(chan struct{}),
releaseStart: make(chan struct{}),
}
var runtime queueRuntime
if external {
runtime = &externalQueueRuntime{
common: &queueCommon{inner: &queueBackendRecorder{}, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
newWorker: func(int) (driverWorkerBackend, error) {
return worker, nil
},
externalQueueRuntimeState: &externalQueueRuntimeState{registered: map[string]Handler{}},
}
} else {
runtime = &nativeQueueRuntime{
common: &queueCommon{inner: worker, cfg: Config{DefaultQueue: "default"}, driver: DriverSync},
runtime: worker,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
}
var firstCalls, secondCalls int
runtime.Register("job:replace", func(context.Context, Job) error {
firstCalls++
return nil
})
startResult := make(chan error, 1)
go func() { startResult <- runtime.StartWorkers(context.Background()) }()
<-worker.startEntered
runtime.Register("job:replace", func(context.Context, Job) error {
secondCalls++
return nil
})
close(worker.releaseStart)
if err := <-startResult; err != nil {
t.Fatalf("start workers: %v", err)
}
handler := worker.registered["job:replace"]
if handler == nil {
t.Fatal("worker did not receive replacement slot")
}
if err := handler(context.Background(), NewJob("job:replace")); err != nil {
t.Fatalf("invoke replacement: %v", err)
}
if firstCalls != 0 || secondCalls != 1 {
t.Fatalf("replacement calls = first:%d second:%d, want 0/1", firstCalls, secondCalls)
}
if err := runtime.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown: %v", err)
}
})
}
}
// TestRuntimeNewRegistrationIsLiveDuringBlockedStart verifies Register cannot complete while a consuming backend still lacks the new type.
func TestRuntimeNewRegistrationIsLiveDuringBlockedStart(t *testing.T) {
startErr := errors.New("worker start failed")
tests := []struct {
name string
external bool
startFails bool
}{
{name: "native_success"},
{name: "native_failed_start_retry", startFails: true},
{name: "external_success", external: true},
{name: "external_failed_start_retry", external: true, startFails: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
worker := &blockingStrictRegistrationRuntimeBackendStub{
startEntered: make(chan struct{}),
releaseStart: make(chan struct{}),
}
if test.startFails {
worker.startErr = startErr
}
var runtime queueRuntime
if test.external {
runtime = &externalQueueRuntime{
common: &queueCommon{inner: &queueBackendRecorder{}, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
newWorker: func(int) (driverWorkerBackend, error) {
return worker, nil
},
externalQueueRuntimeState: &externalQueueRuntimeState{registered: map[string]Handler{}},
}
} else {
runtime = &nativeQueueRuntime{
common: &queueCommon{inner: worker, cfg: Config{DefaultQueue: "default"}, driver: DriverSync},
runtime: worker,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
}
startResult := make(chan error, 1)
go func() { startResult <- runtime.StartWorkers(context.Background()) }()
<-worker.startEntered
var firstCalls, replacementCalls int
registrationRuntime := runtime.WithContext(context.Background())
registrationRuntime.Register("job:late", func(context.Context, Job) error {
firstCalls++
return nil
})
handler := worker.registered["job:late"]
if handler == nil {
t.Fatal("Register returned while the live backend still lacked the new handler")
}
if err := handler(context.Background(), NewJob("job:late")); err != nil {
t.Fatalf("invoke late handler: %v", err)
}
registrationRuntime.Register("job:late", func(context.Context, Job) error {
replacementCalls++
return nil
})
if err := handler(context.Background(), NewJob("job:late")); err != nil {
t.Fatalf("invoke replacement handler: %v", err)
}
if firstCalls != 1 || replacementCalls != 1 {
t.Fatalf("late handler calls = first:%d replacement:%d, want 1/1", firstCalls, replacementCalls)
}
if registrations := worker.registrations["job:late"]; registrations != 1 {
t.Fatalf("late backend registrations = %d, want 1", registrations)
}
for _, jobType := range []string{"job:late:second", "job:late:third"} {
registrationRuntime.Register(jobType, func(context.Context, Job) error { return nil })
if registrations := worker.registrations[jobType]; registrations != 1 {
t.Fatalf("backend registrations for %q = %d, want 1", jobType, registrations)
}
}
close(worker.releaseStart)
err := <-startResult
if test.startFails {
if !errors.Is(err, startErr) {
t.Fatalf("first start error = %v, want %v", err, startErr)
}
worker.startErr = nil
if err := runtime.StartWorkers(context.Background()); err != nil {
t.Fatalf("retry start: %v", err)
}
} else if err != nil {
t.Fatalf("start workers: %v", err)
}
if registrations := worker.registrations["job:late"]; registrations != 1 {
t.Fatalf("late backend registrations after start retry = %d, want 1", registrations)
}
if err := runtime.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown: %v", err)
}
})
}
}
// TestRuntimeConcurrentStartWaiterPreservesLateRegistration verifies a canceled waiter cannot create or disturb the active startup generation.
func TestRuntimeConcurrentStartWaiterPreservesLateRegistration(t *testing.T) {
for _, external := range []bool{false, true} {
name := "native"
if external {
name = "external"
}
t.Run(name, func(t *testing.T) {
worker := &blockingStrictRegistrationRuntimeBackendStub{
startEntered: make(chan struct{}),
releaseStart: make(chan struct{}),
}
var runtime queueRuntime
if external {
runtime = &externalQueueRuntime{
common: &queueCommon{inner: &queueBackendRecorder{}, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
newWorker: func(int) (driverWorkerBackend, error) {
return worker, nil
},
externalQueueRuntimeState: &externalQueueRuntimeState{registered: map[string]Handler{}},
}
} else {
runtime = &nativeQueueRuntime{
common: &queueCommon{inner: worker, cfg: Config{DefaultQueue: "default"}, driver: DriverSync},
runtime: worker,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
}
firstResult := make(chan error, 1)
go func() { firstResult <- runtime.StartWorkers(context.Background()) }()
<-worker.startEntered
secondCtx, cancelSecond := context.WithCancel(context.Background())
secondResult := make(chan error, 1)
go func() {
secondResult <- runtime.StartWorkers(secondCtx)
}()
cancelSecond()
if err := <-secondResult; !errors.Is(err, context.Canceled) {
t.Fatalf("concurrent start waiter error = %v, want context canceled", err)
}
runtime.Register("job:shared-start", func(context.Context, Job) error { return nil })
if worker.registered["job:shared-start"] == nil {
t.Fatal("late registration was absent from the shared startup generation")
}
close(worker.releaseStart)
if err := <-firstResult; err != nil {
t.Fatalf("first start: %v", err)
}
if worker.startCalls != 1 {
t.Fatalf("backend start calls = %d, want 1", worker.startCalls)
}
if registrations := worker.registrations["job:shared-start"]; registrations != 1 {
t.Fatalf("shared-start backend registrations = %d, want 1", registrations)
}
if err := runtime.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown: %v", err)
}
})
}
}
// TestExternalRuntimeRegistrationDuringWorkerConstructionIsInstalledBeforeStart verifies factory latency cannot exclude a completed registration from startup.
func TestExternalRuntimeRegistrationDuringWorkerConstructionIsInstalledBeforeStart(t *testing.T) {
worker := &blockingStrictRegistrationRuntimeBackendStub{
startEntered: make(chan struct{}),
releaseStart: make(chan struct{}),
}
factoryEntered := make(chan struct{})
releaseFactory := make(chan struct{})
runtime := &externalQueueRuntime{
common: &queueCommon{inner: &queueBackendRecorder{}, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
newWorker: func(int) (driverWorkerBackend, error) {
close(factoryEntered)
<-releaseFactory
return worker, nil
},
externalQueueRuntimeState: &externalQueueRuntimeState{registered: map[string]Handler{}},
}
startResult := make(chan error, 1)
go func() { startResult <- runtime.StartWorkers(context.Background()) }()
<-factoryEntered
runtime.Register("job:during-factory", func(context.Context, Job) error { return nil })
runtime.Register("job:during-factory", nil)
close(releaseFactory)
<-worker.startEntered
if worker.registered["job:during-factory"] == nil {
t.Fatal("registration completed during worker construction but was absent when the worker started")
}
if registrations := worker.registrations["job:during-factory"]; registrations != 1 {
t.Fatalf("factory-window backend registrations = %d, want 1", registrations)
}
close(worker.releaseStart)
if err := <-startResult; err != nil {
t.Fatalf("start workers: %v", err)
}
if err := runtime.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown: %v", err)
}
}
// TestNativeRuntimeShutdownRetainsStateForPublicRetry verifies a failed drain cannot make later cleanup a no-op.
func TestNativeRuntimeShutdownRetainsStateForPublicRetry(t *testing.T) {
shutdownErr := errors.New("native shutdown timed out")
backend := &runtimeBackendStub{stopErr: shutdownErr}
runtime := &nativeQueueRuntime{
common: &queueCommon{inner: backend, cfg: Config{DefaultQueue: "default"}, driver: DriverSync},
runtime: backend,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
started: true,
},
}
publicQueue, err := newQueueFromRuntime(runtime)
if err != nil {
t.Fatalf("new public queue: %v", err)
}
if err := publicQueue.Shutdown(context.Background()); !errors.Is(err, shutdownErr) {
t.Fatalf("first shutdown error = %v, want %v", err, shutdownErr)
}
if !runtime.started || !runtime.draining {
t.Fatalf("native runtime lost retryable state: started=%t draining=%t", runtime.started, runtime.draining)
}
if err := publicQueue.StartWorkers(context.Background()); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("start during drain error = %v, want ErrQueuerShuttingDown", err)
}
backend.stopErr = nil
if err := publicQueue.Shutdown(context.Background()); err != nil {
t.Fatalf("retry shutdown: %v", err)
}
if backend.stopCalls != 2 {
t.Fatalf("native shutdown calls = %d, want 2", backend.stopCalls)
}
if runtime.started || runtime.draining {
t.Fatalf("native runtime remained active: started=%t draining=%t", runtime.started, runtime.draining)
}
}
// TestExternalRuntimeShutdownRetainsWorkerForPublicRetry verifies worker and producer cleanup preserve their ordering after timeout.
func TestExternalRuntimeShutdownRetainsWorkerForPublicRetry(t *testing.T) {
shutdownErr := errors.New("worker shutdown timed out")
inner := &queueBackendRecorder{}
worker := &runtimeBackendStub{stopErr: shutdownErr}
runtime := &externalQueueRuntime{
common: &queueCommon{inner: inner, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
externalQueueRuntimeState: &externalQueueRuntimeState{
registered: map[string]Handler{},
worker: worker,
started: true,
},
}
publicQueue, err := newQueueFromRuntime(runtime)
if err != nil {
t.Fatalf("new public queue: %v", err)
}
if err := publicQueue.Shutdown(context.Background()); !errors.Is(err, shutdownErr) {
t.Fatalf("first shutdown error = %v, want %v", err, shutdownErr)
}
if runtime.worker != worker || !runtime.started || !runtime.draining {
t.Fatalf("external runtime lost retryable state: worker=%T started=%t draining=%t", runtime.worker, runtime.started, runtime.draining)
}
if inner.shutdowns != 0 {
t.Fatalf("producer shutdowns = %d before worker drain, want 0", inner.shutdowns)
}
if err := publicQueue.StartWorkers(context.Background()); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("start during drain error = %v, want ErrQueuerShuttingDown", err)
}
worker.stopErr = nil
if err := publicQueue.Shutdown(context.Background()); err != nil {
t.Fatalf("retry shutdown: %v", err)
}
if worker.stopCalls != 2 || inner.shutdowns != 1 {
t.Fatalf("worker/producer shutdown calls = %d/%d, want 2/1", worker.stopCalls, inner.shutdowns)
}
if runtime.worker != nil || runtime.started || runtime.draining {
t.Fatalf("external runtime retained completed state: worker=%T started=%t draining=%t", runtime.worker, runtime.started, runtime.draining)
}
}
// TestNativeRuntimeShutdownClosesNeverStartedBackend verifies producer-owned resources do not depend on worker startup.
func TestNativeRuntimeShutdownClosesNeverStartedBackend(t *testing.T) {
backend := &runtimeBackendStub{}
runtime := &nativeQueueRuntime{
common: &queueCommon{inner: backend, cfg: Config{DefaultQueue: "default"}, driver: DriverDatabase},
runtime: backend,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
if err := runtime.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown never-started runtime: %v", err)
}
if backend.stopCalls != 1 || !runtime.closed {
t.Fatalf("backend stops/closed = %d/%t, want 1/true", backend.stopCalls, runtime.closed)
}
if err := runtime.Shutdown(context.Background()); err != nil {
t.Fatalf("idempotent shutdown: %v", err)
}
if backend.stopCalls != 1 {
t.Fatalf("idempotent backend stops = %d, want 1", backend.stopCalls)
}
if err := runtime.StartWorkers(context.Background()); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("start after shutdown error = %v, want ErrQueuerShuttingDown", err)
}
if err := runtime.Dispatch(NewJob("job:closed")); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("dispatch after shutdown error = %v, want ErrQueuerShuttingDown", err)
}
}
// TestExternalRuntimeShutdownLatchesIntentDuringStart verifies a blocked startup cannot admit work after shutdown begins.
func TestExternalRuntimeShutdownLatchesIntentDuringStart(t *testing.T) {
inner := &queueBackendRecorder{}
worker := &blockingRuntimeBackendStub{
startEntered: make(chan struct{}),
releaseStart: make(chan struct{}),
}
var factoryCalls int
runtime := &externalQueueRuntime{
common: &queueCommon{inner: inner, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
newWorker: func(int) (driverWorkerBackend, error) {
factoryCalls++
return worker, nil
},
externalQueueRuntimeState: &externalQueueRuntimeState{registered: map[string]Handler{}},
}
startResult := make(chan error, 1)
go func() { startResult <- runtime.StartWorkers(context.Background()) }()
<-worker.startEntered
runtime.Register("job:before-startup-drain", func(context.Context, Job) error { return nil })
if worker.registered["job:before-startup-drain"] == nil {
t.Fatal("pre-drain registration was absent during external startup")
}
shutdownResult := make(chan error, 1)
go func() { shutdownResult <- runtime.Shutdown(context.Background()) }()
waitForRuntimeDraining(t, func() bool {
runtime.mu.Lock()
defer runtime.mu.Unlock()
return runtime.draining
})
runtime.Register("job:after-startup-drain", func(context.Context, Job) error { return nil })
if worker.registered["job:after-startup-drain"] != nil {
t.Fatal("post-drain registration reached the external worker")
}
if err := runtime.Dispatch(NewJob("job:rejected").OnQueue("default")); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("dispatch during startup drain = %v, want ErrQueuerShuttingDown", err)
}
if err := runtime.StartWorkers(context.Background()); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("fresh start during startup drain = %v, want ErrQueuerShuttingDown", err)
}
close(worker.releaseStart)
if err := <-startResult; err != nil {
t.Fatalf("original start: %v", err)
}
if err := <-shutdownResult; err != nil {
t.Fatalf("shutdown racing start: %v", err)
}
if factoryCalls != 1 || worker.startCalls != 1 || worker.stopCalls != 1 || inner.shutdowns != 1 {
t.Fatalf("factory/start/stop/producer calls = %d/%d/%d/%d, want 1/1/1/1", factoryCalls, worker.startCalls, worker.stopCalls, inner.shutdowns)
}
if runtime.worker != nil || runtime.started || runtime.draining || !runtime.closed {
t.Fatalf("runtime lifecycle after shutdown = worker:%T started:%t draining:%t closed:%t", runtime.worker, runtime.started, runtime.draining, runtime.closed)
}
}
// TestNativeRuntimeShutdownLatchesIntentDuringStart verifies native startup uses the same shutdown gate.
func TestNativeRuntimeShutdownLatchesIntentDuringStart(t *testing.T) {
worker := &blockingRuntimeBackendStub{
startEntered: make(chan struct{}),
releaseStart: make(chan struct{}),
}
runtime := &nativeQueueRuntime{
common: &queueCommon{inner: worker, cfg: Config{DefaultQueue: "default"}, driver: DriverSync},
runtime: worker,
nativeQueueRuntimeState: &nativeQueueRuntimeState{
registered: map[string]Handler{},
},
}
startResult := make(chan error, 1)
go func() { startResult <- runtime.StartWorkers(context.Background()) }()
<-worker.startEntered
runtime.Register("job:before-startup-drain", func(context.Context, Job) error { return nil })
if worker.registered["job:before-startup-drain"] == nil {
t.Fatal("pre-drain registration was absent during native startup")
}
shutdownResult := make(chan error, 1)
go func() { shutdownResult <- runtime.Shutdown(context.Background()) }()
waitForRuntimeDraining(t, func() bool {
runtime.mu.Lock()
defer runtime.mu.Unlock()
return runtime.draining
})
runtime.Register("job:after-startup-drain", func(context.Context, Job) error { return nil })
if worker.registered["job:after-startup-drain"] != nil {
t.Fatal("post-drain registration reached the native backend")
}
if err := runtime.Dispatch(NewJob("job:rejected")); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("dispatch during startup drain = %v, want ErrQueuerShuttingDown", err)
}
if err := runtime.StartWorkers(context.Background()); !errors.Is(err, ErrQueuerShuttingDown) {
t.Fatalf("fresh start during startup drain = %v, want ErrQueuerShuttingDown", err)
}
close(worker.releaseStart)
if err := <-startResult; err != nil {
t.Fatalf("original start: %v", err)
}
if err := <-shutdownResult; err != nil {
t.Fatalf("shutdown racing start: %v", err)
}
if worker.startCalls != 1 || worker.stopCalls != 1 {
t.Fatalf("native start/stop calls = %d/%d, want 1/1", worker.startCalls, worker.stopCalls)
}
if runtime.started || runtime.draining || !runtime.closed {
t.Fatalf("native lifecycle after shutdown = started:%t draining:%t closed:%t", runtime.started, runtime.draining, runtime.closed)
}
}
// TestExternalRuntimeRetainsFailedStartWorkerForCleanup verifies partial factory resources remain reachable by Shutdown.
func TestExternalRuntimeRetainsFailedStartWorkerForCleanup(t *testing.T) {
startErr := errors.New("worker start failed")
worker := &runtimeBackendStub{startErr: startErr}
inner := &queueBackendRecorder{}
runtime := &externalQueueRuntime{
common: &queueCommon{inner: inner, cfg: Config{DefaultQueue: "default"}, driver: DriverSQS},
newWorker: func(int) (driverWorkerBackend, error) {
return worker, nil
},
externalQueueRuntimeState: &externalQueueRuntimeState{registered: map[string]Handler{}},
}
if err := runtime.StartWorkers(context.Background()); !errors.Is(err, startErr) {
t.Fatalf("start error = %v, want %v", err, startErr)
}