-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathmap_broker_memory_test.go
More file actions
4514 lines (4008 loc) · 144 KB
/
Copy pathmap_broker_memory_test.go
File metadata and controls
4514 lines (4008 loc) · 144 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 centrifuge
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require"
)
func newTestMemoryMapBroker(tb testing.TB, n *Node) *MemoryMapBroker {
e, err := NewMemoryMapBroker(n, MemoryMapBrokerConfig{})
require.NoError(tb, err)
err = e.RegisterEventHandler(nil)
require.NoError(tb, err)
tb.Cleanup(func() {
_ = n.Shutdown(context.Background())
})
return e
}
// stateToMapMemory converts []StateEntry to map for easier testing.
func stateToMapMemory(pubs []*Publication) map[string][]byte {
result := make(map[string][]byte, len(pubs))
for _, pub := range pubs {
// Extract data from Publication
result[pub.Key] = pub.Data
}
return result
}
// TestMemoryMapBroker_StatefulChannel tests stateful channel with keyed state and revisions.
func TestMemoryMapBroker_StatefulChannel(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_stateful"
// Publish some keyed state updates
_, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1"),
})
require.NoError(t, err)
_, err = broker.Publish(ctx, channel, "key2", MapPublishOptions{
Data: []byte("data2"),
})
require.NoError(t, err)
_, err = broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1_updated"),
})
require.NoError(t, err)
// Read state
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, streamPos, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.NotEmpty(t, streamPos.Epoch)
require.Greater(t, streamPos.Offset, uint64(0))
// Verify state contains latest values
state := stateToMapMemory(entries)
require.Len(t, state, 2)
require.Equal(t, []byte("data1_updated"), state["key1"])
require.Equal(t, []byte("data2"), state["key2"])
// Read stream to verify all publications are in history
streamResult, err := broker.ReadStream(ctx, channel, MapReadStreamOptions{
Filter: StreamFilter{
Limit: -1, // Get all
},
})
require.NoError(t, err)
require.Len(t, streamResult.Publications, 3) // All 3 publications in stream
}
// TestMemoryMapBroker_StatefulChannelOrdered tests ordered stateful channel.
func TestMemoryMapBroker_StatefulChannelOrdered(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
ordered: true,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_ordered"
// Publish with scores for ordering
for i := 0; i < 5; i++ {
_, err := broker.Publish(ctx, channel, fmt.Sprintf("key%d", i), MapPublishOptions{
Data: []byte(fmt.Sprintf("data%d", i)),
score: int64(i * 10), // Scores: 0, 10, 20, 30, 40
})
require.NoError(t, err)
}
// Read ordered state (descending by score)
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries, 5)
// Verify all keys present
state := stateToMapMemory(entries)
for i := 0; i < 5; i++ {
key := fmt.Sprintf("key%d", i)
require.Contains(t, state, key)
}
}
// TestMemoryMapBroker_StateRevision tests that state values include revisions.
func TestMemoryMapBroker_StateRevision(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_revision"
// Publish a keyed state update
res1, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1"),
})
require.NoError(t, err)
require.Equal(t, uint64(1), res1.Position.Offset)
// Publish another update
res2, err := broker.Publish(ctx, channel, "key2", MapPublishOptions{
Data: []byte("data2"),
})
require.NoError(t, err)
require.Equal(t, uint64(2), res2.Position.Offset)
require.Equal(t, res1.Position.Epoch, res2.Position.Epoch) // Same epoch
// Read state - entries now include per-entry revisions
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, streamPos, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Equal(t, res2.Position.Offset, streamPos.Offset)
require.Equal(t, res2.Position.Epoch, streamPos.Epoch)
// Verify payloads
state := stateToMapMemory(entries)
require.Equal(t, []byte("data1"), state["key1"])
require.Equal(t, []byte("data2"), state["key2"])
// Verify per-entry offsets (epoch is in streamPos, same for all)
require.NotEmpty(t, streamPos.Epoch)
for _, pub := range entries {
require.Greater(t, pub.Offset, uint64(0))
}
}
// TestMemoryMapBroker_StatePagination tests cursor-based state pagination.
func TestMemoryMapBroker_StatePagination(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_pagination"
// Publish 10 keyed entries
for i := 0; i < 10; i++ {
_, err := broker.Publish(ctx, channel, fmt.Sprintf("key%d", i), MapPublishOptions{
Data: []byte(fmt.Sprintf("data%d", i)),
})
require.NoError(t, err)
}
// Read state with limit
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 3,
Cursor: "",
})
page1, pos1, cursor := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.NotEmpty(t, page1)
// Collect all keys across pages
allKeys := make(map[string]bool)
for _, entry := range page1 {
allKeys[entry.Key] = true
}
// Continue reading until cursor is empty
for cursor != "" {
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 3,
Cursor: cursor,
})
page, pos, newCursor := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Equal(t, pos1.Epoch, pos.Epoch) // Same epoch across pages
for _, entry := range page {
// Keys should not repeat across pages
require.NotContains(t, allKeys, entry.Key, "key should not repeat: %s", entry.Key)
allKeys[entry.Key] = true
}
cursor = newCursor
}
// Should have read all 10 entries
require.Len(t, allKeys, 10)
}
// TestMemoryMapBroker_EpochHandling tests epoch changes and state invalidation.
func TestMemoryMapBroker_EpochHandling(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_epoch"
// Publish initial data
res1, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1"),
})
require.NoError(t, err)
epoch1 := res1.Position.Epoch
// Read state
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, streamPos1, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries, 1)
require.Equal(t, epoch1, streamPos1.Epoch)
// Verify epoch consistency
require.NotEmpty(t, epoch1)
}
// TestMemoryMapBroker_EpochMismatchWhenChannelNotExists tests that we return
// ErrorUnrecoverablePosition when client sends an epoch but the channel doesn't exist
// (e.g., after server restart). This is the server restart recovery scenario.
func TestMemoryMapBroker_EpochMismatchWhenChannelNotExists(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_nonexistent_channel"
// Client tries to read state with an old epoch, but channel doesn't exist
// (simulates reconnection after server restart)
_, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Revision: &StreamPosition{
Epoch: "old_epoch_from_previous_session",
Offset: 100,
},
Limit: 100,
})
require.ErrorIs(t, err, ErrorUnrecoverablePosition)
}
// TestMemoryMapBroker_NoEpochWhenChannelNotExists tests that we return success
// when client doesn't send an epoch and the channel doesn't exist (fresh subscription).
func TestMemoryMapBroker_NoEpochWhenChannelNotExists(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_fresh_channel"
// Fresh subscription - no epoch provided
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, streamPos, cursor := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Empty(t, entries) // No entries in non-existent channel
require.NotEmpty(t, streamPos.Epoch) // Should get a new epoch
require.Empty(t, cursor) // No cursor for empty result
}
// TestMemoryMapBroker_Idempotency tests idempotent publishing.
func TestMemoryMapBroker_Idempotency(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_idempotency"
// Publish with idempotency key
res1, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1"),
IdempotencyKey: "unique-id-1",
IdempotentResultTTL: 60 * time.Second,
})
require.NoError(t, err)
require.False(t, res1.Suppressed)
require.Equal(t, uint64(1), res1.Position.Offset)
// Publish again with same idempotency key
res2, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1_different"),
IdempotencyKey: "unique-id-1",
IdempotentResultTTL: 60 * time.Second,
})
require.NoError(t, err)
require.True(t, res2.Suppressed) // Suppressed due to idempotency
require.Equal(t, SuppressReasonIdempotency, res2.SuppressReason)
require.Equal(t, res1.Position.Offset, res2.Position.Offset) // Same offset
require.Equal(t, res1.Position.Epoch, res2.Position.Epoch) // Same epoch
// State should still have original data (second publish was cached/skipped)
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
state := stateToMapMemory(entries)
require.Len(t, state, 1)
require.Equal(t, []byte("data1"), state["key1"])
}
// TestMemoryMapBroker_VersionedPublishing tests version-based idempotency.
func TestMemoryMapBroker_VersionedPublishing(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_version"
// Publish with version 2 (version 0 means "disable version check")
res1, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data_v2"),
Version: 2,
})
require.NoError(t, err)
require.False(t, res1.Suppressed)
require.Equal(t, uint64(1), res1.Position.Offset)
// Try to publish older version (should be suppressed)
res2, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data_v1"),
Version: 1,
})
require.NoError(t, err)
require.True(t, res2.Suppressed) // Suppressed due to out-of-order version
require.Equal(t, SuppressReasonVersion, res2.SuppressReason)
require.Equal(t, res1.Position.Offset, res2.Position.Offset) // Same offset (suppressed)
// Publish newer version
res3, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data_v3"),
Version: 3,
})
require.NoError(t, err)
require.False(t, res3.Suppressed)
require.Equal(t, uint64(2), res3.Position.Offset) // New offset
// State should have v3 data
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
state := stateToMapMemory(entries)
require.Equal(t, []byte("data_v3"), state["key1"])
}
// TestMemoryMapBroker_PerKeyVersion tests that version tracking is per-key independent.
func TestMemoryMapBroker_PerKeyVersion(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_per_key_version"
// key1 with version=10 → accepted
res1, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("key1_v10"),
Version: 10,
})
require.NoError(t, err)
require.False(t, res1.Suppressed)
// key2 with version=5 → accepted (independent, was broken before per-key version)
res2, err := broker.Publish(ctx, channel, "key2", MapPublishOptions{
Data: []byte("key2_v5"),
Version: 5,
})
require.NoError(t, err)
require.False(t, res2.Suppressed, "key2 should not be suppressed by key1's version")
// key1 with version=5 → suppressed (same key, lower version)
res3, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("key1_v5"),
Version: 5,
})
require.NoError(t, err)
require.True(t, res3.Suppressed)
require.Equal(t, SuppressReasonVersion, res3.SuppressReason)
// Remove key1
_, err = broker.Remove(ctx, channel, "key1", MapRemoveOptions{})
require.NoError(t, err)
// Publish key1 with version=1 → accepted (version cleared by remove)
res4, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("key1_v1"),
Version: 1,
})
require.NoError(t, err)
require.False(t, res4.Suppressed, "key1 version should be cleared after remove")
// Verify final state
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
require.NoError(t, err)
state := stateToMapMemory(stateRes.Publications)
require.Equal(t, []byte("key1_v1"), state["key1"])
require.Equal(t, []byte("key2_v5"), state["key2"])
}
// TestMemoryMapBroker_MultipleChannels tests multiple channels independently.
func TestMemoryMapBroker_MultipleChannels(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel1 := "test_multi1"
channel2 := "test_multi2"
// Publish to channel1
_, err := broker.Publish(ctx, channel1, "key1", MapPublishOptions{
Data: []byte("data1"),
})
require.NoError(t, err)
// Publish to channel2
_, err = broker.Publish(ctx, channel2, "key2", MapPublishOptions{
Data: []byte("data2"),
})
require.NoError(t, err)
// Read channel1 state
stateRes, err := broker.ReadState(ctx, channel1, MapReadStateOptions{
Limit: 100,
})
entries1, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
state1 := stateToMapMemory(entries1)
require.Len(t, state1, 1)
require.Equal(t, []byte("data1"), state1["key1"])
// Read channel2 state
stateRes, err = broker.ReadState(ctx, channel2, MapReadStateOptions{
Limit: 100,
})
entries2, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
state2 := stateToMapMemory(entries2)
require.Len(t, state2, 1)
require.Equal(t, []byte("data2"), state2["key2"])
}
// TestMemoryMapBroker_OrderedStateOrdering tests that ordered state return entries
// in correct score order (descending by score).
func TestMemoryMapBroker_OrderedStateOrdering(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
ordered: true,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_ordered_ordering"
// Publish entries with specific scores (out of order to test sorting)
testCases := []struct {
key string
score int64
data string
}{
{"key_c", 30, "data_c"},
{"key_a", 10, "data_a"},
{"key_e", 50, "data_e"},
{"key_b", 20, "data_b"},
{"key_d", 40, "data_d"},
}
for _, tc := range testCases {
_, err := broker.Publish(ctx, channel, tc.key, MapPublishOptions{
Data: []byte(tc.data),
score: tc.score,
})
require.NoError(t, err)
}
// Read ordered state - should be sorted by score (descending)
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries, 5, "Should have all 5 entries")
// Verify ordering by score (descending: 50, 40, 30, 20, 10)
expectedOrder := []string{"key_e", "key_d", "key_c", "key_b", "key_a"}
for i, entry := range entries {
require.Equal(t, expectedOrder[i], entry.Key, "Entry %d should be %s", i, expectedOrder[i])
}
t.Logf("SUCCESS: Entries returned in correct descending score order: %v", expectedOrder)
}
// TestMemoryMapBroker_OrderedStatePagination tests that pagination over ordered state
// maintains correct ordering across pages.
func TestMemoryMapBroker_OrderedStatePagination(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
ordered: true,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_ordered_pagination"
// Publish 20 entries with scores 100, 200, 300, ..., 2000
for i := 1; i <= 20; i++ {
key := fmt.Sprintf("key_%02d", i)
score := int64(i * 100)
data := fmt.Sprintf("data_%02d", i)
_, err := broker.Publish(ctx, channel, key, MapPublishOptions{
Data: []byte(data),
score: score,
})
require.NoError(t, err)
}
// Read first page (limit=5, no cursor)
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 5,
})
page1, pos1, cursor1 := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, page1, 5, "First page should have 5 entries")
require.NotEmpty(t, cursor1, "Should have cursor for next page")
// Verify first page ordering (descending: 20, 19, 18, 17, 16)
for i := 0; i < 5; i++ {
expectedKey := fmt.Sprintf("key_%02d", 20-i)
require.Equal(t, expectedKey, page1[i].Key, "Page 1, entry %d should be %s", i, expectedKey)
}
// Read second page (using cursor)
stateRes, err = broker.ReadState(ctx, channel, MapReadStateOptions{
Cursor: cursor1,
Limit: 5,
})
page2, pos2, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, page2, 5, "Second page should have 5 entries")
require.Equal(t, pos1.Epoch, pos2.Epoch, "Epoch should be consistent across pages")
// Verify second page ordering (descending: 15, 14, 13, 12, 11)
for i := 0; i < 5; i++ {
expectedKey := fmt.Sprintf("key_%02d", 15-i)
require.Equal(t, expectedKey, page2[i].Key, "Page 2, entry %d should be %s", i, expectedKey)
}
t.Logf("SUCCESS: Pagination maintains correct ordering across pages")
}
// TestMemoryMapBroker_OrderedStateWithNegativeScores tests ordering with negative scores.
func TestMemoryMapBroker_OrderedStateWithNegativeScores(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
ordered: true,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_ordered_negative"
// Publish entries with negative, zero, and positive scores
testCases := []struct {
key string
score int64
}{
{"key_pos", 100},
{"key_neg", -50},
{"key_zero", 0},
{"key_neg2", -100},
{"key_pos2", 50},
}
for _, tc := range testCases {
_, err := broker.Publish(ctx, channel, tc.key, MapPublishOptions{
Data: []byte("data"),
score: tc.score,
})
require.NoError(t, err)
}
// Read ordered state
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries, 5)
// Verify ordering (descending: 100, 50, 0, -50, -100)
expectedOrder := []string{"key_pos", "key_pos2", "key_zero", "key_neg", "key_neg2"}
for i, entry := range entries {
require.Equal(t, expectedOrder[i], entry.Key, "Entry %d should be %s", i, expectedOrder[i])
}
t.Logf("SUCCESS: Negative scores handled correctly in descending ordering")
}
// TestMemoryMapBroker_OrderedStateUpdatePreservesOrder tests that updating an entry's score
// changes its position in the ordered state.
func TestMemoryMapBroker_OrderedStateUpdatePreservesOrder(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
ordered: true,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_ordered_update"
// Publish 5 entries
for i := 1; i <= 5; i++ {
_, err := broker.Publish(ctx, channel, fmt.Sprintf("key_%d", i), MapPublishOptions{
Data: []byte(fmt.Sprintf("data_%d", i)),
score: int64(i * 10), // 10, 20, 30, 40, 50
})
require.NoError(t, err)
}
// Read initial order (descending: 50, 40, 30, 20, 10)
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries1, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Equal(t, "key_5", entries1[0].Key) // Highest score (50)
require.Equal(t, "key_1", entries1[4].Key) // Lowest score (10)
// Update key_1 to have highest score (60)
_, err = broker.Publish(ctx, channel, "key_1", MapPublishOptions{
Data: []byte("updated_data"),
score: 60, // Now highest
})
require.NoError(t, err)
// Read updated order
stateRes, err = broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries2, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries2, 5)
// Verify new order (descending: 60, 50, 40, 30, 20)
expectedOrder := []string{"key_1", "key_5", "key_4", "key_3", "key_2"}
for i, entry := range entries2 {
require.Equal(t, expectedOrder[i], entry.Key, "After update, entry %d should be %s", i, expectedOrder[i])
}
t.Logf("SUCCESS: Updating score correctly reorders entries in descending order")
}
// TestMemoryMapBroker_Remove tests removing keys from state.
func TestMemoryMapBroker_Remove(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_remove"
// Publish some keys
_, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte("data1"),
})
require.NoError(t, err)
_, err = broker.Publish(ctx, channel, "key2", MapPublishOptions{
Data: []byte("data2"),
})
require.NoError(t, err)
// Verify state has 2 keys
stateRes, err := broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ := stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries, 2)
// Remove key1
_, err = broker.Remove(ctx, channel, "key1", MapRemoveOptions{})
require.NoError(t, err)
// Verify state has 1 key
stateRes, err = broker.ReadState(ctx, channel, MapReadStateOptions{
Limit: 100,
})
entries, _, _ = stateRes.Publications, stateRes.Position, stateRes.Cursor
require.NoError(t, err)
require.Len(t, entries, 1)
require.Equal(t, "key2", entries[0].Key)
// Verify remove was added to stream
streamResult, err := broker.ReadStream(ctx, channel, MapReadStreamOptions{
Filter: StreamFilter{
Limit: -1,
},
})
require.NoError(t, err)
require.Len(t, streamResult.Publications, 3) // key1, key2, remove(key1)
require.True(t, streamResult.Publications[2].Removed)
require.Equal(t, "key1", streamResult.Publications[2].Key)
// Remove non-existent key should be suppressed with key_not_found
res, err := broker.Remove(ctx, channel, "nonexistent", MapRemoveOptions{})
require.NoError(t, err)
require.True(t, res.Suppressed)
require.Equal(t, SuppressReasonKeyNotFound, res.SuppressReason)
// Verify no extra stream entry was added
streamResult, err = broker.ReadStream(ctx, channel, MapReadStreamOptions{
Filter: StreamFilter{
Limit: -1,
},
})
require.NoError(t, err)
require.Len(t, streamResult.Publications, 3) // Still 3 - no entry for nonexistent key
}
func TestMemoryMapBroker_RemovePreservesTags(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModePersistent,
StreamSize: 100,
StreamTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_remove_tags"
// Publish with tags.
_, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte(`{"v":1}`),
Tags: map[string]string{"role": "admin", "team": "eng"},
})
require.NoError(t, err)
// Remove without explicit tags — should auto-read from state.
_, err = broker.Remove(ctx, channel, "key1", MapRemoveOptions{})
require.NoError(t, err)
// Read stream — removal should have the original tags.
streamResult, err := broker.ReadStream(ctx, channel, MapReadStreamOptions{
Filter: StreamFilter{Limit: -1},
})
require.NoError(t, err)
var removal *Publication
for _, pub := range streamResult.Publications {
if pub.Removed {
removal = pub
}
}
require.NotNil(t, removal)
require.Equal(t, map[string]string{"role": "admin", "team": "eng"}, removal.Tags)
}
func TestMemoryMapBroker_RemoveExplicitTagsOverride(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModePersistent,
StreamSize: 100,
StreamTTL: 300 * time.Second,
}
}
broker := newTestMemoryMapBroker(t, node)
ctx := context.Background()
channel := "test_remove_explicit_tags"
// Publish with tags.
_, err := broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte(`{"v":1}`),
Tags: map[string]string{"role": "admin"},
})
require.NoError(t, err)
// Remove with explicit tags — should override state tags.
_, err = broker.Remove(ctx, channel, "key1", MapRemoveOptions{
Tags: map[string]string{"role": "viewer"},
})
require.NoError(t, err)
streamResult, err := broker.ReadStream(ctx, channel, MapReadStreamOptions{
Filter: StreamFilter{Limit: -1},
})
require.NoError(t, err)
var removal *Publication
for _, pub := range streamResult.Publications {
if pub.Removed {
removal = pub
}
}
require.NotNil(t, removal)
require.Equal(t, map[string]string{"role": "viewer"}, removal.Tags)
}
func TestMemoryMapBroker_CleanupPreservesTags(t *testing.T) {
t.Parallel()
node, _ := New(Config{})
node.config.Map.GetMapChannelOptions = func(channel string) MapChannelOptions {
return MapChannelOptions{
Mode: MapModeRecoverable,
StreamSize: 100,
StreamTTL: 300 * time.Second,
KeyTTL: 50 * time.Millisecond,
}
}
handler := &testBrokerEventHandler{
HandlePublicationFunc: func(ch string, pub *Publication, sp StreamPosition, useDelta bool, prevPub *Publication) error {
return nil
},
}
broker, err := NewMemoryMapBroker(node, MemoryMapBrokerConfig{})
require.NoError(t, err)
err = broker.RegisterEventHandler(handler)
require.NoError(t, err)
t.Cleanup(func() { _ = node.Shutdown(context.Background()) })
ctx := context.Background()
channel := "test_cleanup_tags"
// Publish with tags.
_, err = broker.Publish(ctx, channel, "key1", MapPublishOptions{
Data: []byte(`{"v":1}`),
Tags: map[string]string{"role": "admin"},
})
require.NoError(t, err)
// Wait for expiry + trigger cleanup.
time.Sleep(100 * time.Millisecond)
var nextCheck int64