Repository navigation
Expand file tree
/
Copy pathqueue_test.go
More file actions
3687 lines (3422 loc) · 112 KB
/
Copy pathqueue_test.go
File metadata and controls
3687 lines (3422 loc) · 112 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 sqliteq
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/goptics/varmq"
"github.com/goptics/varmq/contract"
)
func TestSQLiteQueue(t *testing.T) {
// Create a temporary store folder
dbPath := t.TempDir()
queues := mustNew(t, dbPath)
// Create a new queue with default settings (removeOnComplete = true)
q, err := queues.NewQueue("test_queue")
if err != nil {
t.Fatalf("Failed to create queue: %v", err)
}
defer queues.Close()
// Test enqueue
t.Run("Enqueue", func(t *testing.T) {
success := q.Enqueue([]byte("test item 1"))
if !success {
t.Error("Enqueue failed")
}
success = q.Enqueue([]byte("42"))
if !success {
t.Error("Enqueue failed")
}
success = q.Enqueue([]byte("some complex data"))
if !success {
t.Error("Enqueue failed")
}
if q.Len() != 3 {
t.Errorf("Expected queue length 3, got %d", q.Len())
}
})
// Test values
t.Run("Values", func(t *testing.T) {
values := q.Values()
if len(values) != 3 {
t.Errorf("Expected 3 values, got %d", len(values))
}
})
// Test dequeue
t.Run("Dequeue", func(t *testing.T) {
data, success := q.Dequeue()
if !success {
t.Error("Dequeue failed")
}
// The first item should be "test item 1" as bytes
byteData, ok := data.([]byte)
if !ok {
t.Errorf("Expected []byte, got %T", data)
}
if string(byteData) != "test item 1" {
t.Errorf("Expected 'test item 1', got '%s'", string(byteData))
}
if q.Len() != 2 {
t.Errorf("Expected queue length 2, got %d", q.Len())
}
// Verify the item is completely removed from the database
var count int
row := q.f.db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE status = 'completed' OR status = 'processing'", q.table))
error := row.Scan(&count)
if error != nil {
t.Errorf("Error checking items in database: %v", error)
}
if count != 0 {
t.Errorf("Expected 0 items with completed/processing status, got %d", count)
}
})
// Test dequeue with ack ID
t.Run("DequeueWithAckId", func(t *testing.T) {
item, success, ackID := q.DequeueWithAckId()
if !success {
t.Error("DequeueWithAckId failed")
}
if ackID == "" {
t.Error("Expected non-empty ack ID")
}
// The next item should be the string "42" as bytes
byteData, ok := item.([]byte)
if !ok {
t.Errorf("Expected []byte, got %T", item)
}
if string(byteData) != "42" {
t.Errorf("Expected '42', got '%s'", string(byteData))
}
// Test acknowledge
ackSuccess := q.Acknowledge(ackID)
if !ackSuccess {
t.Error("Acknowledge failed")
}
// Test invalid ack ID
ackSuccess = q.Acknowledge("invalid-ack-id")
if ackSuccess {
t.Error("Acknowledge with invalid ID should fail")
}
})
// Test purge
t.Run("Purge", func(t *testing.T) {
q.Purge()
if q.Len() != 0 {
t.Errorf("Expected queue length 0 after purge, got %d", q.Len())
}
})
// Test empty queue
t.Run("EmptyQueue", func(t *testing.T) {
item, success := q.Dequeue()
if success {
t.Errorf("Dequeue on empty queue should fail, got %v", item)
}
item, success, ackID := q.DequeueWithAckId()
if success {
t.Errorf("DequeueWithAckId on empty queue should fail, got %v, %s", item, ackID)
}
})
}
// Test removeOnComplete option behavior
func TestRemoveOnCompleteOption(t *testing.T) {
// Test with removeOnComplete = false
t.Run("KeepCompletedItems", func(t *testing.T) {
// Create a temporary store folder
dbPath := t.TempDir()
// Create a queue with removeOnComplete = false
queues := mustNew(t, dbPath)
q, err := queues.NewQueue("test_queue", WithRemoveOnComplete(false))
if err != nil {
t.Fatalf("Failed to create queue: %v", err)
}
defer queues.Close()
// Enqueue an item
q.Enqueue("test item")
// Dequeue with ack ID
_, success, ackID := q.DequeueWithAckId()
if !success {
t.Error("DequeueWithAckId failed")
}
// Acknowledge the item
if !q.Acknowledge(ackID) {
t.Error("Acknowledge failed")
}
// Since removeOnComplete is false, the item should still be in the database
// but marked as completed, so the queue length should be 0
if q.Len() != 0 {
t.Errorf("Expected queue length 0, got %d", q.Len())
}
// Verify the item is still in the database by checking directly
var count int
row := q.f.db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE status = 'completed'", q.table))
error := row.Scan(&count)
if error != nil {
t.Errorf("Error checking completed items: %v", error)
}
if count != 1 {
t.Errorf("Expected 1 completed item in database, got %d", count)
}
})
// Test with removeOnComplete = true (default)
t.Run("RemoveCompletedItems", func(t *testing.T) {
// Create a temporary store folder
dbPath := t.TempDir()
queues := mustNew(t, dbPath)
// Create a queue with default removeOnComplete = true
q, err := queues.NewQueue("test_queue")
if err != nil {
t.Fatalf("Failed to create queue: %v", err)
}
defer queues.Close()
// Enqueue an item
q.Enqueue("test item")
// Test direct dequeue (no ack ID)
_, success := q.Dequeue()
if !success {
t.Error("Dequeue failed")
}
// Since dequeueInternal with withAckId=false now deletes directly,
// the item should be removed from the database immediately
var count int
row := q.f.db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", q.table))
error := row.Scan(&count)
if error != nil {
t.Errorf("Error checking items in database: %v", error)
}
if count != 0 {
t.Errorf("Expected 0 items in database after Dequeue, got %d", count)
}
// Try with DequeueWithAckId and Acknowledge process
q.Enqueue([]byte("test item 2"))
_, success, ackID := q.DequeueWithAckId()
if !success {
t.Error("DequeueWithAckId failed")
}
// Check that the item is still in the database with processing status
row = q.f.db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE status = 'processing'", q.table))
error = row.Scan(&count)
if error != nil {
t.Errorf("Error checking processing items: %v", error)
}
if count != 1 {
t.Errorf("Expected 1 processing item in database, got %d", count)
}
// Acknowledge the item
if !q.Acknowledge(ackID) {
t.Error("Acknowledge failed")
}
// Since removeOnComplete is true, the item should be removed from the database
row = q.f.db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", q.table))
error = row.Scan(&count)
if error != nil {
t.Errorf("Error checking items in database: %v", error)
}
if count != 0 {
t.Errorf("Expected 0 items in database after Acknowledge, got %d", count)
}
})
}
// Test concurrent operations
func TestConcurrentOperations(t *testing.T) {
// Create a temporary store folder
dbPath := t.TempDir()
// Create a new queue
queues := mustNew(t, dbPath)
q, err := queues.NewQueue("test_queue")
if err != nil {
t.Fatalf("Failed to create queue: %v", err)
}
defer queues.Close()
// Enqueue items concurrently
numItems := 100
done := make(chan bool)
// Producer goroutine
go func() {
for i := 0; i < numItems; i++ {
itemData := []byte(fmt.Sprintf("item-%d", i))
if !q.Enqueue(itemData) {
t.Errorf("Failed to enqueue item %d", i)
}
}
done <- true
}()
// Consumer goroutine
processed := 0
ackIDs := make([]string, 0, numItems)
go func() {
for processed < numItems {
_, success, ackID := q.DequeueWithAckId()
if success {
ackIDs = append(ackIDs, ackID)
processed++
}
}
done <- true
}()
// Wait for producer and consumer to finish
<-done
<-done
// Verify all items were processed
if processed != numItems {
t.Errorf("Expected %d processed items, got %d", numItems, processed)
}
// Acknowledge all items
for _, ackID := range ackIDs {
if !q.Acknowledge(ackID) {
t.Errorf("Failed to acknowledge item with ID %s", ackID)
}
}
// Verify queue is empty
if q.Len() != 0 {
t.Errorf("Expected empty queue, got length %d", q.Len())
}
}
func TestQuoteIdent(t *testing.T) {
tt := []struct{ input, want string }{
{"foo", `"foo"`},
{"spaces are here", `"spaces are here"`},
{`"quoted"`, `"""quoted"""`},
{``, `""`}, // belive it or not this is a valid table name
}
for _, tc := range tt {
t.Run(tc.input, func(t *testing.T) {
got := quoteIdent(tc.input)
if got != tc.want {
t.Errorf("Unexpected quotes tabled (want %q, got %q)", tc.want, got)
}
})
}
}
func TestTableInitErrorKeepsPool(t *testing.T) {
qs := mustNew(t, filepath.Join(t.TempDir(), "pool.db"), WithSingleFile())
defer qs.Close()
ok, err := qs.NewQueue("ok")
if err != nil {
t.Fatalf("Failed to create queue: %v", err)
}
// A view named like the queue makes CREATE INDEX fail during table init
if _, err := ok.f.db.Exec(`CREATE VIEW "bad" AS SELECT 1 AS x`); err != nil {
t.Fatalf("Failed to create view: %v", err)
}
if _, err := qs.NewQueue("bad"); err == nil {
t.Fatal("Expected table init to fail for the second queue")
}
if !ok.Enqueue([]byte("still works")) {
t.Error("Enqueue on the first queue failed after the second queue's init error")
}
}
func TestRecoveryError(t *testing.T) {
db, err := sql.Open("sqlite3", filepath.Join(t.TempDir(), "recovery.db"))
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
q := &Queue{f: &file{db: db}, name: "recovery", table: quoteIdent("recovery")}
db.Close()
if err := q.requeueNoAck(); err == nil {
t.Error("Expected an error from requeueNoAck on a closed database")
}
}
// openQueue opens queue "q" in a fresh folder store.
func openQueue(t *testing.T, opts ...Option) (*Queue, Queues) {
t.Helper()
qs := mustNew(t, t.TempDir())
q, err := qs.NewQueue("q", opts...)
if err != nil {
qs.Close()
t.Fatalf("Failed to create queue: %v", err)
}
return q, qs
}
// countRows counts the rows of table "q" matching where.
func countRows(t *testing.T, db *sql.DB, where string) int {
t.Helper()
var n int
if err := db.QueryRow(`SELECT COUNT(*) FROM "q" WHERE ` + where).Scan(&n); err != nil {
t.Fatalf("Failed to count rows: %v", err)
}
return n
}
func TestAckIDIsRowID(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
q.Enqueue([]byte("a"))
q.Enqueue([]byte("b"))
q.Dequeue()
_, ok, ackID := q.DequeueWithAckId()
if !ok {
t.Fatal("DequeueWithAckId failed")
}
got, err := strconv.ParseInt(ackID, 10, 64)
if err != nil {
t.Fatalf("Ack id %q is not a decimal integer: %v", ackID, err)
}
var id int64
if err := q.f.db.QueryRow(`SELECT id FROM "q" WHERE status = 'processing'`).Scan(&id); err != nil {
t.Fatalf("Failed to read the claimed row: %v", err)
}
if got != id || id != 2 {
t.Errorf("Ack id %d, claimed row id %d, want both 2", got, id)
}
}
func TestAckGarbage(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
q.Enqueue([]byte("claimed"))
q.Enqueue([]byte("pending"))
_, ok, ackID := q.DequeueWithAckId()
if !ok {
t.Fatal("DequeueWithAckId failed")
}
// Garbage, a v0.2 cuid, non-canonical spellings of the claimed id, and
// the id of a row that is still pending
garbage := []string{"", "abc", "-1", "0", "99999999999999999999", "cjld2cjxh0000qzrmn831i7rn",
" " + ackID, "+" + ackID, "0" + ackID, ackID + ".0", "2"}
if ackID == "2" {
t.Fatalf("Expected the claimed row to be id 1, got ack id %q", ackID)
}
for _, id := range garbage {
if q.Acknowledge(id) {
t.Errorf("Acknowledge(%q) = true, want false", id)
}
}
if n := countRows(t, q.f.db, "1"); n != 2 {
t.Errorf("Expected 2 rows untouched, got %d", n)
}
if n := countRows(t, q.f.db, "status = 'processing'"); n != 1 {
t.Errorf("Expected the claimed row still processing, got %d processing rows", n)
}
if !q.Acknowledge(ackID) {
t.Error("Acknowledge of the real id failed after the garbage")
}
}
func TestAckTwice(t *testing.T) {
for _, remove := range []bool{true, false} {
t.Run(fmt.Sprintf("remove=%v", remove), func(t *testing.T) {
q, qs := openQueue(t, WithRemoveOnComplete(remove))
defer qs.Close()
q.Enqueue([]byte("a"))
_, ok, ackID := q.DequeueWithAckId()
if !ok {
t.Fatal("DequeueWithAckId failed")
}
if !q.Acknowledge(ackID) {
t.Fatal("First Acknowledge failed")
}
if q.Acknowledge(ackID) {
t.Error("Second Acknowledge of the same id returned true")
}
})
}
}
func TestKeepCompleted(t *testing.T) {
q, qs := openQueue(t, WithRemoveOnComplete(false))
defer qs.Close()
q.Enqueue([]byte("done"))
q.Enqueue([]byte("waiting"))
_, ok, ackID := q.DequeueWithAckId()
if !ok {
t.Fatal("DequeueWithAckId failed")
}
if !q.Acknowledge(ackID) {
t.Fatal("Acknowledge failed")
}
if n := countRows(t, q.f.db, "status = 'completed' AND ack = 1"); n != 1 {
t.Errorf("Expected 1 completed row with ack = 1, got %d", n)
}
if n := q.Len(); n != 1 {
t.Errorf("Expected Len 1 (the completed row excluded), got %d", n)
}
}
func TestOrderByID(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
const n = 1000
for i := 0; i < n; i++ {
if !q.Enqueue([]byte(strconv.Itoa(i))) {
t.Fatalf("Enqueue %d failed", i)
}
}
// Enqueues inside one millisecond, or a clock stepping back, leave
// created_at out of insert order; here it runs backwards outright
if _, err := q.f.db.Exec(`UPDATE "q" SET created_at = datetime('2025-01-01', '-' || id || ' seconds')`); err != nil {
t.Fatalf("Failed to rewrite created_at: %v", err)
}
values := q.Values()
if len(values) != n {
t.Fatalf("Expected %d values, got %d", n, len(values))
}
for i, v := range values {
if got := string(v.([]byte)); got != strconv.Itoa(i) {
t.Fatalf("Values()[%d] = %q, want %q", i, got, strconv.Itoa(i))
}
}
for i := 0; i < n; i++ {
item, ok := q.Dequeue()
if !ok {
t.Fatalf("Dequeue %d failed", i)
}
if got := string(item.([]byte)); got != strconv.Itoa(i) {
t.Fatalf("Dequeue %d = %q, want %q", i, got, strconv.Itoa(i))
}
}
}
func TestConcurrentClaimsNoDuplicates(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
const producers, perProducer, consumers = 8, 100, 8
var wg sync.WaitGroup
for p := 0; p < producers; p++ {
wg.Add(1)
go func(p int) {
defer wg.Done()
for i := 0; i < perProducer; i++ {
if !q.Enqueue([]byte(fmt.Sprintf("%d-%d", p, i))) {
t.Errorf("Enqueue %d-%d failed", p, i)
}
}
}(p)
}
var (
mu sync.Mutex
seen = map[string]int{}
done atomic.Int64
)
var cw sync.WaitGroup
for c := 0; c < consumers; c++ {
cw.Add(1)
go func() {
defer cw.Done()
for done.Load() < producers*perProducer {
item, ok, ackID := q.DequeueWithAckId()
if !ok {
continue
}
mu.Lock()
seen[string(item.([]byte))]++
mu.Unlock()
if !q.Acknowledge(ackID) {
t.Errorf("Acknowledge(%s) failed", ackID)
}
done.Add(1)
}
}()
}
wg.Wait()
cw.Wait()
if len(seen) != producers*perProducer {
t.Errorf("Expected %d distinct jobs, got %d", producers*perProducer, len(seen))
}
for job, n := range seen {
if n != 1 {
t.Errorf("Job %s delivered %d times", job, n)
}
}
if n := countRows(t, q.f.db, "1"); n != 0 {
t.Errorf("Expected no rows left, got %d", n)
}
}
func TestImplementsBatch(t *testing.T) {
type batcher interface {
DequeueBatchWithAckIds([]any, []string) (int, int, error)
}
var _ batcher = (*Queue)(nil)
var _ batcher = (*PriorityQueue)(nil)
}
// enqueueN adds jobs "0".."n-1" to q.
func enqueueN(t *testing.T, q *Queue, n int) {
t.Helper()
for i := 0; i < n; i++ {
if !q.Enqueue([]byte(strconv.Itoa(i))) {
t.Fatalf("Enqueue %d failed", i)
}
}
}
func TestBatchPop(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 10)
items, ackIDs := make([]any, 4), make([]string, 4)
n, remaining, err := q.DequeueBatchWithAckIds(items, ackIDs)
if err != nil || n != 4 || remaining != 6 {
t.Fatalf("Batch of 4: n=%d remaining=%d err=%v, want 4, 6, nil", n, remaining, err)
}
seen := map[string]bool{}
for i := 0; i < n; i++ {
if got := string(items[i].([]byte)); got != strconv.Itoa(i) {
t.Errorf("items[%d] = %q, want %q", i, got, strconv.Itoa(i))
}
if _, ok := parseAckID(ackIDs[i]); !ok {
t.Errorf("ackIDs[%d] = %q is not a row id", i, ackIDs[i])
}
if seen[ackIDs[i]] {
t.Errorf("ackIDs[%d] = %q repeats", i, ackIDs[i])
}
seen[ackIDs[i]] = true
}
items, ackIDs = make([]any, 10), make([]string, 10)
n, remaining, err = q.DequeueBatchWithAckIds(items, ackIDs)
if err != nil || n != 6 || remaining != 0 {
t.Fatalf("Batch of 10: n=%d remaining=%d err=%v, want 6, 0, nil", n, remaining, err)
}
for i := 0; i < n; i++ {
if got := string(items[i].([]byte)); got != strconv.Itoa(i+4) {
t.Errorf("items[%d] = %q, want %q", i, got, strconv.Itoa(i+4))
}
}
n, remaining, err = q.DequeueBatchWithAckIds(items, ackIDs)
if err != nil || n != 0 || remaining != 0 {
t.Fatalf("Empty batch: n=%d remaining=%d err=%v, want 0, 0, nil", n, remaining, err)
}
if got := countRows(t, q.f.db, "status = 'processing'"); got != 10 {
t.Errorf("Expected 10 processing rows, got %d", got)
}
}
func TestBatchMinLen(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 10)
n, remaining, err := q.DequeueBatchWithAckIds(make([]any, 5), make([]string, 2))
if err != nil || n > 2 || remaining != 10-n {
t.Fatalf("n=%d remaining=%d err=%v, want n <= 2, 10-n, nil", n, remaining, err)
}
if got := countRows(t, q.f.db, "status = 'processing'"); got != n {
t.Errorf("Expected %d processing rows, got %d", n, got)
}
}
func TestBatchRemainingCap(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 300)
n, remaining, err := q.DequeueBatchWithAckIds(make([]any, 1), make([]string, 1))
if err != nil || n != 1 || remaining != remainingCap {
t.Fatalf("n=%d remaining=%d err=%v, want 1, %d, nil", n, remaining, err, remainingCap)
}
if got := q.Len(); got != 299 {
t.Errorf("Len() = %d, want 299", got)
}
}
func TestBatchClosed(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 3)
q.Close()
n, _, err := q.DequeueBatchWithAckIds(make([]any, 3), make([]string, 3))
if n != 0 || err != nil {
t.Fatalf("n=%d err=%v after Close, want 0, nil", n, err)
}
if got := countRows(t, q.f.db, "status = 'pending'"); got != 3 {
t.Errorf("Expected 3 pending rows, got %d", got)
}
}
func TestCrashAfterBatch(t *testing.T) {
dir := t.TempDir()
qs := mustNew(t, dir)
q, err := qs.NewQueue("q")
if err != nil {
t.Fatalf("Failed to create queue: %v", err)
}
enqueueN(t, q, 5)
if n, _, err := q.DequeueBatchWithAckIds(make([]any, 3), make([]string, 3)); n != 3 || err != nil {
t.Fatalf("Batch of 3: n=%d err=%v", n, err)
}
// The process "dies": the file closes with 3 rows claimed and no ack
if err := qs.Close(); err != nil {
t.Fatalf("Failed to close: %v", err)
}
qs = mustNew(t, dir)
defer qs.Close()
q, err = qs.NewQueue("q")
if err != nil {
t.Fatalf("Failed to reopen queue: %v", err)
}
if got := q.Len(); got != 5 {
t.Fatalf("Len() = %d after reopen, want 5", got)
}
for i := 0; i < 5; i++ {
item, ok := q.Dequeue()
if !ok {
t.Fatalf("Dequeue %d failed", i)
}
if got := string(item.([]byte)); got != strconv.Itoa(i) {
t.Fatalf("Dequeue %d = %q, want %q", i, got, strconv.Itoa(i))
}
}
}
func TestConcurrentWritersOneFile(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
concurrentWriters(t, q)
}
// concurrentWriters runs 8 producers and 16 ackers against one batch popper
// and checks every job is delivered once and acked.
func concurrentWriters(t *testing.T, q *Queue) {
t.Helper()
const producers, perProducer, ackers, batch = 8, 500, 16, 16
const total = producers * perProducer
var pw sync.WaitGroup
for p := 0; p < producers; p++ {
pw.Add(1)
go func(p int) {
defer pw.Done()
for i := 0; i < perProducer; i++ {
if !q.Enqueue([]byte(fmt.Sprintf("%d-%d", p, i))) {
t.Errorf("Enqueue %d-%d failed", p, i)
}
}
}(p)
}
type job struct{ data, ackID string }
jobs := make(chan job, total)
var (
mu sync.Mutex
seen = map[string]int{}
)
drained := make(chan struct{})
go func() {
defer close(drained)
defer close(jobs)
items, ackIDs := make([]any, batch), make([]string, batch)
// A failed add leaves fewer than total jobs, so the drain is bounded
deadline := time.Now().Add(time.Minute)
for got := 0; got < total; {
if time.Now().After(deadline) {
t.Errorf("Drained %d of %d jobs before the deadline", got, total)
return
}
n, _, err := q.DequeueBatchWithAckIds(items, ackIDs)
if err != nil {
t.Errorf("Batch pop failed: %v", err)
return
}
for i := 0; i < n; i++ {
jobs <- job{string(items[i].([]byte)), ackIDs[i]}
}
got += n
}
}()
var aw sync.WaitGroup
for a := 0; a < ackers; a++ {
aw.Add(1)
go func() {
defer aw.Done()
for j := range jobs {
mu.Lock()
seen[j.data]++
mu.Unlock()
if !q.Acknowledge(j.ackID) {
t.Errorf("Acknowledge(%s) of %s failed", j.ackID, j.data)
}
}
}()
}
pw.Wait()
<-drained
aw.Wait()
if len(seen) != total {
t.Errorf("Expected %d distinct jobs, got %d", total, len(seen))
}
for data, n := range seen {
if n != 1 {
t.Errorf("Job %s delivered %d times", data, n)
}
}
if n := countRows(t, q.f.db, "1"); n != 0 {
t.Errorf("Expected no rows left, got %d", n)
}
}
// TestWritesTakeFileMutex holds the file's write mutex and checks that every
// write waits for it and no read does.
func TestWritesTakeFileMutex(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
enqueueN(t, q, 10)
_, _, ack1 := q.DequeueWithAckId()
writes := []struct {
name string
op func()
}{
{"Enqueue", func() { q.Enqueue([]byte("x")) }},
{"Dequeue", func() { q.Dequeue() }},
{"DequeueWithAckId", func() { q.DequeueWithAckId() }},
{"DequeueBatchWithAckIds", func() { q.DequeueBatchWithAckIds(make([]any, 2), make([]string, 2)) }},
{"Acknowledge", func() { q.Acknowledge(ack1) }},
{"CancelJob", func() { q.CancelJob("x") }},
{"gated DequeueWithAckId", func() { q.DequeueWithAckId() }},
{"gated Dequeue", func() { q.Dequeue() }},
{"requeueNoAck", func() { q.requeueNoAck() }},
{"Purge", func() { q.Purge() }},
}
for _, w := range writes {
t.Run(w.name, func(t *testing.T) {
q.f.mu.Lock()
done := make(chan struct{})
go func() {
w.op()
close(done)
}()
select {
case <-done:
q.f.mu.Unlock()
t.Fatalf("%s ran while the write mutex was held", w.name)
case <-time.After(100 * time.Millisecond):
}
q.f.mu.Unlock()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatalf("%s did not finish after the mutex was released", w.name)
}
})
}
reads := []struct {
name string
op func()
}{
{"Len", func() { q.Len() }},
{"Values", func() { q.Values() }},
}
for _, r := range reads {
t.Run(r.name, func(t *testing.T) {
q.f.mu.Lock()
defer q.f.mu.Unlock()
done := make(chan struct{})
go func() {
r.op()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatalf("%s waited for the write mutex", r.name)
}
})
}
}
// otherProcess opens q's table again on a pool of its own, as a second
// process on the same database file would.
func otherProcess(t *testing.T, q *Queue) *Queue {
t.Helper()
db, err := sql.Open(driverName(q.f.pages), dsn(q.f.key))
if err != nil {
t.Fatal(err)
}
f := &file{key: q.f.key, db: db, pages: q.f.pages, refs: 1, handles: map[string]*handle{}, recovered: map[string]bool{}}
f.b = &batcher{commit: f.commitRound}
q2, err := newQueue(f, q.name, q.priority, WithRemoveOnComplete(q.removeOnComplete))
if err != nil {
db.Close()
t.Fatal(err)
}
t.Cleanup(func() {
q2.Close()
db.Close()
})
return q2
}
// job is a varmq-style envelope with Job ID id.
func job(id string) []byte { return []byte(`{"id":"` + id + `","data":1}`) }
// watch starts a watch of id on q; the channel gets its one outcome.
func watch(q *Queue, id string) <-chan contract.JobOutcome {
ch := make(chan contract.JobOutcome, 2)
q.WatchOutcome(id, func(o contract.JobOutcome) { ch <- o })
return ch
}
func waitOutcome(t *testing.T, ch <-chan contract.JobOutcome) contract.JobOutcome {
t.Helper()
select {
case o := <-ch:
return o
case <-time.After(5 * time.Second):
t.Fatal("no outcome")
return contract.JobOutcome{}
}
}
func noOutcome(t *testing.T, ch <-chan contract.JobOutcome) {
t.Helper()
select {
case o := <-ch:
t.Fatalf("unexpected outcome %+v", o)
case <-time.After(4 * pollEvery):
}
}
// pop hands out the next item and its ack id, failing on none.
func pop(t *testing.T, q *Queue) (string, string) {
t.Helper()
v, ok, ack := q.DequeueWithAckId()
if !ok {
t.Fatal("DequeueWithAckId found nothing")
}
return string(v.([]byte)), ack
}
// A watch reports each way a job ends: Acknowledge, Reject with its reason,
// AcknowledgeResult with its JSON; a job without a Job ID writes nothing.
func TestWatchOutcome(t *testing.T) {
q, qs := openQueue(t)
defer qs.Close()
cases := []struct {
id string
finish func(ack string) bool
want contract.JobOutcome
}{
{"ack", q.Acknowledge, contract.JobOutcome{ID: "ack", State: contract.JobCompleted}},
{"rej", func(a string) bool { return q.Reject(a, "boom") }, contract.JobOutcome{ID: "rej", State: contract.JobFailed, Error: "boom"}},
{"res", func(a string) bool { return q.AcknowledgeResult(a, []byte(`{"n":42}`)) },
contract.JobOutcome{ID: "res", State: contract.JobCompleted, Result: []byte(`{"n":42}`)}},
}
for _, c := range cases {
ch := watch(q, c.id)
q.Enqueue(job(c.id))
_, ack := pop(t, q)
noOutcome(t, ch)
if !c.finish(ack) {
t.Fatalf("%s: finish failed", c.id)
}
got := waitOutcome(t, ch)
if got.ID != c.want.ID || got.State != c.want.State || got.Error != c.want.Error || string(got.Result) != string(c.want.Result) {