-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathmap_broker_redis.go
More file actions
3278 lines (2983 loc) · 96.4 KB
/
Copy pathmap_broker_redis.go
File metadata and controls
3278 lines (2983 loc) · 96.4 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 (
"bytes"
"context"
"errors"
"fmt"
"runtime"
"strconv"
"strings"
"sync"
"time"
_ "embed"
"github.com/centrifugal/centrifuge/internal/convert"
"github.com/centrifugal/centrifuge/internal/epoch"
"github.com/centrifugal/centrifuge/internal/redispartition"
"github.com/centrifugal/protocol"
"github.com/redis/rueidis"
)
var (
//go:embed internal/redis_lua/map_broker_add.lua
brokerStatePublishScriptSource string
//go:embed internal/redis_lua/map_broker_read_ordered.lua
brokerStateReadOrderedScriptSource string
//go:embed internal/redis_lua/map_broker_read_unordered.lua
brokerStateReadUnorderedScriptSource string
//go:embed internal/redis_lua/map_broker_stream_read.lua
brokerStateReadStreamScriptSource string
//go:embed internal/redis_lua/map_broker_read_meta.lua
brokerStateReadMetaScriptSource string
//go:embed internal/redis_lua/map_broker_stats.lua
brokerStateStatsScriptSource string
//go:embed internal/redis_lua/map_broker_find_expired.lua
brokerStateFindExpiredScriptSource string
//go:embed internal/redis_lua/map_broker_batch_remove.lua
brokerStateBatchRemoveScriptSource string
)
type brokerShardWrapper struct {
shard *RedisShard
subClientsMu sync.Mutex
subClients [][]rueidis.DedicatedClient
pubSubStartChannels [][]*pubSubStart
pubSubRunner mapBrokerPubSubRunner
}
// mapBrokerPubSubRunner abstracts the subscriber-side pub/sub strategy for
// RedisMapBroker. Mirrors brokerPubSubRunner; one instance per shard, selected
// at construction time. subClientsIndex maps a partition-derived cluster shard
// index to the first-dimension index used in brokerShardWrapper.subClients
// (default is identity; non-default strategies may remap, e.g. partition → node).
type mapBrokerPubSubRunner interface {
init(s *brokerShardWrapper, shard *RedisShard) error
run(s *brokerShardWrapper, h BrokerEventHandler) error
subClientsIndex(clusterShardIdx int) int
}
// RedisMapBroker is a Redis-based MapBroker.
// Note – it does not work properly with Redis eviction, use with disabled eviction
// to avoid undefined state.
//
// Message Formats
// ===============
//
// This broker uses simplified message formats published by Lua scripts:
//
// 1. No prefix:
// - Raw protobuf bytes (Publication)
// - Used by direct PUBLISH calls without Lua scripts when stream is not used.
//
// 2. Non-delta publications:
// - Format: "offset:epoch:Publication"
// - Where Publication is in protobuf format.
//
// 3. Delta publications:
// - Format: "d:offset:epoch:prev_len:prev_publication:curr_len:curr_publication"
// - Where prev_publication and curr_publication are protocol.Publication in protobuf.
// - Enables atomic publishing of current + previous publication for delta compression of publication data.
// - Prev is atomically fetched from stream.
//
// Storage:
// - Streams (XADD): keeps protocol.Publication
// - States (HSET): For keyed state - may keep latest protocol.Publication or custom state.
//
// Pagination:
// - ordered state use ZRANGEBYSCORE/ZRANGEBYLEX with LIMIT — exact page sizes.
// - Unordered state use HSCAN with COUNT — COUNT is only a hint, Redis may return
// more entries than requested (especially for small hashes in listpack encoding).
// Callers should not rely on exact Limit enforcement for unordered reads.
type RedisMapBroker struct {
node *Node
conf RedisMapBrokerConfig
shards []*brokerShardWrapper
// partitionTags is non-nil when UsePrecomputedPartitionTags is enabled;
// indexed by partition index, returns the hash tag string. Read-only
// after construction (shared with the package-level precomputed table).
partitionTags []string
addScript *rueidis.Lua
readOrderedScript *rueidis.Lua
readUnorderedScript *rueidis.Lua
readStreamScript *rueidis.Lua
readMetaScript *rueidis.Lua
presenceStatsScript *rueidis.Lua
findExpiredScript *rueidis.Lua
batchRemoveScript *rueidis.Lua
closeCh chan struct{}
closeOnce sync.Once
shardChannel string
messagePrefix string
}
var _ MapBroker = (*RedisMapBroker)(nil)
// RedisMapBrokerConfig is a config for RedisMapBroker.
type RedisMapBrokerConfig struct {
// Shards is a slice of RedisShard to use. At least one shard must be provided.
Shards []*RedisShard
// Prefix to use before every channel name and key in Redis.
Prefix string
// Name of broker, for observability purposes – i.e. becomes part of metrics/logs labels.
// By default, empty string is used.
Name string
// LoadSHA1 enables loading SHA1 from Redis via SCRIPT LOAD instead of calculating
// it on the client side. This is useful for FIPS compliance.
LoadSHA1 bool
// IdempotentResultTTL is a time-to-live for idempotent result.
IdempotentResultTTL time.Duration
// SubscribeOnReplica allows subscribing on replica Redis nodes.
SubscribeOnReplica bool
// SkipPubSub enables mode when broker only works with data structures, without
// publishing to channels and using PUB/SUB.
SkipPubSub bool
// NumShardedPubSubPartitions when greater than zero allows turning on a mode in which
// broker will use Redis Cluster with sharded PUB/SUB feature available in
// Redis >= 7: https://redis.io/docs/manual/pubsub/#sharded-pubsub
NumShardedPubSubPartitions int
// UsePrecomputedPartitionTags switches sharded PUB/SUB partition hash tags
// from the bare partition index ("0", "1", ...) to a precomputed table
// chosen so CRC16 hash slots distribute evenly across any cluster size.
// See RedisBrokerConfig.UsePrecomputedPartitionTags for details and
// migration constraints.
//
// When enabled, NumShardedPubSubPartitions must equal one of the sizes
// returned by redispartition.PrecomputedSizes() (16, 32, 64, 128, 256,
// 512, 1024, 2048, 4096). Construction returns an error otherwise. The
// exact tag table is bundled in internal/redispartition/precomputed.go;
// the tags are stable and will not change.
//
// Default: false (backward-compatible bare-index tags).
UsePrecomputedPartitionTags bool
// numSubscribeShards defines how many subscribe shards will be used.
numSubscribeShards int
// numResubscribeShards defines how many subscriber goroutines will be used for
// resubscribing process for each subscribe shard.
numResubscribeShards int
// pubSubProbeInterval configures how often the broker verifies that its
// PUB/SUB connections still deliver messages. See the field with the same
// name in RedisBrokerConfig for the details. Not exported: the default is
// expected to work everywhere, the knob only exists for tests.
pubSubProbeInterval time.Duration
// numPubSubProcessors allows configuring number of workers which will process
// messages coming from Redis PUB/SUB.
numPubSubProcessors int
// CleanupInterval defines how often to run the cleanup worker that
// generates remove events for expired keyed state entries (presence and state).
// Default is 1 second. Set to -1 to disable cleanup (make sure you understand the consequences).
// Applies to all channels using TTL-based state.
CleanupInterval time.Duration
// CleanupBatchSize defines max entries to process per channel per cleanup cycle.
// Default is 100. Applies to all keyed state (presence and state).
CleanupBatchSize int
}
// NewRedisMapBroker initializes RedisMapBroker.
func NewRedisMapBroker(n *Node, conf RedisMapBrokerConfig) (*RedisMapBroker, error) {
if len(conf.Shards) == 0 {
return nil, errors.New("state broker: no shards provided")
}
if conf.SubscribeOnReplica {
for i, s := range conf.Shards {
if s.replicaClient == nil {
return nil, fmt.Errorf("broker: SubscribeOnReplica enabled but no replica client initialized in shard[%d] (ReplicaClientEnabled option)", i)
}
}
}
if conf.Prefix == "" {
conf.Prefix = "centrifuge"
}
if conf.IdempotentResultTTL == 0 {
conf.IdempotentResultTTL = 5 * time.Minute
}
if conf.numSubscribeShards == 0 {
conf.numSubscribeShards = 1
}
if conf.numResubscribeShards == 0 {
conf.numResubscribeShards = 16
}
conf.pubSubProbeInterval = normalizePubSubProbeInterval(conf.pubSubProbeInterval)
if conf.numPubSubProcessors == 0 {
conf.numPubSubProcessors = runtime.NumCPU() / conf.numSubscribeShards
if conf.NumShardedPubSubPartitions > 0 {
conf.numPubSubProcessors /= conf.NumShardedPubSubPartitions
}
if conf.numPubSubProcessors < 1 {
conf.numPubSubProcessors = 1
}
}
if conf.CleanupBatchSize == 0 {
conf.CleanupBatchSize = 100
}
if conf.CleanupInterval == 0 {
conf.CleanupInterval = time.Second
}
var partitionTags []string
if conf.UsePrecomputedPartitionTags {
if conf.NumShardedPubSubPartitions <= 0 {
return nil, errors.New("state broker: UsePrecomputedPartitionTags requires NumShardedPubSubPartitions > 0")
}
tags, err := redispartition.FindTags(conf.NumShardedPubSubPartitions)
if err != nil {
return nil, fmt.Errorf("state broker: %w", err)
}
partitionTags = tags
}
shardWrappers := make([]*brokerShardWrapper, 0, len(conf.Shards))
for _, s := range conf.Shards {
shardWrappers = append(shardWrappers, &brokerShardWrapper{shard: s})
}
e := &RedisMapBroker{
node: n,
conf: conf,
shards: shardWrappers,
partitionTags: partitionTags,
addScript: rueidis.NewLuaScript(
brokerStatePublishScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
readOrderedScript: rueidis.NewLuaScript(
brokerStateReadOrderedScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
readUnorderedScript: rueidis.NewLuaScript(
brokerStateReadUnorderedScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
readStreamScript: rueidis.NewLuaScript(
brokerStateReadStreamScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
readMetaScript: rueidis.NewLuaScript(
brokerStateReadMetaScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
presenceStatsScript: rueidis.NewLuaScript(
brokerStateStatsScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
findExpiredScript: rueidis.NewLuaScript(
brokerStateFindExpiredScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
batchRemoveScript: rueidis.NewLuaScript(
brokerStateBatchRemoveScriptSource,
rueidis.WithLoadSHA1(conf.LoadSHA1),
),
closeCh: make(chan struct{}),
}
e.shardChannel = conf.Prefix + redisPubSubShardChannelSuffix
e.messagePrefix = conf.Prefix + redisClientChannelPrefix
for _, wrapper := range e.shards {
shard := wrapper.shard
if !shard.isCluster && e.conf.NumShardedPubSubPartitions > 0 {
return nil, errors.New("can use sharded PUB/SUB feature (non-zero number of pub/sub partitions) only with Redis Cluster")
}
if shard.isCluster && e.conf.NumShardedPubSubPartitions == 0 {
return nil, errors.New("redis cluster requires sharded PUB/SUB (set NumShardedPubSubPartitions > 0)")
}
if newMapBrokerPubSubRunnerHook != nil {
wrapper.pubSubRunner = newMapBrokerPubSubRunnerHook(e, shard)
}
if wrapper.pubSubRunner == nil {
wrapper.pubSubRunner = &defaultMapBrokerPubSubRunner{broker: e}
}
if err := wrapper.pubSubRunner.init(wrapper, shard); err != nil {
return nil, err
}
}
if e.conf.CleanupInterval > 0 {
go e.runCleanupWorker(context.Background())
go e.runCleanupLagWorker(context.Background())
}
return e, nil
}
// parseStateValue parses a state value in format: offset:epoch:payload
// Returns offset, epoch, payload, and error if parsing fails.
func parseStateValue(val []byte) (uint64, string, []byte, error) {
if len(val) == 0 {
return 0, "", nil, fmt.Errorf("empty state value")
}
// Find first colon (offset separator)
firstColon := bytes.IndexByte(val, ':')
if firstColon == -1 {
return 0, "", nil, fmt.Errorf("missing offset separator in state value")
}
// Parse offset
offset, err := strconv.ParseUint(convert.BytesToString(val[:firstColon]), 10, 64)
if err != nil {
return 0, "", nil, fmt.Errorf("invalid offset in state value: %w", err)
}
// Find second colon (epoch separator)
remaining := val[firstColon+1:]
secondColon := bytes.IndexByte(remaining, ':')
if secondColon == -1 {
return 0, "", nil, fmt.Errorf("missing epoch separator in state value")
}
// Extract epoch
epoch := convert.BytesToString(remaining[:secondColon])
// Everything after second colon is payload
payload := remaining[secondColon+1:]
return offset, epoch, payload, nil
}
func (e *RedisMapBroker) useShardedPubSub(s *RedisShard) bool {
return s.isCluster && e.conf.NumShardedPubSubPartitions > 0
}
func (e *RedisMapBroker) getShard(channel string) *brokerShardWrapper {
if len(e.shards) == 1 {
return e.shards[0]
}
return e.shards[consistentIndex(channel, len(e.shards))]
}
func (e *RedisMapBroker) streamKey(s *RedisShard, ch string) string {
return e.buildKey(s, ch, ":stream:")
}
func (e *RedisMapBroker) metaKey(s *RedisShard, ch string) string {
return e.buildKey(s, ch, ":meta:")
}
func (e *RedisMapBroker) stateHashKey(s *RedisShard, ch string) string {
return e.buildKey(s, ch, ":state:")
}
func (e *RedisMapBroker) stateOrderKey(s *RedisShard, ch string) string {
return e.buildKey(s, ch, ":state:order:")
}
func (e *RedisMapBroker) stateExpireKey(s *RedisShard, ch string) string {
return e.buildKey(s, ch, ":state:expire:")
}
func (e *RedisMapBroker) stateMetaKey(s *RedisShard, ch string) string {
return e.buildKey(s, ch, ":state:meta:")
}
func (e *RedisMapBroker) cleanupRegistrationKeyForChannel(s *RedisShard, ch string) string {
// Get the cleanup registration key with proper hash tag for the channel's partition
// Single registration ZSET works for ALL keyed state (presence, state, etc.)
if !s.isCluster {
return e.conf.Prefix + ":cleanup:channels"
}
idx := consistentIndex(ch, e.conf.NumShardedPubSubPartitions)
return e.conf.Prefix + ":cleanup:channels:{" + e.pubSubPartitionHashTag(idx) + "}"
}
func (e *RedisMapBroker) resultCacheKey(s *RedisShard, ch string, idempotencyKey string) string {
if !s.isCluster {
var builder strings.Builder
builder.Grow(len(e.conf.Prefix) + 9 + len(ch) + 1 + len(idempotencyKey))
builder.WriteString(e.conf.Prefix)
builder.WriteString(".result.")
builder.WriteString(ch)
builder.WriteByte('.')
builder.WriteString(idempotencyKey)
return builder.String()
}
idx := consistentIndex(ch, e.conf.NumShardedPubSubPartitions)
idxStr := e.pubSubPartitionHashTag(idx)
var builder strings.Builder
capacity := len(e.conf.Prefix) + 9 + 1 + len(idxStr) + 2 + len(ch) + 1 + len(idempotencyKey)
builder.Grow(capacity)
builder.WriteString(e.conf.Prefix)
builder.WriteString(".result.{")
builder.WriteString(idxStr)
builder.WriteString("}.")
builder.WriteString(ch)
builder.WriteByte('.')
builder.WriteString(idempotencyKey)
return builder.String()
}
// buildKey is a helper function to build Redis keys with proper cluster hash tag support
func (e *RedisMapBroker) buildKey(s *RedisShard, ch string, infix string) string {
if !s.isCluster {
var builder strings.Builder
builder.Grow(len(e.conf.Prefix) + len(infix) + len(ch))
builder.WriteString(e.conf.Prefix)
builder.WriteString(infix)
builder.WriteString(ch)
return builder.String()
}
idx := consistentIndex(ch, e.conf.NumShardedPubSubPartitions)
idxStr := e.pubSubPartitionHashTag(idx)
var builder strings.Builder
capacity := len(e.conf.Prefix) + len(infix) + 1 + len(idxStr) + 2 + len(ch)
builder.Grow(capacity)
builder.WriteString(e.conf.Prefix)
builder.WriteString(infix)
builder.WriteByte('{')
builder.WriteString(idxStr)
builder.WriteString("}.")
builder.WriteString(ch)
return builder.String()
}
func (e *RedisMapBroker) messageChannelID(s *RedisShard, ch string) string {
if !e.useShardedPubSub(s) {
var builder strings.Builder
builder.Grow(len(e.messagePrefix) + len(ch))
builder.WriteString(e.messagePrefix)
builder.WriteString(ch)
return builder.String()
}
idx := consistentIndex(ch, e.conf.NumShardedPubSubPartitions)
idxStr := e.pubSubPartitionHashTag(idx)
capacity := len(e.messagePrefix) + 1 + len(idxStr) + 2 + len(ch)
var builder strings.Builder
builder.Grow(capacity)
builder.WriteString(e.messagePrefix)
builder.WriteByte('{')
builder.WriteString(idxStr)
builder.WriteString("}.")
builder.WriteString(ch)
return builder.String()
}
// Close closes the broker.
func (e *RedisMapBroker) Close(_ context.Context) error {
e.closeOnce.Do(func() {
close(e.closeCh)
})
return nil
}
func (e *RedisMapBroker) Clear(ctx context.Context, ch string, _ MapClearOptions) error {
s := e.getShard(ch)
shard := s.shard
client := shard.client
dataKeys := []string{
e.streamKey(shard, ch),
e.metaKey(shard, ch),
e.stateHashKey(shard, ch),
e.stateOrderKey(shard, ch),
e.stateExpireKey(shard, ch),
e.stateMetaKey(shard, ch),
}
cmds := make(rueidis.Commands, 0, 2)
cmds = append(cmds, client.B().Del().Key(dataKeys...).Build())
cleanupKey := e.cleanupRegistrationKeyForChannel(shard, ch)
cmds = append(cmds, client.B().Zrem().Key(cleanupKey).Member(ch).Build())
results := client.DoMulti(ctx, cmds...)
for _, res := range results {
if err := res.Error(); err != nil {
return err
}
}
return nil
}
func boolToStr(b bool) string {
if b {
return "1"
}
return "0"
}
// millis converts a duration to a milliseconds string.
// Zero/negative returns "0".
func millis(d time.Duration) string {
if d <= 0 {
return "0"
}
return strconv.FormatInt(d.Milliseconds(), 10)
}
// Publish publishes data to a stateful channel with optional keyed state.
func (e *RedisMapBroker) Publish(ctx context.Context, ch string, key string, opts MapPublishOptions) (MapUpdateResult, error) {
s := e.getShard(ch)
shardClient := s.shard.client
// Resolve channel options once for this operation.
chOpts, err := ResolveAndValidateMapChannelOptions(e.node.config.Map.GetMapChannelOptions, ch)
if err != nil {
return MapUpdateResult{}, err
}
// Reject CAS and Version in ephemeral mode.
if chOpts.Mode.IsEphemeral() {
if opts.ExpectedPosition != nil {
return MapUpdateResult{}, errors.New("CAS (ExpectedPosition) requires recoverable or persistent mode")
}
if opts.Version > 0 {
return MapUpdateResult{}, errors.New("version-based dedup requires recoverable or persistent mode")
}
}
// Fast path for non-history, non-idempotent, non-keyed publications.
if chOpts.Mode.IsEphemeral() && opts.IdempotencyKey == "" && key == "" {
if e.conf.SkipPubSub {
return MapUpdateResult{}, nil
}
protoPub := &protocol.Publication{
Data: opts.Data,
Info: infoToProto(opts.ClientInfo),
Tags: opts.Tags,
Time: time.Now().UnixMilli(),
}
protoPub.Delta = opts.UseDelta
pubBytes, err := protoPub.MarshalVT()
if err != nil {
return MapUpdateResult{}, err
}
payload := "0::" + convert.BytesToString(pubBytes)
chID := e.messageChannelID(s.shard, ch)
if e.useShardedPubSub(s.shard) {
cmd := shardClient.B().Spublish().Channel(chID).Message(payload).Build()
return MapUpdateResult{}, shardClient.Do(ctx, cmd).Error()
}
cmd := shardClient.B().Publish().Channel(chID).Message(payload).Build()
return MapUpdateResult{}, shardClient.Do(ctx, cmd).Error()
}
now := time.Now().UnixMilli()
// Stream publication (used for stream and pub/sub).
streamProtoPub := &protocol.Publication{
Data: opts.Data,
Info: infoToProto(opts.ClientInfo),
Tags: opts.Tags,
Time: now,
Key: key,
Score: opts.score,
}
streamBytes, err := streamProtoPub.MarshalVT()
if err != nil {
return MapUpdateResult{}, err
}
// stateBytes is nil — Lua will use streamBytes for both state and stream.
var stateBytes []byte
var resultKey string
var resultExpire string
if opts.IdempotencyKey != "" {
resultKey = e.resultCacheKey(s.shard, ch, opts.IdempotencyKey)
if opts.IdempotentResultTTL > 0 {
resultExpire = millis(opts.IdempotentResultTTL)
} else {
resultExpire = millis(e.conf.IdempotentResultTTL)
}
}
var streamKey, metaKey, stateHashKey, stateOrderKey, stateExpireKey, stateMetaKey string
streamless := chOpts.Mode.IsEphemeral()
if !streamless {
streamKey = e.streamKey(s.shard, ch)
metaKey = e.metaKey(s.shard, ch)
}
ordered := chOpts.ordered
if key != "" {
stateHashKey = e.stateHashKey(s.shard, ch)
if !streamless {
// State meta key tracks epoch for consistency between state and stream.
// In streamless mode, skip it to prevent multi-node epoch mismatch clearing state.
stateMetaKey = e.stateMetaKey(s.shard, ch)
}
if ordered {
stateOrderKey = e.stateOrderKey(s.shard, ch)
}
stateExpireKey = e.stateExpireKey(s.shard, ch)
}
metaExpire := millis(chOpts.MetaTTL)
useDelta := "0"
if opts.UseDelta {
useDelta = "1"
}
version := "0"
if opts.Version > 0 {
version = strconv.FormatUint(opts.Version, 10)
}
publishCommand := "PUBLISH"
if e.useShardedPubSub(s.shard) {
publishCommand = "SPUBLISH"
}
if e.conf.SkipPubSub {
publishCommand = ""
}
chID := e.messageChannelID(s.shard, ch)
if e.conf.SkipPubSub {
chID = ""
}
// Setup cleanup registration if KeyTTL is set (keyed state with expiration)
cleanupRegKey := ""
if chOpts.KeyTTL > 0 && key != "" && stateExpireKey != "" {
cleanupRegKey = e.cleanupRegistrationKeyForChannel(s.shard, ch)
}
// Prepare ExpectedPosition arguments for CAS
expectedOffset := ""
expectedEpoch := ""
if opts.ExpectedPosition != nil {
expectedOffset = strconv.FormatUint(opts.ExpectedPosition.Offset, 10)
expectedEpoch = opts.ExpectedPosition.Epoch
}
// In Redis Cluster, all KEYS in a Lua script must hash to the same slot. Empty string
// keys hash to slot 0, which differs from the hash-tagged real keys. Compute a slot-
// aligned nil key placeholder and substitute it for any empty KEYS. The Lua script
// converts these back to '' using ARGV[23].
nilKey := ""
if s.shard.isCluster {
nilKey = e.buildKey(s.shard, ch, ":nil:")
if streamKey == "" {
streamKey = nilKey
}
if metaKey == "" {
metaKey = nilKey
}
if resultKey == "" {
resultKey = nilKey
}
if stateHashKey == "" {
stateHashKey = nilKey
}
if stateOrderKey == "" {
stateOrderKey = nilKey
}
if stateExpireKey == "" {
stateExpireKey = nilKey
}
if stateMetaKey == "" {
stateMetaKey = nilKey
}
if cleanupRegKey == "" {
cleanupRegKey = nilKey
}
}
// Pre-compute per-key version field names for Lua.
versionField, versionEpochField := "", ""
if opts.Version > 0 && key != "" {
versionField = "v:" + key
versionEpochField = "ve:" + key
}
replies, err := e.addScript.Exec(ctx, shardClient,
[]string{
streamKey, metaKey, resultKey, stateHashKey, stateOrderKey, stateExpireKey,
stateMetaKey, cleanupRegKey,
},
[]string{
key, // message_key
convert.BytesToString(streamBytes), // message_payload (Publication - for stream and publishing)
strconv.Itoa(chOpts.StreamSize),
millis(chOpts.StreamTTL),
chID, // channel (for Lua to publish)
metaExpire,
epoch.Generate(), // new_epoch_if_empty
publishCommand,
resultExpire,
useDelta,
version,
opts.VersionEpoch,
"0", // is_remove
strconv.FormatInt(opts.score, 10),
millis(chOpts.KeyTTL),
"0", // use_hpexpire
ch, // channel_for_cleanup (for cleanup registration)
string(opts.KeyMode), // key_mode
boolToStr(opts.RefreshTTLOnSuppress), // refresh_ttl_on_suppress
expectedOffset, // expected_offset (for CAS)
expectedEpoch, // expected_epoch (for CAS)
convert.BytesToString(stateBytes), // state_payload (for state storage, empty to use message_payload)
nilKey, // nil_key (slot-aligned placeholder for unused KEYS)
versionField, // version_field (pre-computed "v:KEY" or "")
versionEpochField, // version_epoch_field (pre-computed "ve:KEY" or "")
strconv.FormatInt(now, 10), // now (current time in milliseconds)
},
).ToArray()
if err != nil {
return MapUpdateResult{}, err
}
return parseAddScriptResult(replies)
}
// Remove removes a key from keyed state state.
func (e *RedisMapBroker) Remove(ctx context.Context, ch string, key string, opts MapRemoveOptions) (MapUpdateResult, error) {
s := e.getShard(ch)
shardClient := s.shard.client
// Resolve channel options once for this operation.
chOpts, err := ResolveAndValidateMapChannelOptions(e.node.config.Map.GetMapChannelOptions, ch)
if err != nil {
return MapUpdateResult{}, err
}
// Reject CAS in ephemeral mode.
if chOpts.Mode.IsEphemeral() {
if opts.ExpectedPosition != nil {
return MapUpdateResult{}, errors.New("CAS (ExpectedPosition) requires recoverable or persistent mode")
}
}
var streamKey, metaKey string
if chOpts.Mode.HasStream() {
streamKey = e.streamKey(s.shard, ch)
metaKey = e.metaKey(s.shard, ch)
}
streamless := chOpts.Mode.IsEphemeral()
// For unpublish, we use state keys to track which keys exist
stateHashKey := e.stateHashKey(s.shard, ch)
stateExpireKey := e.stateExpireKey(s.shard, ch)
var stateMetaKey string
if !streamless {
// State meta key tracks epoch for consistency between state and stream.
// In streamless mode, skip it to prevent multi-node epoch mismatch clearing state.
stateMetaKey = e.stateMetaKey(s.shard, ch)
}
metaExpire := millis(chOpts.MetaTTL)
publishCommand := "PUBLISH"
if e.useShardedPubSub(s.shard) {
publishCommand = "SPUBLISH"
}
chID := e.messageChannelID(s.shard, ch)
if e.conf.SkipPubSub {
publishCommand = ""
chID = ""
}
now := time.Now().UnixMilli()
// Create a Publication with key and removed=true to signal removal.
// Include opts.Tags so server-side tags filtering can route the removal correctly.
protoPub := &protocol.Publication{
Key: key,
Removed: true,
Time: now,
Tags: opts.Tags,
}
pubBytes, err := protoPub.MarshalVT()
if err != nil {
return MapUpdateResult{}, err
}
// Handle idempotency key for remove operations.
var resultKey string
var resultExpire string
if opts.IdempotencyKey != "" {
resultKey = e.resultCacheKey(s.shard, ch, opts.IdempotencyKey)
if opts.IdempotentResultTTL > 0 {
resultExpire = millis(opts.IdempotentResultTTL)
} else {
resultExpire = millis(e.conf.IdempotentResultTTL)
}
}
// Prepare ExpectedPosition arguments for CAS
expectedOffset := ""
expectedEpoch := ""
if opts.ExpectedPosition != nil {
expectedOffset = strconv.FormatUint(opts.ExpectedPosition.Offset, 10)
expectedEpoch = opts.ExpectedPosition.Epoch
}
// Compute slot-aligned nil key for unused KEYS in cluster mode (see Publish for details).
nilKey := ""
stateOrderKey := ""
cleanupRegKey := ""
if s.shard.isCluster {
nilKey = e.buildKey(s.shard, ch, ":nil:")
if resultKey == "" {
resultKey = nilKey
}
stateOrderKey = nilKey
cleanupRegKey = nilKey
if streamKey == "" {
streamKey = nilKey
}
if metaKey == "" {
metaKey = nilKey
}
if stateMetaKey == "" {
stateMetaKey = nilKey
}
}
// Pre-compute per-key version field names for cleanup on remove.
versionField, versionEpochField := "", ""
if key != "" {
versionField = "v:" + key
versionEpochField = "ve:" + key
}
replies, err := e.addScript.Exec(ctx, shardClient,
[]string{
streamKey, metaKey, resultKey,
stateHashKey,
stateOrderKey,
stateExpireKey,
stateMetaKey,
cleanupRegKey,
},
[]string{
key, // message_key
convert.BytesToString(pubBytes), // message_payload (Publication with Removed=true for stream)
strconv.Itoa(chOpts.StreamSize),
millis(chOpts.StreamTTL),
chID, // channel (for Lua to publish)
metaExpire,
epoch.Generate(), // new_epoch_if_empty
publishCommand,
resultExpire, // result_key_expire
"0", "0", "", // use_delta, version, version_epoch
"1", // is_leave (this triggers removal)
"0", // score
"0", // map_member_ttl
"0", // use_hpexpire
"", // channel_for_cleanup (not used for unpublish)
"", // key_mode (not used for unpublish)
"0", // refresh_ttl_on_suppress (not used for unpublish)
expectedOffset, // expected_offset (for CAS)
expectedEpoch, // expected_epoch (for CAS)
"", // state_payload (not used for unpublish)
nilKey, // nil_key (slot-aligned placeholder for unused KEYS)
versionField, // version_field (pre-computed "v:KEY" or "")
versionEpochField, // version_epoch_field (pre-computed "ve:KEY" or "")
strconv.FormatInt(now, 10), // now (current time in milliseconds)
},
).ToArray()
if err != nil {
return MapUpdateResult{}, err
}
return parseAddScriptResult(replies)
}
// ReadState retrieves state entries with per-entry revisions for a channel.
// Each entry includes its revision so client can filter: entry.Revision <= state_revision.
// If opts.Revision is provided and epoch changed, returns empty entries.
// Returns entries, stream position, next cursor for pagination, and error.
// Cursor "0" or "" means end of iteration.
func (e *RedisMapBroker) ReadState(ctx context.Context, ch string, opts MapReadStateOptions) (MapStateResult, error) {
// Resolve channel options once for this operation.
chOpts, err := ResolveAndValidateMapChannelOptions(e.node.config.Map.GetMapChannelOptions, ch)
if err != nil {
return MapStateResult{}, err
}
// Handle single key lookup (Key filter) — takes priority over Limit.
if opts.Key != "" {
return e.readSingleKeyWithOpts(ctx, ch, opts, chOpts)
}
// Limit=0: return only stream position (no entries).
if opts.Limit == 0 {
streamResult, err := e.ReadStream(ctx, ch, MapReadStreamOptions{
Filter: StreamFilter{Limit: 0},
})
if err != nil {
return MapStateResult{}, err
}
return MapStateResult{Position: streamResult.Position}, nil
}
if chOpts.ordered {
return e.readOrderedState(ctx, ch, opts, chOpts)
}
return e.readUnorderedState(ctx, ch, opts, chOpts)
}
//func (e *RedisMapBroker) ReadStateZero(ctx context.Context, ch string, opts MapReadStateOptions) (MapStateResult, error) {
// // Resolve channel options once for this operation.
// chOpts, err := ResolveAndValidateMapChannelOptions(e.node.config.Map.GetMapChannelOptions, ch)
// if err != nil {
// return MapStateResult{}, err
// }
//
// // Handle single key lookup (Key filter) — takes priority over Limit.
// if opts.Key != "" {
// return e.readSingleKeyWithOpts(ctx, ch, opts, chOpts)
// }
// // Limit=0: return only stream position (no entries).
// if opts.Limit == 0 {
// streamResult, err := e.ReadStream(ctx, ch, MapReadStreamOptions{
// Filter: StreamFilter{Limit: 0},
// })
// if err != nil {
// return MapStateResult{}, err
// }
// return MapStateResult{Position: streamResult.Position}, nil
// }
// if chOpts.ordered {
// return e.readOrderedState(ctx, ch, opts, chOpts)
// }
// return e.readUnorderedStateZero(ctx, ch, opts, chOpts)
//}
// readSingleKeyWithOpts retrieves a single key from the state using HGET instead of HSCAN.
// This is more efficient for single key lookups and supports CAS read-modify-write patterns.
func (e *RedisMapBroker) readSingleKeyWithOpts(ctx context.Context, ch string, opts MapReadStateOptions, chOpts MapChannelOptions) (MapStateResult, error) {
s := e.getShard(ch)
shardClient := s.shard.client
stateHashKey := e.stateHashKey(s.shard, ch)
streamless := chOpts.Mode.IsEphemeral()
if streamless {
// Streamless mode: just read the key, no meta needed.
valBytes, err := shardClient.Do(ctx, shardClient.B().Hget().Key(stateHashKey).Field(opts.Key).Build()).AsBytes()
keyNotFound := rueidis.IsRedisNil(err)
if err != nil && !keyNotFound {
return MapStateResult{}, err
}
if keyNotFound || len(valBytes) == 0 {
return MapStateResult{}, nil
}
entryOffset, _, payload, err := parseStateValue(valBytes)
if err != nil {
return MapStateResult{}, fmt.Errorf("failed to parse state value: %w", err)
}
var protoPub protocol.Publication
if err := protoPub.UnmarshalVT(payload); err != nil {
return MapStateResult{}, fmt.Errorf("failed to unmarshal publication: %w", err)
}
pub := pubFromProto(&protoPub)
pub.Key = opts.Key
pub.Offset = entryOffset
return MapStateResult{Publications: []*Publication{pub}}, nil
}
metaKey := e.metaKey(s.shard, ch)