-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
client.go
3509 lines (3150 loc) · 105 KB
/
client.go
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"
"fmt"
"io"
"math"
"slices"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/convert"
"github.com/centrifugal/centrifuge/internal/queue"
"github.com/centrifugal/centrifuge/internal/recovery"
"github.com/centrifugal/centrifuge/internal/saferand"
"github.com/centrifugal/protocol"
"github.com/google/uuid"
"github.com/segmentio/encoding/json"
fdelta "github.com/shadowspore/fossil-delta"
"google.golang.org/protobuf/encoding/protojson"
)
// Empty Replies/Pushes for pings.
var jsonPingReply = []byte(`{}`)
var protobufPingReply []byte
var jsonPingPush = []byte(`{}`)
var protobufPingPush []byte
var randSource *saferand.Rand
func init() {
protobufPingReply, _ = protocol.DefaultProtobufReplyEncoder.Encode(&protocol.Reply{})
protobufPingPush, _ = protocol.DefaultProtobufPushEncoder.Encode(&protocol.Push{})
randSource = saferand.New(time.Now().UnixNano())
}
// clientEventHub allows dealing with client event handlers.
// All its methods are not goroutine-safe and supposed to be called
// once inside Node ConnectHandler.
type clientEventHub struct {
aliveHandler AliveHandler
disconnectHandler DisconnectHandler
subscribeHandler SubscribeHandler
unsubscribeHandler UnsubscribeHandler
publishHandler PublishHandler
refreshHandler RefreshHandler
subRefreshHandler SubRefreshHandler
rpcHandler RPCHandler
messageHandler MessageHandler
presenceHandler PresenceHandler
presenceStatsHandler PresenceStatsHandler
historyHandler HistoryHandler
stateSnapshotHandler StateSnapshotHandler
}
// OnAlive allows setting AliveHandler.
// AliveHandler called periodically for active client connection.
func (c *Client) OnAlive(h AliveHandler) {
c.eventHub.aliveHandler = h
}
// OnRefresh allows setting RefreshHandler.
// RefreshHandler called when it's time to refresh expiring client connection.
func (c *Client) OnRefresh(h RefreshHandler) {
c.eventHub.refreshHandler = h
}
// OnDisconnect allows setting DisconnectHandler.
// DisconnectHandler called when client disconnected.
func (c *Client) OnDisconnect(h DisconnectHandler) {
c.eventHub.disconnectHandler = h
}
// OnMessage allows setting MessageHandler.
// MessageHandler called when client sent asynchronous message.
func (c *Client) OnMessage(h MessageHandler) {
c.eventHub.messageHandler = h
}
// OnRPC allows setting RPCHandler.
// RPCHandler will be executed on every incoming RPC call.
func (c *Client) OnRPC(h RPCHandler) {
c.eventHub.rpcHandler = h
}
// OnSubRefresh allows setting SubRefreshHandler.
// SubRefreshHandler called when it's time to refresh client subscription.
func (c *Client) OnSubRefresh(h SubRefreshHandler) {
c.eventHub.subRefreshHandler = h
}
// OnSubscribe allows setting SubscribeHandler.
// SubscribeHandler called when client subscribes on a channel.
func (c *Client) OnSubscribe(h SubscribeHandler) {
c.eventHub.subscribeHandler = h
}
// OnUnsubscribe allows setting UnsubscribeHandler.
// UnsubscribeHandler called when client unsubscribes from channel.
func (c *Client) OnUnsubscribe(h UnsubscribeHandler) {
c.eventHub.unsubscribeHandler = h
}
// OnPublish allows setting PublishHandler.
// PublishHandler called when client publishes message into channel.
func (c *Client) OnPublish(h PublishHandler) {
c.eventHub.publishHandler = h
}
// OnPresence allows setting PresenceHandler.
// PresenceHandler called when Presence request from client received.
// At this moment you can only return a custom error or disconnect client.
func (c *Client) OnPresence(h PresenceHandler) {
c.eventHub.presenceHandler = h
}
// OnPresenceStats allows settings PresenceStatsHandler.
// PresenceStatsHandler called when Presence Stats request from client received.
// At this moment you can only return a custom error or disconnect client.
func (c *Client) OnPresenceStats(h PresenceStatsHandler) {
c.eventHub.presenceStatsHandler = h
}
// OnHistory allows settings HistoryHandler.
// HistoryHandler called when History request from client received.
// At this moment you can only return a custom error or disconnect client.
func (c *Client) OnHistory(h HistoryHandler) {
c.eventHub.historyHandler = h
}
const (
// flagSubscribed will be set upon successful Subscription to a channel.
// Until that moment channel exists in client Channels map only to track
// duplicate subscription requests.
flagSubscribed uint8 = 1 << iota
flagEmitPresence
flagEmitJoinLeave
flagPushJoinLeave
flagPositioning
flagServerSide
flagClientSideRefresh
flagDeltaAllowed
)
// ChannelContext contains extra context for channel connection subscribed to.
// Note: this struct is aligned to consume less memory.
type ChannelContext struct {
subscribingCh chan struct{}
info []byte
expireAt int64
positionCheckTime int64
metaTTLSeconds int64
streamPosition StreamPosition
flags uint8
Source uint8
}
func channelHasFlag(flags, flag uint8) bool {
return flags&flag != 0
}
type timerOp uint8
const (
timerOpStale timerOp = 1
timerOpPresence timerOp = 2
timerOpExpire timerOp = 3
timerOpPing timerOp = 4
timerOpPong timerOp = 5
)
type status uint8
const (
statusConnecting status = 1
statusConnected status = 2
statusClosed status = 3
)
// ConnectRequest can be used in a unidirectional connection case to
// pass initial connection information from a client-side.
type ConnectRequest struct {
// Token is an optional token from a client.
Token string
// Data is an optional custom data from a client.
Data []byte
// Name of a client.
Name string
// Version of a client.
Version string
// Subs is a map with channel subscription state (for recovery on connect).
Subs map[string]SubscribeRequest
}
// SubscribeRequest contains state of subscription to a channel.
type SubscribeRequest struct {
// Recover enables publication recovery for a channel.
Recover bool
// Epoch last seen by a client.
Epoch string
// Offset last seen by a client.
Offset uint64
}
func (r *ConnectRequest) toProto() *protocol.ConnectRequest {
if r == nil {
return nil
}
req := &protocol.ConnectRequest{
Token: r.Token,
Data: r.Data,
Name: r.Name,
Version: r.Version,
}
if len(r.Subs) > 0 {
subs := make(map[string]*protocol.SubscribeRequest, len(r.Subs))
for k, v := range r.Subs {
subs[k] = &protocol.SubscribeRequest{
Recover: v.Recover,
Epoch: v.Epoch,
Offset: v.Offset,
}
}
req.Subs = subs
}
return req
}
// Client represents client connection to server.
type Client struct {
mu sync.RWMutex
connectMu sync.Mutex // allows syncing connect with disconnect.
presenceMu sync.Mutex // allows syncing presence routine with client closing.
ctx context.Context
transport Transport
node *Node
exp int64
channels map[string]ChannelContext
messageWriter *writer
pubSubSync *recovery.PubSubSync
uid string
session string
user string
info []byte
storage map[string]any
storageMu sync.Mutex
authenticated bool
clientSideRefresh bool
status status
timerOp timerOp
nextPresence int64
nextExpire int64
nextPing int64
nextPong int64
lastSeen int64
lastPing int64
pingInterval time.Duration
pongTimeout time.Duration
eventHub *clientEventHub
timer *time.Timer
startWriterOnce sync.Once
replyWithoutQueue bool
unusable bool
}
// ClientCloseFunc must be called on Transport handler close to clean up Client.
type ClientCloseFunc func() error
// NewClient initializes new Client.
func NewClient(ctx context.Context, n *Node, t Transport) (*Client, ClientCloseFunc, error) {
uidObject, err := uuid.NewRandom()
if err != nil {
return nil, nil, err
}
uid := uidObject.String()
var session string
if t.Unidirectional() || t.Emulation() {
sessionObject, err := uuid.NewRandom()
if err != nil {
return nil, nil, err
}
session = sessionObject.String()
}
client := &Client{
ctx: ctx,
uid: uid,
session: session,
node: n,
transport: t,
channels: make(map[string]ChannelContext),
pubSubSync: recovery.NewPubSubSync(),
status: statusConnecting,
eventHub: &clientEventHub{},
}
staleCloseDelay := n.config.ClientStaleCloseDelay
if staleCloseDelay > 0 {
client.mu.Lock()
client.timerOp = timerOpStale
client.timer = time.AfterFunc(staleCloseDelay, client.onTimerOp)
client.mu.Unlock()
}
return client, func() error { return client.close(DisconnectConnectionClosed) }, nil
}
var defaultUniErrorCodeToDisconnect = map[uint32]Disconnect{
ErrorExpired.Code: DisconnectExpired,
ErrorTokenExpired.Code: DisconnectExpired,
ErrorTooManyRequests.Code: DisconnectTooManyRequests,
ErrorPermissionDenied.Code: DisconnectPermissionDenied,
}
func (c *Client) extractUnidirectionalDisconnect(err error) Disconnect {
switch t := err.(type) {
case *Disconnect:
return *t
case Disconnect:
return t
case *Error:
if c.node.config.UnidirectionalCodeToDisconnect != nil {
if d, ok := c.node.config.UnidirectionalCodeToDisconnect[t.Code]; ok {
return d
}
}
if d, ok := defaultUniErrorCodeToDisconnect[t.Code]; ok {
return d
}
return DisconnectServerError
default:
return DisconnectServerError
}
}
// Connect supposed to be called only from a unidirectional transport layer
// to pass initial information about connection and thus initiate Node.OnConnecting
// event. Bidirectional transport initiate connecting workflow automatically
// since client passes Connect command upon successful connection establishment
// with a server. If there is an error during connect method processing Centrifuge
// extracts Disconnect from it and closes the connection with that Disconnect message.
func (c *Client) Connect(req ConnectRequest) {
// unidirectionalConnect never returns errors when errorToDisconnect is true.
_ = c.unidirectionalConnect(req.toProto(), 0, true)
}
// ConnectNoErrorToDisconnect is the same as Client.Connect but does not try to extract
// Disconnect code from the error returned by the connect logic, instead it just returns
// the error to the caller. This error must be handled by the caller on the Transport level,
// and the connection must be closed on Transport level upon receiving an error.
func (c *Client) ConnectNoErrorToDisconnect(req ConnectRequest) error {
return c.unidirectionalConnect(req.toProto(), 0, false)
}
func (c *Client) getDisconnectPushReply(d Disconnect) ([]byte, error) {
disconnect := &protocol.Disconnect{
Code: d.Code,
Reason: d.Reason,
}
push := &protocol.Push{
Disconnect: disconnect,
}
if c.node.LogEnabled(LogLevelTrace) {
c.traceOutPush(push)
}
return c.encodeReply(&protocol.Reply{
Push: push,
})
}
func hasFlag(flags, flag uint64) bool {
return flags&flag != 0
}
func (c *Client) issueCommandReadEvent(cmd *protocol.Command, size int) error {
if c.node.clientEvents.commandReadHandler != nil {
return c.node.clientEvents.commandReadHandler(c, CommandReadEvent{
Command: cmd,
CommandSize: size,
})
}
return nil
}
func (c *Client) issueCommandProcessedEvent(event CommandProcessedEvent) {
if c.node.clientEvents.commandProcessedHandler != nil {
c.node.clientEvents.commandProcessedHandler(c, event)
}
}
func (c *Client) unidirectionalConnect(connectRequest *protocol.ConnectRequest, connectCmdSize int, errorToDisconnect bool) error {
started := time.Now()
var cmd *protocol.Command
if c.node.LogEnabled(LogLevelTrace) {
cmd = &protocol.Command{Id: 1, Connect: connectRequest}
c.traceInCmd(cmd)
}
if c.node.clientEvents.commandReadHandler != nil {
cmd = &protocol.Command{Id: 1, Connect: connectRequest}
err := c.issueCommandReadEvent(cmd, connectCmdSize)
if err != nil {
if c.node.clientEvents.commandProcessedHandler != nil {
c.handleCommandFinished(cmd, protocol.FrameTypeConnect, err, nil, started)
}
if errorToDisconnect {
d := c.extractUnidirectionalDisconnect(err)
go func() { _ = c.close(d) }()
return nil
}
return err
}
}
_, err := c.connectCmd(connectRequest, nil, time.Time{}, nil)
if err != nil {
if c.node.clientEvents.commandProcessedHandler != nil {
c.handleCommandFinished(cmd, protocol.FrameTypeConnect, err, nil, started)
}
if errorToDisconnect {
d := c.extractUnidirectionalDisconnect(err)
go func() { _ = c.close(d) }()
return nil
}
return err
}
if c.node.clientEvents.commandProcessedHandler != nil {
c.handleCommandFinished(cmd, protocol.FrameTypeConnect, nil, nil, started)
}
c.triggerConnect()
c.scheduleOnConnectTimers()
return nil
}
func (c *Client) onTimerOp() {
c.mu.Lock()
if c.status == statusClosed {
c.mu.Unlock()
return
}
op := c.timerOp
c.mu.Unlock()
switch op {
case timerOpStale:
c.closeStale()
case timerOpPresence:
c.updatePresence()
case timerOpExpire:
c.expire()
case timerOpPing:
c.sendPing()
case timerOpPong:
c.checkPong()
}
}
// Lock must be held outside.
func (c *Client) scheduleNextTimer() {
if c.status == statusClosed {
return
}
c.stopTimer()
var minEventTime int64
var nextTimerOp timerOp
var needTimer bool
if c.nextExpire > 0 {
nextTimerOp = timerOpExpire
minEventTime = c.nextExpire
needTimer = true
}
if c.nextPresence > 0 && (minEventTime == 0 || c.nextPresence < minEventTime) {
nextTimerOp = timerOpPresence
minEventTime = c.nextPresence
needTimer = true
}
if c.nextPing > 0 && (minEventTime == 0 || c.nextPing < minEventTime) {
nextTimerOp = timerOpPing
minEventTime = c.nextPing
needTimer = true
}
if c.nextPong > 0 && (minEventTime == 0 || c.nextPong < minEventTime) {
nextTimerOp = timerOpPong
minEventTime = c.nextPong
needTimer = true
}
if needTimer {
c.timerOp = nextTimerOp
afterDuration := time.Duration(minEventTime-time.Now().UnixNano()) * time.Nanosecond
if c.timer != nil {
c.timer.Reset(afterDuration)
} else {
c.timer = time.AfterFunc(afterDuration, c.onTimerOp)
}
}
}
// Lock must be held outside.
func (c *Client) stopTimer() {
if c.timer != nil {
c.timer.Stop()
}
}
func getPingData(uni bool, protoType ProtocolType) []byte {
if uni {
if protoType == ProtocolTypeJSON {
return jsonPingPush
} else {
return protobufPingPush
}
} else {
if protoType == ProtocolTypeJSON {
return jsonPingReply
} else {
return protobufPingReply
}
}
}
func (c *Client) sendPing() {
c.mu.Lock()
c.lastPing = time.Now().UnixNano()
c.mu.Unlock()
unidirectional := c.transport.Unidirectional()
_ = c.transportEnqueue(getPingData(unidirectional, c.transport.Protocol()), "", protocol.FrameTypeServerPing)
if c.node.LogEnabled(LogLevelTrace) {
c.traceOutReply(emptyReply)
}
c.mu.Lock()
if c.pongTimeout > 0 && !unidirectional {
c.nextPong = time.Now().Add(c.pongTimeout).UnixNano()
}
c.addPingUpdate(false, true)
c.mu.Unlock()
}
func (c *Client) checkPong() {
c.mu.RLock()
lastPing := c.lastPing
if lastPing < 0 {
lastPing = -lastPing
}
lastSeen := c.lastSeen
c.mu.RUnlock()
if lastSeen < lastPing {
go func() { c.Disconnect(DisconnectNoPong) }()
return
}
c.node.metrics.observePingPongDuration(time.Duration(lastSeen-lastPing)*time.Nanosecond, c.transport.Name())
c.mu.Lock()
c.nextPong = 0
c.scheduleNextTimer()
c.mu.Unlock()
}
// Lock must be held outside.
func (c *Client) addPingUpdate(isFirst bool, scheduleNext bool) {
delay := c.pingInterval
if isFirst {
// Send first ping in random interval between PingInterval/2 and PingInterval to
// spread ping-pongs in time (useful when many connections reconnect
// almost immediately).
pingNanoseconds := c.pingInterval.Nanoseconds()
delay = time.Duration(pingNanoseconds/2) + time.Duration(randSource.Int63n(pingNanoseconds/2))*time.Nanosecond
}
c.nextPing = time.Now().Add(delay).UnixNano()
if scheduleNext {
c.scheduleNextTimer()
}
}
// Lock must be held outside.
func (c *Client) addPresenceUpdate(scheduleNext bool) {
c.nextPresence = time.Now().Add(c.node.config.ClientPresenceUpdateInterval).UnixNano()
if scheduleNext {
c.scheduleNextTimer()
}
}
// Lock must be held outside.
func (c *Client) addExpireUpdate(after time.Duration, scheduleNext bool) {
c.nextExpire = time.Now().Add(after).UnixNano()
if scheduleNext {
c.scheduleNextTimer()
}
}
// closeStale closes connection if it's not authenticated yet, or it's
// unusable but still not closed. At moment used to close client connections
// which have not sent valid connect command in a reasonable time interval after
// establishing connection with a server.
func (c *Client) closeStale() {
c.mu.RLock()
authenticated := c.authenticated
unusable := c.unusable
closed := c.status == statusClosed
c.mu.RUnlock()
if (!authenticated || unusable) && !closed {
_ = c.close(DisconnectStale)
}
}
func (c *Client) transportEnqueue(data []byte, ch string, frameType protocol.FrameType) error {
item := queue.Item{
Data: data,
FrameType: frameType,
}
if c.node.config.GetChannelNamespaceLabel != nil {
item.Channel = ch
}
disconnect := c.messageWriter.enqueue(item)
if disconnect != nil {
// close in goroutine to not block message broadcast.
go func() { _ = c.close(*disconnect) }()
return io.EOF
}
return nil
}
// updateChannelPresence updates client presence info for channel so it
// won't expire until client disconnect.
func (c *Client) updateChannelPresence(ch string, chCtx ChannelContext) error {
if !channelHasFlag(chCtx.flags, flagEmitPresence) {
return nil
}
c.mu.RLock()
if _, ok := c.channels[ch]; !ok {
c.mu.RUnlock()
return nil
}
c.mu.RUnlock()
return c.node.addPresence(ch, c.uid, &ClientInfo{
ClientID: c.uid,
UserID: c.user,
ConnInfo: c.info,
ChanInfo: chCtx.info,
})
}
// Context returns client Context. This context will be canceled
// as soon as client connection closes.
func (c *Client) Context() context.Context {
return c.ctx
}
func (c *Client) checkSubscriptionExpiration(channel string, channelContext ChannelContext, delay time.Duration, resultCB func(bool)) {
now := c.node.nowTimeGetter().Unix()
expireAt := channelContext.expireAt
clientSideRefresh := channelHasFlag(channelContext.flags, flagClientSideRefresh)
if expireAt > 0 && now > expireAt+int64(delay.Seconds()) {
// Subscription expired.
if clientSideRefresh || c.eventHub.subRefreshHandler == nil {
// The only way subscription could be refreshed in this case is via
// SUB_REFRESH command sent from client but looks like that command
// with new refreshed token have not been received in configured window.
resultCB(false)
return
}
cb := func(reply SubRefreshReply, err error) {
if err != nil {
resultCB(false)
return
}
if reply.Expired || (reply.ExpireAt > 0 && reply.ExpireAt < now) {
resultCB(false)
return
}
c.mu.Lock()
if ctx, ok := c.channels[channel]; ok {
if len(reply.Info) > 0 {
ctx.info = reply.Info
}
ctx.expireAt = reply.ExpireAt
c.channels[channel] = ctx
}
c.mu.Unlock()
resultCB(true)
}
// Give subscription a chance to be refreshed via SubRefreshHandler.
event := SubRefreshEvent{Channel: channel}
c.eventHub.subRefreshHandler(event, cb)
return
}
resultCB(true)
}
// updatePresence used for various periodic actions we need to do with client connections.
func (c *Client) updatePresence() {
c.presenceMu.Lock()
defer c.presenceMu.Unlock()
config := c.node.config
c.mu.Lock()
unusable := c.unusable
if c.status == statusClosed {
c.mu.Unlock()
return
}
channels := make(map[string]ChannelContext, len(c.channels))
for channel, channelContext := range c.channels {
if !channelHasFlag(channelContext.flags, flagSubscribed) {
continue
}
channels[channel] = channelContext
}
c.mu.Unlock()
if unusable {
go c.closeStale()
return
}
if c.eventHub.aliveHandler != nil {
c.eventHub.aliveHandler()
}
for channel, channelContext := range channels {
err := c.updateChannelPresence(channel, channelContext)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error updating presence for channel", map[string]any{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
}
c.checkSubscriptionExpiration(channel, channelContext, config.ClientExpiredSubCloseDelay, func(result bool) {
if !result {
serverSide := channelHasFlag(channelContext.flags, flagServerSide)
if c.isAsyncUnsubscribe(serverSide) {
go func(ch string) { c.handleAsyncUnsubscribe(ch, unsubscribeExpired) }(channel)
} else {
go func() { _ = c.close(DisconnectSubExpired) }()
}
}
})
checkDelay := config.ClientChannelPositionCheckDelay
if checkDelay > 0 && !c.checkPosition(checkDelay, channel, channelContext) {
serverSide := channelHasFlag(channelContext.flags, flagServerSide)
if c.node.logger.enabled(LogLevelDebug) {
c.node.logger.log(newLogEntry(LogLevelDebug, "client insufficient state from periodic check", map[string]any{"channel": channel, "user": c.user, "client": c.uid}))
}
if c.isAsyncUnsubscribe(serverSide) {
go func(ch string) { c.handleAsyncUnsubscribe(ch, unsubscribeInsufficientState) }(channel)
continue
} else {
go func() { c.handleInsufficientStateDisconnect() }()
// No need to proceed after close.
return
}
}
}
c.mu.Lock()
c.addPresenceUpdate(true)
c.mu.Unlock()
}
func (c *Client) checkPosition(checkDelay time.Duration, ch string, chCtx ChannelContext) bool {
if !channelHasFlag(chCtx.flags, flagPositioning) {
return true
}
nowUnix := c.node.nowTimeGetter().Unix()
needCheckPosition := nowUnix-chCtx.positionCheckTime > int64(checkDelay.Seconds())
if !needCheckPosition {
return true
}
var historyMetaTTL time.Duration
if chCtx.metaTTLSeconds > 0 {
historyMetaTTL = time.Duration(chCtx.metaTTLSeconds) * time.Second
}
c.mu.Lock()
if c.status == statusClosed {
c.mu.Unlock()
return true
}
chCtx, ok := c.channels[ch]
if !ok || !channelHasFlag(chCtx.flags, flagSubscribed) {
c.mu.Unlock()
return true
}
position := chCtx.streamPosition
c.mu.Unlock()
validPosition, err := c.node.checkPosition(ch, position, historyMetaTTL)
if err != nil {
// Check later.
return true
}
if validPosition {
c.mu.Lock()
if chContext, ok := c.channels[ch]; ok {
chContext.positionCheckTime = nowUnix
c.channels[ch] = chContext
}
c.mu.Unlock()
}
return validPosition
}
// ID returns unique client connection id.
func (c *Client) ID() string {
return c.uid
}
// sessionID returns unique client session id. Session ID is not shared to other
// connections in any way.
func (c *Client) sessionID() string {
return c.session
}
// UserID returns user id associated with client connection.
func (c *Client) UserID() string {
return c.user
}
// Info returns connection info.
func (c *Client) Info() []byte {
c.mu.Lock()
info := make([]byte, len(c.info))
copy(info, c.info)
c.mu.Unlock()
return info
}
// Transport returns client connection transport information.
func (c *Client) Transport() TransportInfo {
return c.transport
}
// Channels returns a slice of channels client connection currently subscribed to.
func (c *Client) Channels() []string {
c.mu.RLock()
defer c.mu.RUnlock()
channels := make([]string, 0, len(c.channels))
for ch, ctx := range c.channels {
if !channelHasFlag(ctx.flags, flagSubscribed) {
continue
}
channels = append(channels, ch)
}
return channels
}
// ChannelsWithContext returns a map of channels client connection currently subscribed to
// with a ChannelContext.
func (c *Client) ChannelsWithContext() map[string]ChannelContext {
c.mu.RLock()
defer c.mu.RUnlock()
channels := make(map[string]ChannelContext, len(c.channels))
for ch, ctx := range c.channels {
if !channelHasFlag(ctx.flags, flagSubscribed) {
continue
}
channels[ch] = ctx
}
return channels
}
// IsSubscribed returns true if client subscribed to a channel.
func (c *Client) IsSubscribed(ch string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
ctx, ok := c.channels[ch]
return ok && channelHasFlag(ctx.flags, flagSubscribed)
}
// Send data to client. This sends an asynchronous message – data will be
// just written to connection. on client side this message can be handled
// with Message handler.
func (c *Client) Send(data []byte) error {
if hasFlag(c.transport.DisabledPushFlags(), PushFlagMessage) {
return nil
}
replyData, err := c.getSendPushReply(data)
if err != nil {
return err
}
return c.transportEnqueue(replyData, "", protocol.FrameTypePushMessage)
}
func (c *Client) encodeReply(reply *protocol.Reply) ([]byte, error) {
protoType := c.transport.Protocol().toProto()
if c.transport.Unidirectional() {
encoder := protocol.GetPushEncoder(protoType)
return encoder.Encode(reply.Push)
} else {
encoder := protocol.GetReplyEncoder(protoType)
return encoder.Encode(reply)
}
}
func (c *Client) getSendPushReply(data []byte) ([]byte, error) {
p := &protocol.Message{
Data: data,
}
return c.encodeReply(&protocol.Reply{
Push: &protocol.Push{
Message: p,
},
})
}
// Unsubscribe allows unsubscribing client from channel.
func (c *Client) Unsubscribe(ch string, unsubscribe ...Unsubscribe) {
if len(unsubscribe) > 1 {
panic("Client.Unsubscribe called with more than 1 unsubscribe argument")
}
c.mu.RLock()
if c.status == statusClosed {
c.mu.RUnlock()
return
}
c.mu.RUnlock()
unsub := unsubscribeServer
if len(unsubscribe) > 0 {
unsub = unsubscribe[0]
}
err := c.unsubscribe(ch, unsub, nil)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error unsubscribe", map[string]any{"channel": ch, "user": c.user, "client": c.uid, "error": err.Error()}))
go c.Disconnect(DisconnectServerError)
return
}
_ = c.sendUnsubscribe(ch, unsub)
}
func (c *Client) sendUnsubscribe(ch string, unsub Unsubscribe) error {
if hasFlag(c.transport.DisabledPushFlags(), PushFlagUnsubscribe) {
return nil
}
replyData, err := c.getUnsubscribePushReply(ch, unsub)
if err != nil {
return err
}
_ = c.transportEnqueue(replyData, ch, protocol.FrameTypePushUnsubscribe)
c.node.metrics.incServerUnsubscribe(unsub.Code)
return nil
}
func (c *Client) getUnsubscribePushReply(ch string, unsub Unsubscribe) ([]byte, error) {
p := &protocol.Unsubscribe{
Code: unsub.Code,
Reason: unsub.Reason,
}
return c.encodeReply(&protocol.Reply{
Push: &protocol.Push{
Channel: ch,
Unsubscribe: p,
},
})
}
// Disconnect client connection with specific disconnect code and reason.
// If zero args or nil passed then DisconnectForceNoReconnect is used.
//
// This method internally creates a new goroutine at the moment to do
// closing stuff. An extra goroutine is required to solve disconnect
// and alive callback ordering/sync problems. Will be a noop if client
// already closed. As this method runs a separate goroutine client
// connection will be closed eventually (i.e. not immediately).
func (c *Client) Disconnect(disconnect ...Disconnect) {
if len(disconnect) > 1 {
panic("Client.Disconnect called with more than 1 argument")
}
go func() {
if len(disconnect) == 0 {
_ = c.close(DisconnectForceNoReconnect)
} else {
_ = c.close(disconnect[0])
}
}()
}
func (c *Client) close(disconnect Disconnect) error {
c.startWriter(0, 0, 0)
c.presenceMu.Lock()
defer c.presenceMu.Unlock()
c.connectMu.Lock()
defer c.connectMu.Unlock()
c.mu.Lock()
if c.status == statusClosed {
c.mu.Unlock()
return nil
}
prevStatus := c.status
c.status = statusClosed
c.stopTimer()
channels := make(map[string]ChannelContext, len(c.channels))
for channel, channelContext := range c.channels {
channels[channel] = channelContext
}
c.mu.Unlock()
// Unsubscribe from all channels.