-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathclient_map.go
More file actions
1696 lines (1567 loc) · 62.2 KB
/
Copy pathclient_map.go
File metadata and controls
1696 lines (1567 loc) · 62.2 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"
"errors"
"slices"
"time"
"github.com/centrifugal/centrifuge/internal/convert"
"github.com/centrifugal/centrifuge/internal/filter"
"github.com/centrifugal/centrifuge/internal/recovery"
"github.com/centrifugal/protocol"
"github.com/segmentio/encoding/json"
)
// Map subscriptions provide synchronized state across clients. Unlike normal pub/sub
// subscriptions, map subscriptions maintain a state of key-value entries plus a stream
// of changes for recovery.
//
// Subscription protocol phases:
//
// 1. State phase: Client paginates through current key-value state. Each response
// includes a stream position (offset/epoch) marking the state's point in time.
//
// 2. Stream phase (optional): Client paginates through stream history to catch up on
// changes since the state was taken. May skip if state is up-to-date.
//
// 3. Live phase: Server coordinates the transition to real-time:
// - Starts buffering pub/sub messages before subscribing
// - Subscribes to pub/sub channel
// - Reads final stream catch-up since client's position
// - Merges stream with buffered messages (deduplication by offset)
// - Sends merged publications to client and enables live updates
//
// This buffering mechanism ensures no messages are lost during the gap between
// the final stream read and pub/sub subscription becoming active.
//
// Key differences from normal subscriptions:
//
// EnablePositioning and EnableRecovery are auto-set from the channel's Mode
// (configured in MapChannelOptions via GetMapChannelOptions resolver):
//
// - MapModeEphemeral: Streamless mode. No stream history is maintained.
// State is always available, but recovery on reconnect requires a full state re-sync.
// CAS (ExpectedPosition) and Version-based dedup are not available.
// EnablePositioning and EnableRecovery are both set to false.
//
// - MapModeRecoverable / MapModePersistent: Stream mode. Publications are tracked with
// offsets, stream history is maintained, and clients can recover missed publications
// on reconnect. CAS and Version features are available.
// EnablePositioning and EnableRecovery are both set to true.
//
// When Type is SubscriptionTypeMap in SubscribeOptions, the subscription gets:
// - State delivery (always)
// - Stream position tracking (if Mode.HasStream())
// - Stream-based recovery (if Mode.HasStream())
// - Delta compression support for stream catch-up (if negotiated)
// - Tags filtering for stream and live publications (if allowed)
//
// Map Presence Subscriptions
//
// Map presence subscriptions allow clients to watch who is online in a channel.
// They are a special type of map subscription that tracks client or user presence.
//
// Presence is configured using full channel names:
//
// - MapClientPresenceChannel (e.g., "presence-clients:game1") - When set, client presence
// is published to this channel. Each entry is keyed by client ID and contains
// full ClientInfo. Use for tracking individual connections.
//
// - MapUserPresenceChannel (e.g., "presence-users:game1") - When set, user presence is
// published to this channel. Each entry is keyed by user ID with minimal data.
// Provides natural deduplication when users have multiple connections.
//
// Authorization flow:
//
// Presence subscriptions go through OnSubscribe handler with SubscribeEvent.Type set
// to SubscriptionTypeMap (same as map data subscriptions). The handler can use the
// channel name to distinguish presence channels from data channels.
//
// Client subscribes to presence channel -> OnSubscribe called with Type=SubscriptionTypeMap
// -> Handler returns SubscribeReply{Options: SubscribeOptions{Type: SubscriptionTypeMap}}
// -> Subscription proceeds
//
// Presence data lifecycle:
//
// - On subscribe (with configured presence prefix): presence published
// - Periodically refreshed via TTL to handle connection drops
// - On unsubscribe/disconnect: presence removed (with stream entry for real-time notification)
// - TTL expiration: automatic cleanup if client disappears without clean disconnect
// Map subscription phase constants.
const (
MapPhaseLive int32 = 0 // Join live pub/sub, switch to real-time streaming (default)
MapPhaseStream int32 = 1 // Paginating over stream (history catch-up)
MapPhaseState int32 = 2 // Paginating over state (map state)
)
// subscribeResultTypeMap is the Type value for map subscriptions in protocol.SubscribeResult.
const subscribeResultTypeMap = 1
const (
// defaultMapPageSize is the default page size when client does not specify one.
defaultMapPageSize = 100
// defaultMapMinPageSize is the default minimum page size for map pagination.
defaultMapMinPageSize = 100
// defaultMapMaxPageSize is the default maximum page size for map pagination.
defaultMapMaxPageSize = 1000
)
// validateAndCreateTagsFilter validates the tags filter from the request and creates a tagsFilter.
// Returns (nil, nil) if req.Tf is nil. Returns (nil, error) if validation fails.
func (c *Client) validateAndCreateTagsFilter(req *protocol.SubscribeRequest, allowTagsFilter bool, channel string) (*tagsFilter, error) {
if req.Tf == nil {
return nil, nil
}
if !allowTagsFilter {
c.node.logger.log(newLogEntry(LogLevelInfo, "tags filter not allowed for map channel", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
return nil, ErrorBadRequest
}
if err := filter.Validate(req.Tf); err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "invalid tags filter for map channel", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
return nil, ErrorBadRequest
}
return &tagsFilter{
filter: req.Tf,
hash: filter.Hash(req.Tf),
}, nil
}
// escapeStateForDelta JSON-escapes Data in state publications for delta-enabled JSON
// transport. This ensures the client receives data as JSON strings (matching the format
// used for real-time and recovered publications), so it can store exact bytes for delta.
func escapeStateForDelta(pubs []*protocol.Publication, deltaEnabled bool, isJSON bool) []*protocol.Publication {
if !deltaEnabled || !isJSON {
return pubs
}
for i, pub := range pubs {
if len(pub.Data) > 0 {
pubs[i] = copyMapPubWithData(pub, json.Escape(convert.BytesToString(pub.Data)), false)
}
}
return pubs
}
// mapSubscribeState tracks state for map subscriptions that are still loading.
type mapSubscribeState struct {
options SubscribeOptions // From OnSubscribe callback
epoch string // Epoch from first response (for validation)
offset uint64 // Offset from first state page (frozen for consistency)
startedAt int64 // UnixNano when catch-up started (for timeout)
streamStart uint64 // Stream top captured on first stream request
offsetCaptured bool // True after offset is captured (since 0 is valid offset)
streamStartCaptured bool // True after streamStart is captured (since 0 is valid offset)
isPresence bool // True if this is a presence subscription
subscribingCh chan struct{} // Closed when subscription completes (for race handling)
subGen uint64 // Subscription generation, stable from this reservation through the live c.channels entry and the hub subInfo. See subInfo.subGen.
tagsFilter *tagsFilter // Client tags filter for state/stream publications
serverTagsFilter *tagsFilter // Server tags filter for state/stream publications
}
// handleMapSubscribeCommand handles the full map subscribe command flow:
// validates, checks for continuation, calls OnSubscribe handler for initial requests.
func (c *Client) handleMapSubscribeCommand(
req *protocol.SubscribeRequest,
cmd *protocol.Command,
started time.Time,
rw *replyWriter,
) error {
if c.eventHub.subscribeHandler == nil {
return ErrorNotAvailable
}
_, replyError, disconnect := c.validateSubscribeRequest(req)
if disconnect != nil || replyError != nil {
if disconnect != nil {
return *disconnect
}
return replyError
}
// Sweep expired catch-ups on other channels. Handles abandoned catch-ups where
// the client stopped sending requests but stayed connected. The current channel
// is skipped — its expiry is checked below with a proper DisconnectStale.
c.sweepExpiredMapSubscribing(req.Channel)
// For map subscription continuation requests (pagination or non-state phase with existing state),
// bypass the OnSubscribe callback - we already authorized on the first request.
c.mu.RLock()
state, hasState := c.mapSubscribing[req.Channel]
c.mu.RUnlock()
if req.Cursor != "" {
if !hasState {
return ErrorPermissionDenied
}
catchUpChOpts, _ := c.node.resolveMapChannelOptions(req.Channel)
if c.isMapCatchUpExpired(state, catchUpChOpts) {
c.node.logger.log(newLogEntry(LogLevelInfo, "map subscribe catch-up timeout", map[string]any{
"channel": req.Channel, "user": c.user, "client": c.uid,
}))
c.cleanupMapSubscribing(req.Channel)
return DisconnectSlow
}
reply := SubscribeReply{Options: state.options}
if handleErr := c.handleMapSubscribe(req, reply, cmd, started, rw); handleErr != nil {
c.writeDisconnectOrErrorFlush(req.Channel, protocol.FrameTypeSubscribe, cmd, handleErr, started, rw)
}
return nil
}
if req.Phase != MapPhaseState && hasState {
catchUpChOpts, _ := c.node.resolveMapChannelOptions(req.Channel)
if c.isMapCatchUpExpired(state, catchUpChOpts) {
c.node.logger.log(newLogEntry(LogLevelInfo, "map subscribe catch-up timeout", map[string]any{
"channel": req.Channel, "user": c.user, "client": c.uid,
}))
c.cleanupMapSubscribing(req.Channel)
return DisconnectSlow
}
reply := SubscribeReply{Options: state.options}
if handleErr := c.handleMapSubscribe(req, reply, cmd, started, rw); handleErr != nil {
c.writeDisconnectOrErrorFlush(req.Channel, protocol.FrameTypeSubscribe, cmd, handleErr, started, rw)
}
return nil
}
event := SubscribeEvent{
Channel: req.Channel,
Token: req.Token,
Data: req.Data,
Type: SubscriptionType(req.Type),
}
// No reservation cleanup here: map subscribes reserve c.mapSubscribing, not
// c.channels (validateSubscribeRequest returns before the regular install for
// Type >= 1), and c.channels is only written by commitSubscription — which is
// followed by a nil return on every path. So there is never a c.channels entry
// of this subscribe's to undo, and removing "the entry for this channel" could
// only delete a reservation belonging to a different, concurrent subscribe.
// The map reservation and hub entry are rolled back inside the phase handlers,
// identity-matched via cleanupMapSubscribingState.
cb := func(reply SubscribeReply, err error) {
if err != nil {
c.writeDisconnectOrErrorFlush(req.Channel, protocol.FrameTypeSubscribe, cmd, err, started, rw)
return
}
if reply.Options.Type != event.Type {
c.writeDisconnectOrErrorFlush(req.Channel, protocol.FrameTypeSubscribe, cmd, ErrorBadRequest, started, rw)
return
}
if handleErr := c.handleMapSubscribe(req, reply, cmd, started, rw); handleErr != nil {
c.writeDisconnectOrErrorFlush(req.Channel, protocol.FrameTypeSubscribe, cmd, handleErr, started, rw)
}
}
c.eventHub.subscribeHandler(event, cb)
return nil
}
// handleMapSubscribe routes map subscription requests to the appropriate phase handler.
// This is called after OnSubscribe callback has authorized the map subscription.
func (c *Client) handleMapSubscribe(
req *protocol.SubscribeRequest,
reply SubscribeReply,
cmd *protocol.Command,
started time.Time,
rw *replyWriter,
) error {
channel := req.Channel
// Auto-set positioning flags from Mode.
chOpts, err := c.node.resolveMapChannelOptions(channel)
if err != nil {
c.cleanupMapSubscribing(channel)
return err
}
if chOpts.Mode.HasStream() {
reply.Options.EnablePositioning = true
reply.Options.EnableRecovery = true
} else {
reply.Options.EnablePositioning = false
reply.Options.EnableRecovery = false
}
// Route based on phase.
switch req.Phase {
case MapPhaseState:
return c.handleMapStatePhase(req, reply, cmd, started, rw)
case MapPhaseStream:
return c.handleMapStreamPhase(req, reply, cmd, started, rw)
case MapPhaseLive:
return c.handleMapLivePhase(req, reply, cmd, started, rw)
default:
c.cleanupMapSubscribing(channel)
c.node.logger.log(newLogEntry(LogLevelInfo, "invalid map phase", map[string]any{
"channel": channel, "phase": req.Phase, "user": c.user, "client": c.uid,
}))
return ErrorBadRequest
}
}
// handleMapStatePhase handles stateless state pagination.
func (c *Client) handleMapStatePhase(
req *protocol.SubscribeRequest,
reply SubscribeReply,
cmd *protocol.Command,
started time.Time,
rw *replyWriter,
) error {
channel := req.Channel
// Acquire pagination lock for this channel.
if !c.acquireMapPaginationLock(channel) {
return ErrorConcurrentPagination
}
defer c.releaseMapPaginationLock(channel)
// Track map subscription state on first state request (no cursor).
if req.Cursor == "" {
// Validate and store tags filter on first request.
tf, err := c.validateAndCreateTagsFilter(req, reply.Options.AllowTagsFilter, channel)
if err != nil {
return err
}
c.mu.Lock()
if c.mapSubscribing == nil {
c.mapSubscribing = make(map[string]*mapSubscribeState)
}
if _, exists := c.mapSubscribing[channel]; exists {
// A concurrent initial subscribe for this channel installed its state
// between validateSubscribeRequest's check and this lock (pagination
// spans multiple commands, so the pagination lock alone does not close
// that window). Overwriting would orphan the existing reservation's
// subscribingCh — an unsubscribe waiting on it would hit the 5s timeout
// and force-disconnect the client — and hand this request a generation
// that no longer matches the map entry. Reject the duplicate, same as
// the recovery-mode guard in handleMapStreamPhase.
c.mu.Unlock()
return ErrorAlreadySubscribed
}
var stf *tagsFilter
if reply.Options.ServerTagsFilter != nil {
stf = &tagsFilter{
filter: reply.Options.ServerTagsFilter,
hash: filter.Hash(reply.Options.ServerTagsFilter),
}
}
c.mapSubscribing[channel] = &mapSubscribeState{
options: reply.Options,
startedAt: time.Now().UnixNano(),
isPresence: reply.Options.Type.IsMapPresence(),
subscribingCh: make(chan struct{}),
subGen: c.subGenCounter.Add(1),
tagsFilter: tf,
serverTagsFilter: stf,
}
c.mu.Unlock()
} else {
// Subsequent request - verify we have authorization.
c.mu.RLock()
state, ok := c.mapSubscribing[channel]
c.mu.RUnlock()
if !ok {
c.node.logger.log(newLogEntry(LogLevelInfo, "map subscription not authorized", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
return ErrorPermissionDenied
}
// Use stored options.
reply.Options = state.options
}
// Build read options.
chOpts, _ := c.node.resolveMapChannelOptions(channel)
limit := c.getMapPageSize(req, chOpts)
opts := MapReadStateOptions{
AllowCached: true, // Use cache for subscription state delivery
Cursor: req.Cursor,
Limit: limit,
Asc: req.Asc,
}
// If client provided position, validate epoch.
if req.Offset > 0 || req.Epoch != "" {
opts.Revision = &StreamPosition{
Offset: req.Offset,
Epoch: req.Epoch,
}
}
// Read state page.
stateResult, err := c.node.MapStateRead(c.ctx, channel, opts)
if err != nil {
if errors.Is(err, ErrorUnrecoverablePosition) {
c.cleanupMapSubscribing(channel)
return ErrorUnrecoverablePosition
}
c.node.logger.log(newErrorLogEntry(err, "error reading map state", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
c.cleanupMapSubscribing(channel)
return ErrorInternal
}
pubs := stateResult.Publications
streamPos := stateResult.Position
nextCursor := stateResult.Cursor
// Get state for tags filter and epoch update.
c.mu.RLock()
state := c.mapSubscribing[channel]
c.mu.RUnlock()
// Capture epoch and offset on first page (frozen for consistency).
// The offset is used to return a consistent value on all subsequent pages,
// ensuring the stream catch-up starts from where the first state page was read.
if req.Cursor == "" && state != nil {
c.mu.Lock()
state.epoch = streamPos.Epoch
state.offset = streamPos.Offset
state.offsetCaptured = true
c.mu.Unlock()
}
// Filter state entries modified after client's position (for subsequent pages).
// This ensures entries that were updated after the first page was read don't appear
// in later pages, which would cause duplicates when client catches up from stream.
if opts.Revision != nil {
filteredPubs := make([]*Publication, 0, len(pubs))
for _, pub := range pubs {
// Keep entries with offset <= client's saved offset.
// These are guaranteed to not appear in stream catch-up.
if pub.Offset <= opts.Revision.Offset {
filteredPubs = append(filteredPubs, pub)
}
}
pubs = filteredPubs
}
// Apply server tags filter to state publications.
if state != nil && state.serverTagsFilter != nil {
filteredPubs := make([]*Publication, 0, len(pubs))
for _, pub := range pubs {
match, _ := filter.Match(state.serverTagsFilter.filter, pub.Tags)
if match {
filteredPubs = append(filteredPubs, pub)
}
}
pubs = filteredPubs
}
// Apply client tags filter to state publications.
if state != nil && state.tagsFilter != nil {
filteredPubs := make([]*Publication, 0, len(pubs))
for _, pub := range pubs {
match, _ := filter.Match(state.tagsFilter.filter, pub.Tags)
if match {
filteredPubs = append(filteredPubs, pub)
}
}
pubs = filteredPubs
}
// Check for direct STATE→LIVE transition on last page.
if nextCursor == "" {
if state == nil {
// Disconnect raced with MapStateRead — subscription is being cleaned up.
return nil
}
positioning := state.options.EnablePositioning || state.options.EnableRecovery
// Use frozen offset from first page when available (multi-page pagination).
// stateResult.Position reflects the stream top at the time of THIS page read,
// but publications made during pagination won't appear in state pages AND would
// be missed by stream catch-up if we use the current page's offset. The frozen
// offset from the first page ensures stream catch-up covers the full gap.
effectivePos := streamPos
if state.offsetCaptured && req.Cursor != "" {
effectivePos = StreamPosition{Offset: state.offset, Epoch: state.epoch}
}
if !positioning {
// Streamless: always go LIVE on last page (no stream to paginate through).
return c.handleMapStateToLive(req, reply, state, cmd, started, rw, pubs, effectivePos)
}
// Positioned: skip STREAM phase if stream hasn't advanced much.
currentStreamPos, err := c.node.mapStreamPosition(c.ctx, channel)
if err == nil {
// Use limit as threshold - if stream is within one page, go LIVE.
if effectivePos.Offset+uint64(limit) >= currentStreamPos.Offset {
return c.handleMapStateToLive(req, reply, state, cmd, started, rw, pubs, effectivePos)
}
}
// If error or stream too far ahead, fall through to normal STATE response.
}
// Use frozen offset from first page for consistency. On subsequent pages,
// stream.Top() may have advanced, but we return the first page's offset so
// the client's stream catch-up starts from a consistent point.
responseOffset := streamPos.Offset
if state != nil && state.offsetCaptured && req.Cursor != "" {
responseOffset = state.offset
}
// Build response.
res := &protocol.SubscribeResult{
Type: subscribeResultTypeMap,
Phase: MapPhaseState,
Cursor: nextCursor,
Epoch: streamPos.Epoch,
Offset: responseOffset,
}
// Convert state entries (use State field, not Publications).
stateProtos := make([]*protocol.Publication, 0, len(pubs))
for _, pub := range pubs {
stateProtos = append(stateProtos, pubToProto(pub))
}
// JSON-escape state data for delta-enabled JSON transport so the client can
// store exact bytes for subsequent delta application.
deltaWillBeEnabled := req.Delta != "" && state != nil && slices.Contains(state.options.AllowedDeltaTypes, DeltaType(req.Delta))
res.State = escapeStateForDelta(stateProtos, deltaWillBeEnabled, c.transport.Protocol() == ProtocolTypeJSON)
return c.writeMapSubscribeReply(channel, cmd, res, started, rw)
}
// mapTransitionToLiveParams holds parameters that differ between the four
// methods that transition a map subscription to the live phase. The shared
// protocol (buffer -> subscribe -> stream-read -> merge -> respond -> finalize)
// is implemented once in handleMapTransitionToLive.
type mapTransitionToLiveParams struct {
sincePosition StreamPosition // Stream position to read from
statePubs []*Publication // State publications for the response (nil when not applicable)
allowStreamless bool // Whether streamless mode is allowed
isRecovery bool // Whether this is a recovery (sets WasRecovering/Recovered)
tagsFilterFromState *tagsFilter // Inherited client tags filter from prior phase
serverTagsFilterFromState *tagsFilter // Inherited server tags filter from prior phase
metricsAction string // Metrics action string
// expectedState is the mapSubscribing reservation this transition started
// from, or nil for a direct-to-LIVE recovery join that never ran a
// STATE/STREAM phase. Non-nil: the transition proceeds only while that exact
// reservation is still installed (a timed-out unsubscribe may have consumed
// it, and a fresh subscribe may have re-reserved the channel with a new
// generation). Nil: a reservation is installed on entry so the commit's
// generation check and the unsubscribe wait-gate cover this path too.
expectedState *mapSubscribeState
}
// handleMapTransitionToLive implements the shared buffer-subscribe-read-merge protocol
// used by all four methods that transition a map subscription to the live phase:
// handleMapStateToLive, handleMapStreamToLive, and handleMapRecoveryJoin.
func (c *Client) handleMapTransitionToLive(
req *protocol.SubscribeRequest,
reply SubscribeReply,
opts SubscribeOptions,
isPresence bool,
cmd *protocol.Command,
started time.Time,
rw *replyWriter,
params mapTransitionToLiveParams,
) error {
channel := req.Channel
// One generation per map subscription attempt, taken from the mapSubscribing
// reservation so it is stable from reservation through the live c.channels
// entry and the hub subInfo. This lets a racing unsubscribe identity-match and
// avoid clobbering a fresh concurrent map resubscribe (see subInfo.subGen).
c.mu.Lock()
var subGen uint64
// ourState is the reservation this transition owns; every rollback below
// identity-matches against it so a stalled transition can never tear down a
// fresh resubscribe's reservation.
var ourState *mapSubscribeState
st, hasReservation := c.mapSubscribing[channel]
if params.expectedState != nil {
// State/stream → live: the transition must still own its reservation. A
// timed-out unsubscribe may have consumed it — and a fresh subscribe may
// have installed a new one — while this transition was in flight. Pointer
// identity, same check unsubscribe and cleanupMapSubscribing use.
if !hasReservation || st != params.expectedState {
c.mu.Unlock()
return ErrorInternal
}
subGen = st.subGen
if subGen == 0 {
// Reservation without a generation (hand-constructed in tests;
// production phases always mint one). Stamp it so the commit's
// identity check holds.
subGen = c.subGenCounter.Add(1)
st.subGen = subGen
}
ourState = st
} else if hasReservation {
// Direct-to-LIVE recovery join racing another subscribe that already
// reserved the channel — reject the duplicate, same as the guards in the
// state and stream phases.
c.mu.Unlock()
return ErrorAlreadySubscribed
} else {
// Direct-to-LIVE recovery join: no STATE/STREAM phase ran, so no
// reservation exists. Install one — it carries the generation the commit
// identity-checks, and its subscribingCh lets a concurrent unsubscribe
// wait for this transition instead of racing it. commitSubscription
// consumes it (and the caller closes subscribingCh) on every exit path
// below via cleanupMapSubscribing/commit.
if c.mapSubscribing == nil {
c.mapSubscribing = make(map[string]*mapSubscribeState)
}
subGen = c.subGenCounter.Add(1)
ourState = &mapSubscribeState{
options: opts,
startedAt: time.Now().UnixNano(),
isPresence: isPresence,
subscribingCh: make(chan struct{}),
subGen: subGen,
epoch: req.Epoch,
tagsFilter: params.tagsFilterFromState,
serverTagsFilter: params.serverTagsFilterFromState,
}
c.mapSubscribing[channel] = ourState
}
c.mu.Unlock()
// rollback undoes everything this transition installed, in the order the
// rest of the file uses (buffer → hub → reservation). Identity-matched on
// ourState and subGen so it is a no-op for state a concurrent resubscribe
// owns.
rollback := func(stopBuffering bool) {
if stopBuffering {
c.pubSubSync.StopBuffering(channel)
}
_ = c.node.removeSubscription(channel, c, subGen)
c.cleanupMapSubscribingState(channel, ourState)
}
// Build subscription info first, validate before subscribing.
useID := opts.AllowChannelCompaction && req.Flag&subscriptionFlagChannelCompression != 0
sub := subInfo{client: c, deltaType: deltaTypeNone, useID: useID, isMap: true, subGen: subGen}
// Process tags filter if provided.
if req.Tf != nil {
tf, err := c.validateAndCreateTagsFilter(req, opts.AllowTagsFilter, channel)
if err != nil {
// Nothing added to the hub or buffered yet — only the reservation.
c.cleanupMapSubscribingState(channel, ourState)
return err
}
sub.tagsFilter = tf
} else if params.tagsFilterFromState != nil {
// Use tags filter from prior phase if not provided in this request.
sub.tagsFilter = params.tagsFilterFromState
}
// Server tags filter is always inherited from the state set at subscribe time.
if params.serverTagsFilterFromState != nil {
sub.serverTagsFilter = params.serverTagsFilterFromState
}
// Negotiate delta type if requested.
var deltaEnabled bool
if req.Delta != "" {
dt := DeltaType(req.Delta)
if slices.Contains(opts.AllowedDeltaTypes, dt) {
deltaEnabled = true
sub.deltaType = dt
}
}
// Start coordination: buffer -> add subscription -> read stream -> merge.
c.pubSubSync.StartBuffering(channel)
chanID, err := c.node.addSubscription(channel, sub)
if err != nil {
// addSubscription failed, so there is no hub entry to remove here.
c.pubSubSync.StopBuffering(channel)
c.cleanupMapSubscribingState(channel, ourState)
c.node.logger.log(newErrorLogEntry(err, "error adding map subscription", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
var clientErr *Error
if errors.As(err, &clientErr) && !errors.Is(clientErr, ErrorInternal) {
return clientErr
}
return ErrorInternal
}
positioning := opts.EnablePositioning || opts.EnableRecovery
var recoveredPubs []*protocol.Publication
var latestOffset uint64
streamPos := params.sincePosition
if positioning {
// Positioned mode: read stream from sincePosition to catch any updates.
chOpts, _ := c.node.resolveMapChannelOptions(channel)
liveTransitionLimit := chOpts.LiveTransitionMaxPublicationLimit
if liveTransitionLimit == 0 {
// Default to MaxPageSize.
liveTransitionLimit = chOpts.MaxPageSize
if liveTransitionLimit <= 0 {
liveTransitionLimit = defaultMapMaxPageSize
}
}
streamLimit := -1 // No limit by default.
if liveTransitionLimit > 0 {
streamLimit = liveTransitionLimit
}
// Read limit+1 to distinguish "exactly at limit" from "too far behind".
readLimit := streamLimit
if readLimit > 0 {
readLimit = streamLimit + 1
}
streamOpts := MapReadStreamOptions{
Filter: StreamFilter{
Since: &StreamPosition{
Offset: params.sincePosition.Offset,
Epoch: params.sincePosition.Epoch,
},
Limit: readLimit,
},
AllowCached: true,
}
streamResult, err := c.node.MapStreamRead(c.ctx, channel, streamOpts)
if err != nil {
rollback(true)
if errors.Is(err, ErrorUnrecoverablePosition) {
return ErrorUnrecoverablePosition
}
c.node.logger.log(newErrorLogEntry(err, "error reading stream for live phase", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
return ErrorInternal
}
pubs := streamResult.Publications
streamPos = streamResult.Position
// If recovering and the epoch doesn't match, force full re-subscribe.
// This covers: empty→real (client never had epoch), real→empty (after MapClear
// deleted meta row), and real→different (after Clear + new publications).
//
// For state→live (isRecovery=false), params.sincePosition.Epoch is the
// epoch returned by the broker during the state phase. A mismatch here
// means the broker flipped epochs between state and stream reads (e.g.
// MapClear or meta-TTL eviction landed in between); without this check
// the client would merge the prior-epoch state with new-epoch live pubs
// and silently lose any keys not republished. The `!= ""` guard keeps
// ephemeral-mode subscribes (which have no epoch) working.
if (params.isRecovery || params.sincePosition.Epoch != "") && params.sincePosition.Epoch != streamPos.Epoch {
rollback(true)
return ErrorUnrecoverablePosition
}
// If we got more than the limit, client is too far behind.
if streamLimit > 0 && len(pubs) > streamLimit {
rollback(true)
return ErrorUnrecoverablePosition
}
// Convert stream publications to protocol format.
for _, pub := range pubs {
recoveredPubs = append(recoveredPubs, pubToProto(pub))
}
// Lock buffer and read buffered publications.
bufferedPubs := c.pubSubSync.LockBufferAndReadBuffered(channel)
// Merge recovered and buffered publications.
var maxSeenOffset uint64
var okMerge bool
recoveredPubs, maxSeenOffset, okMerge = recovery.MergePublications(recoveredPubs, bufferedPubs)
if !okMerge {
rollback(true)
return &DisconnectInsufficientState
}
// Update offset if we saw higher.
latestOffset = streamPos.Offset
if maxSeenOffset > latestOffset {
latestOffset = maxSeenOffset
}
if len(recoveredPubs) > 0 {
lastPubOffset := recoveredPubs[len(recoveredPubs)-1].Offset
if lastPubOffset > latestOffset {
latestOffset = lastPubOffset
}
}
// Apply server tags filter to stream publications (after offset calculation).
if sub.serverTagsFilter != nil {
filteredPubs := make([]*protocol.Publication, 0, len(recoveredPubs))
for _, pub := range recoveredPubs {
match, _ := filter.Match(sub.serverTagsFilter.filter, pub.Tags)
if match {
filteredPubs = append(filteredPubs, pub)
}
}
recoveredPubs = filteredPubs
}
// Apply client tags filter to stream publications.
if sub.tagsFilter != nil {
filteredPubs := make([]*protocol.Publication, 0, len(recoveredPubs))
for _, pub := range recoveredPubs {
match, _ := filter.Match(sub.tagsFilter.filter, pub.Tags)
if match {
filteredPubs = append(filteredPubs, pub)
}
}
recoveredPubs = filteredPubs
}
// Apply delta compression to recovered publications if enabled.
if deltaEnabled && req.Delta == string(DeltaTypeFossil) {
recoveredPubs = c.makeRecoveredMapPubsDeltaFossil(recoveredPubs)
}
} else if params.allowStreamless {
// Streamless mode: use buffered publications directly (no stream read, no merge).
bufferedPubs := c.pubSubSync.LockBufferAndReadBuffered(channel)
recoveredPubs = bufferedPubs
// Apply server tags filter to buffered publications. Buffered live pubs are
// captured before per-subscriber filtering, so the server filter must be
// applied here (AND semantics) or streamless recovery leaks server-filtered
// publications.
if sub.serverTagsFilter != nil {
filteredPubs := make([]*protocol.Publication, 0, len(recoveredPubs))
for _, pub := range recoveredPubs {
match, _ := filter.Match(sub.serverTagsFilter.filter, pub.Tags)
if match {
filteredPubs = append(filteredPubs, pub)
}
}
recoveredPubs = filteredPubs
}
// Apply client tags filter to buffered publications.
if sub.tagsFilter != nil {
filteredPubs := make([]*protocol.Publication, 0, len(recoveredPubs))
for _, pub := range recoveredPubs {
match, _ := filter.Match(sub.tagsFilter.filter, pub.Tags)
if match {
filteredPubs = append(filteredPubs, pub)
}
}
recoveredPubs = filteredPubs
}
}
// Convert state publications to protocol format (if any).
isJSON := c.transport.Protocol() == ProtocolTypeJSON
var protoStatePubs []*protocol.Publication
if len(params.statePubs) > 0 {
protoStatePubs = make([]*protocol.Publication, 0, len(params.statePubs))
for _, pub := range params.statePubs {
protoStatePubs = append(protoStatePubs, pubToProto(pub))
}
protoStatePubs = escapeStateForDelta(protoStatePubs, deltaEnabled, isJSON)
}
// Build response with phase=0 (LIVE).
res := &protocol.SubscribeResult{
Type: subscribeResultTypeMap,
Phase: MapPhaseLive,
Epoch: streamPos.Epoch,
Offset: latestOffset,
Delta: deltaEnabled,
State: protoStatePubs,
Publications: recoveredPubs,
}
if d := opts.ClientPublishDebounceInterval; d > 0 {
res.PublishDebounce = uint32(d.Milliseconds())
}
if positioning {
res.Recoverable = true
}
if params.isRecovery {
res.WasRecovering = req.Recover
if req.Recover {
res.Recovered = true
}
}
if chanID > 0 {
res.Id = chanID
}
// Encode reply first so an encode failure is surfaced before we touch
// c.channels — keeps the rollback path simple.
protoReply, err := c.getSubscribeCommandReply(res)
if err != nil {
rollback(true)
c.node.logger.log(newErrorLogEntry(err, "error encoding map subscribe reply", map[string]any{
"channel": channel, "user": c.user, "client": c.uid,
}))
return ErrorInternal
}
// Build channel context with map flag.
channelFlags := c.buildMapChannelFlags(deltaEnabled, req.Delta, isPresence, opts, reply)
channelContext := ChannelContext{
flags: channelFlags,
expireAt: opts.ExpireAt,
info: opts.ChannelInfo,
streamPosition: StreamPosition{
Offset: latestOffset,
Epoch: streamPos.Epoch,
},
metaTTLSeconds: int64(opts.HistoryMetaTTL.Seconds()),
positionCheckTime: time.Now().Unix(),
Source: opts.Source,
mapClientPresenceChannel: opts.MapClientPresenceChannel,
mapUserPresenceChannel: opts.MapUserPresenceChannel,
subGen: subGen,
}
// Install channelContext BEFORE writing the reply so that any follow-up
// commands from the SDK that arrive between the reply send and StopBuffering
// observe the channel as subscribed. Buffered PUB/SUB publications stay
// queued until StopBuffering below — they cannot reach the client yet.
// commitSubscription moves the reservation from mapSubscribing to c.channels
// (or rolls back the hub entry if the client closed mid-subscribe) — the same
// consistency-critical commit the normal subscribe path uses.
subscribingCh, committed := c.commitSubscription(channel, channelContext, reservationMap)
if !committed {
c.releaseSubscribeCommandReply(protoReply)
c.pubSubSync.StopBuffering(channel)
return ErrorInternal
}
if subscribingCh != nil {
close(subscribingCh)
}
c.writeEncodedCommandReply(channel, protocol.FrameTypeSubscribe, cmd, protoReply, rw)
c.handleCommandFinished(cmd, protocol.FrameTypeSubscribe, nil, protoReply, started, "")
c.releaseSubscribeCommandReply(protoReply)
c.node.metrics.incActionCount(params.metricsAction, channel)
if params.isRecovery && req.Recover {
c.node.metrics.incRecover(true, channel, len(recoveredPubs) > 0)
c.node.metrics.observeRecoveredPublications(len(recoveredPubs), channel)
}
// Stop buffering after response written.
c.pubSubSync.StopBuffering(channel)
// Add presence and join handling.
c.setupMapPresenceAndJoin(channel, opts)
return nil
}
// handleMapStateToLive handles direct transition from STATE to LIVE phase.
// This is called on the last state page when stream is close enough to go LIVE directly.
func (c *Client) handleMapStateToLive(
req *protocol.SubscribeRequest,
reply SubscribeReply,
state *mapSubscribeState,
cmd *protocol.Command,
started time.Time,
rw *replyWriter,
statePubs []*Publication,
statePos StreamPosition,
) error {
return c.handleMapTransitionToLive(req, reply, state.options, state.isPresence, cmd, started, rw, mapTransitionToLiveParams{
sincePosition: statePos,
statePubs: statePubs,
allowStreamless: true,
isRecovery: false,
tagsFilterFromState: state.tagsFilter,
serverTagsFilterFromState: state.serverTagsFilter,
metricsAction: "map_subscribe_state_to_live",
expectedState: state,
})
}
// handleMapStreamPhase handles stateless stream pagination (history catch-up).
// Server controls when to transition to LIVE based on captured streamStart.
func (c *Client) handleMapStreamPhase(
req *protocol.SubscribeRequest,
reply SubscribeReply,
cmd *protocol.Command,
started time.Time,
rw *replyWriter,
) error {
channel := req.Channel
// Reject stream phase in streamless mode.
if !reply.Options.EnablePositioning && !reply.Options.EnableRecovery {
c.cleanupMapSubscribing(channel)
return ErrorBadRequest
}
// Check for existing subscription state or recovery mode.
c.mu.RLock()