forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
2258 lines (1994 loc) · 65.7 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"
"fmt"
"io"
"strconv"
"strings"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/clientproto"
"github.com/centrifugal/centrifuge/internal/prepared"
"github.com/centrifugal/centrifuge/internal/recovery"
"github.com/centrifugal/protocol"
"github.com/google/uuid"
)
// ClientEventHub allows to deal with client event handlers.
// All its methods are not goroutine-safe and supposed to be called once on client connect.
type ClientEventHub struct {
disconnectHandler DisconnectHandler
subscribeHandler SubscribeHandler
unsubscribeHandler UnsubscribeHandler
publishHandler PublishHandler
subRefreshHandler SubRefreshHandler
rpcHandler RPCHandler
messageHandler MessageHandler
}
// Disconnect allows to set DisconnectHandler.
// DisconnectHandler called when client disconnected.
func (c *ClientEventHub) Disconnect(h DisconnectHandler) {
c.disconnectHandler = h
}
// Message allows to set MessageHandler.
// MessageHandler called when client sent asynchronous message.
func (c *ClientEventHub) Message(h MessageHandler) {
c.messageHandler = h
}
// RPC allows to set RPCHandler.
// RPCHandler will be executed on every incoming RPC call.
func (c *ClientEventHub) RPC(h RPCHandler) {
c.rpcHandler = h
}
// SubRefresh allows to set SubRefreshHandler.
// SubRefreshHandler called when it's time to refresh client subscription.
func (c *ClientEventHub) SubRefresh(h SubRefreshHandler) {
c.subRefreshHandler = h
}
// Subscribe allows to set SubscribeHandler.
// SubscribeHandler called when client subscribes on channel.
func (c *ClientEventHub) Subscribe(h SubscribeHandler) {
c.subscribeHandler = h
}
// Unsubscribe allows to set UnsubscribeHandler.
// UnsubscribeHandler called when client unsubscribes from channel.
func (c *ClientEventHub) Unsubscribe(h UnsubscribeHandler) {
c.unsubscribeHandler = h
}
// Publish allows to set PublishHandler.
// PublishHandler called when client publishes message into channel.
func (c *ClientEventHub) Publish(h PublishHandler) {
c.publishHandler = h
}
// We poll current position in channel from history storage periodically.
// If client position is wrong maxCheckPositionFailures times in a row
// then client will be disconnected with InsufficientState reason.
const maxCheckPositionFailures int64 = 2
// ChannelContext contains extra context for channel connection subscribed to.
type ChannelContext struct {
Info Raw
serverSide bool
expireAt int64
positionCheckTime int64
positionCheckFailures int64
streamPosition StreamPosition
}
// Client represents client connection to server.
type Client struct {
mu sync.RWMutex
presenceMu sync.Mutex // allows to sync presence routine with client closing.
info Raw
ctx context.Context
transport Transport
uid string
user string
node *Node
exp int64
publicationsOnce sync.Once
publications *pubQueue
channels map[string]ChannelContext
staleTimer *time.Timer
expireTimer *time.Timer
presenceTimer *time.Timer
disconnect *Disconnect
eventHub *ClientEventHub
messageWriter *writer
pubSubSync *recovery.PubSubSync
closed bool
authenticated bool
}
// NewClient initializes new Client.
func NewClient(ctx context.Context, n *Node, t Transport) (*Client, error) {
uuidObject, err := uuid.NewRandom()
if err != nil {
return nil, err
}
config := n.Config()
c := &Client{
ctx: ctx,
uid: uuidObject.String(),
node: n,
transport: t,
eventHub: &ClientEventHub{},
channels: make(map[string]ChannelContext),
pubSubSync: recovery.NewPubSubSync(),
publications: newPubQueue(),
}
transportMessagesSentCounter := transportMessagesSent.WithLabelValues(t.Name())
messageWriterConf := writerConfig{
MaxQueueSize: config.ClientQueueMaxSize,
WriteFn: func(data []byte) error {
if err := t.Write(data); err != nil {
go func() { _ = c.Close(DisconnectWriteError) }()
return err
}
transportMessagesSentCounter.Inc()
return nil
},
WriteManyFn: func(data ...[]byte) error {
buf := getBuffer()
for _, payload := range data {
buf.Write(payload)
}
if err := t.Write(buf.Bytes()); err != nil {
go func() { _ = c.Close(DisconnectWriteError) }()
putBuffer(buf)
return err
}
putBuffer(buf)
transportMessagesSentCounter.Add(float64(len(data)))
return nil
},
}
c.messageWriter = newWriter(messageWriterConf)
staleCloseDelay := config.ClientStaleCloseDelay
if staleCloseDelay > 0 && !c.authenticated {
c.mu.Lock()
c.staleTimer = time.AfterFunc(staleCloseDelay, c.closeUnauthenticated)
c.mu.Unlock()
}
return c, nil
}
// closeUnauthenticated closes connection if it's not authenticated yet.
// At moment used to close client connections which have not sent valid
// connect command in a reasonable time interval after established connection
// with server.
func (c *Client) closeUnauthenticated() {
c.mu.RLock()
authenticated := c.authenticated
closed := c.closed
c.mu.RUnlock()
if !authenticated && !closed {
_ = c.Close(DisconnectStale)
}
}
func (c *Client) transportEnqueue(reply *prepared.Reply) error {
data := reply.Data()
disconnect := c.messageWriter.enqueue(data)
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) error {
chOpts, ok := c.node.ChannelOpts(ch)
if !ok {
return nil
}
if !chOpts.Presence {
return nil
}
info := c.clientInfo(ch)
return c.node.addPresence(ch, c.uid, info)
}
func (c *Client) checkSubscriptionExpiration(channel string, channelContext ChannelContext, delay time.Duration) bool {
now := time.Now().Unix()
expireAt := channelContext.expireAt
if expireAt > 0 && now > expireAt+int64(delay.Seconds()) {
// Subscription expired.
if c.eventHub.subRefreshHandler != nil {
// Give subscription a chance to be refreshed via SubRefreshHandler.
reply := c.eventHub.subRefreshHandler(SubRefreshEvent{Channel: channel})
if reply.Expired || (reply.ExpireAt > 0 && reply.ExpireAt < now) {
return false
}
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()
} else {
// 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.
return false
}
}
return 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()
if c.closed {
c.mu.Unlock()
return
}
channels := make(map[string]ChannelContext, len(c.channels))
for channel, channelContext := range c.channels {
channels[channel] = channelContext
}
c.mu.Unlock()
for channel, channelContext := range channels {
if !c.checkSubscriptionExpiration(channel, channelContext, config.ClientExpiredSubCloseDelay) {
// Ideally we should deal with single expired subscription in this
// case - i.e. unsubscribe client from channel and give an advice
// to resubscribe. But there is scenario when browser goes online
// after computer was in sleeping mode which I have not managed to
// handle reliably on client side when unsubscribe with resubscribe
// flag was used. So I decided to stick with disconnect for now -
// it seems to work fine and drastically simplifies client code.
go func() { _ = c.Close(DisconnectSubExpired) }()
// No need to proceed after close.
return
}
checkDelay := config.ClientChannelPositionCheckDelay
if checkDelay > 0 && !c.checkPosition(checkDelay, channel, channelContext) {
go func() { _ = c.Close(DisconnectInsufficientState) }()
// No need to proceed after close.
return
}
err := c.updateChannelPresence(channel)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error updating presence for channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
}
}
c.mu.Lock()
c.addPresenceUpdate()
c.mu.Unlock()
}
// Lock must be held outside.
func (c *Client) addPresenceUpdate() {
config := c.node.Config()
presenceInterval := config.ClientPresencePingInterval
c.presenceTimer = time.AfterFunc(presenceInterval, c.updatePresence)
}
func (c *Client) checkPosition(checkDelay time.Duration, ch string, channelContext ChannelContext) bool {
chOpts, ok := c.node.ChannelOpts(ch)
if !ok {
return true
}
if !chOpts.HistoryRecover {
return true
}
nowUnix := time.Now().Unix()
isInitialCheck := channelContext.positionCheckTime == 0
isTimeToCheck := nowUnix-channelContext.positionCheckTime > int64(checkDelay.Seconds())
needCheckPosition := isInitialCheck || isTimeToCheck
if !needCheckPosition {
return true
}
position := channelContext.streamPosition
streamTop, err := c.node.streamTop(ch)
if err != nil {
return true
}
isValidPosition := streamTop.Offset == position.Offset && streamTop.Epoch == position.Epoch
keepConnection := true
c.mu.Lock()
if channelContext, ok = c.channels[ch]; ok {
channelContext.positionCheckTime = nowUnix
if !isValidPosition {
channelContext.positionCheckFailures++
keepConnection = channelContext.positionCheckFailures < maxCheckPositionFailures
} else {
channelContext.positionCheckFailures = 0
}
c.channels[ch] = channelContext
}
c.mu.Unlock()
return keepConnection
}
// ID returns unique client connection id.
func (c *Client) ID() string {
return c.uid
}
// UserID returns user ID associated with client connection.
func (c *Client) UserID() string {
return c.user
}
// Transport returns transport details used by client connection.
func (c *Client) Transport() TransportInfo {
return c.transport
}
// Channels returns a map of channels client connection currently subscribed to.
func (c *Client) Channels() map[string]ChannelContext {
c.mu.RLock()
defer c.mu.RUnlock()
channels := make(map[string]ChannelContext, len(c.channels))
for ch, ctx := range c.channels {
channels[ch] = ctx
}
return channels
}
// On returns ClientEventHub to set various event handlers to client.
func (c *Client) On() *ClientEventHub {
return c.eventHub
}
// Send data to client connection asynchronously.
func (c *Client) Send(data protocol.Raw) error {
p := &protocol.Message{
Data: data,
}
pushEncoder := protocol.GetPushEncoder(c.transport.Protocol().toProto())
data, err := pushEncoder.EncodeMessage(p)
if err != nil {
return err
}
result, err := pushEncoder.Encode(clientproto.NewMessagePush(data))
if err != nil {
return err
}
reply := prepared.NewReply(&protocol.Reply{
Result: result,
}, c.transport.Protocol().toProto())
return c.transportEnqueue(reply)
}
// Unsubscribe allows to unsubscribe client from channel.
func (c *Client) Unsubscribe(ch string, opts ...UnsubscribeOption) error {
unsubscribeOpts := &UnsubscribeOptions{}
for _, opt := range opts {
opt(unsubscribeOpts)
}
c.mu.RLock()
if c.closed {
c.mu.RUnlock()
return nil
}
c.mu.RUnlock()
err := c.unsubscribe(ch)
if err != nil {
return err
}
return c.sendUnsub(ch, unsubscribeOpts.Resubscribe)
}
func (c *Client) sendUnsub(ch string, resubscribe bool) error {
pushEncoder := protocol.GetPushEncoder(c.transport.Protocol().toProto())
data, err := pushEncoder.EncodeUnsub(&protocol.Unsub{Resubscribe: resubscribe})
if err != nil {
return err
}
result, err := pushEncoder.Encode(clientproto.NewUnsubPush(ch, data))
if err != nil {
return err
}
reply := prepared.NewReply(&protocol.Reply{
Result: result,
}, c.transport.Protocol().toProto())
_ = c.transportEnqueue(reply)
return nil
}
// Close client connection with specific disconnect reason.
func (c *Client) Close(disconnect *Disconnect) error {
c.presenceMu.Lock()
defer c.presenceMu.Unlock()
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil
}
c.closed = true
if c.disconnect != nil {
disconnect = c.disconnect
}
channels := make(map[string]ChannelContext, len(c.channels))
for channel, channelContext := range c.channels {
channels[channel] = channelContext
}
c.mu.Unlock()
if len(channels) > 0 {
// Unsubscribe from all channels.
for channel := range channels {
err := c.unsubscribe(channel)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error unsubscribing client from channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
}
}
}
c.mu.RLock()
authenticated := c.authenticated
c.mu.RUnlock()
if authenticated {
err := c.node.removeClient(c)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error removing client", map[string]interface{}{"user": c.user, "client": c.uid, "error": err.Error()}))
}
}
c.mu.Lock()
if c.expireTimer != nil {
c.expireTimer.Stop()
}
if c.presenceTimer != nil {
c.presenceTimer.Stop()
}
if c.staleTimer != nil {
c.staleTimer.Stop()
}
c.mu.Unlock()
// Close writer and send messages remaining in writer queue if any.
_ = c.messageWriter.close()
c.publications.Close()
_ = c.transport.Close(disconnect)
if disconnect != nil && disconnect.Reason != "" {
c.node.logger.log(newLogEntry(LogLevelDebug, "closing client connection", map[string]interface{}{"client": c.uid, "user": c.user, "reason": disconnect.Reason, "reconnect": disconnect.Reconnect}))
}
if disconnect != nil {
serverDisconnectCount.WithLabelValues(strconv.Itoa(disconnect.Code)).Inc()
}
if c.eventHub.disconnectHandler != nil {
c.eventHub.disconnectHandler(DisconnectEvent{
Disconnect: disconnect,
})
}
return nil
}
// Lock must be held outside.
func (c *Client) clientInfo(ch string) *protocol.ClientInfo {
var channelInfo protocol.Raw
channelContext, ok := c.channels[ch]
if ok {
channelInfo = channelContext.Info
}
return &protocol.ClientInfo{
User: c.user,
Client: c.uid,
ConnInfo: c.info,
ChanInfo: channelInfo,
}
}
// Handle raw data encoded with Centrifuge protocol. Not goroutine-safe.
func (c *Client) Handle(data []byte) bool {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return false
}
c.mu.Unlock()
if len(data) == 0 {
c.node.logger.log(newLogEntry(LogLevelError, "empty client request received", map[string]interface{}{"client": c.ID(), "user": c.UserID()}))
_ = c.Close(DisconnectBadRequest)
return false
}
protoType := c.transport.Protocol().toProto()
encoder := protocol.GetReplyEncoder(protoType)
decoder := protocol.GetCommandDecoder(protoType, data)
for {
cmd, err := decoder.Decode()
if err != nil {
if err == io.EOF {
break
}
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding command", map[string]interface{}{"data": string(data), "client": c.ID(), "user": c.UserID(), "error": err.Error()}))
_ = c.Close(DisconnectBadRequest)
protocol.PutCommandDecoder(protoType, decoder)
protocol.PutReplyEncoder(protoType, encoder)
return false
}
var encodeErr error
write := func(rep *protocol.Reply) error {
encodeErr = encoder.Encode(rep)
if encodeErr != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding reply", map[string]interface{}{"reply": fmt.Sprintf("%v", rep), "command": fmt.Sprintf("%v", cmd), "client": c.ID(), "user": c.UserID(), "error": encodeErr.Error()}))
}
return encodeErr
}
flush := func() error {
buf := encoder.Finish()
if len(buf) > 0 {
disconnect := c.messageWriter.enqueue(buf)
if disconnect != nil {
if c.node.logger.enabled(LogLevelDebug) {
c.node.logger.log(newLogEntry(LogLevelDebug, "disconnect after sending reply", map[string]interface{}{"client": c.ID(), "user": c.UserID(), "reason": disconnect.Reason}))
}
protocol.PutCommandDecoder(protoType, decoder)
protocol.PutReplyEncoder(protoType, encoder)
_ = c.Close(disconnect)
return fmt.Errorf("flush error")
}
}
encoder.Reset()
return nil
}
disconnect := c.handleCommand(cmd, write, flush)
select {
case <-c.ctx.Done():
if encodeErr == nil {
protocol.PutCommandDecoder(protoType, decoder)
protocol.PutReplyEncoder(protoType, encoder)
}
return true
default:
}
if disconnect != nil {
if disconnect != DisconnectNormal {
c.node.logger.log(newLogEntry(LogLevelInfo, "disconnect after handling command", map[string]interface{}{"command": fmt.Sprintf("%v", cmd), "client": c.ID(), "user": c.UserID(), "reason": disconnect.Reason}))
}
_ = c.Close(disconnect)
if encodeErr == nil {
protocol.PutCommandDecoder(protoType, decoder)
protocol.PutReplyEncoder(protoType, encoder)
}
return false
}
if encodeErr != nil {
_ = c.Close(DisconnectServerError)
return false
}
}
buf := encoder.Finish()
if len(buf) > 0 {
disconnect := c.messageWriter.enqueue(buf)
if disconnect != nil {
if c.node.logger.enabled(LogLevelDebug) {
c.node.logger.log(newLogEntry(LogLevelDebug, "disconnect after sending reply", map[string]interface{}{"client": c.ID(), "user": c.UserID(), "reason": disconnect.Reason}))
}
_ = c.Close(disconnect)
protocol.PutCommandDecoder(protoType, decoder)
protocol.PutReplyEncoder(protoType, encoder)
return false
}
}
protocol.PutCommandDecoder(protoType, decoder)
protocol.PutReplyEncoder(protoType, encoder)
return true
}
type replyWriter struct {
write func(*protocol.Reply) error
flush func() error
}
// handle dispatches Command into correct command handler.
func (c *Client) handleCommand(cmd *protocol.Command, writeFn func(*protocol.Reply) error, flush func() error) *Disconnect {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil
}
c.mu.Unlock()
var disconnect *Disconnect
method := cmd.Method
params := cmd.Params
write := func(rep *protocol.Reply) error {
rep.ID = cmd.ID
if rep.Error != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "client command error", map[string]interface{}{"reply": fmt.Sprintf("%v", rep), "command": fmt.Sprintf("%v", cmd), "client": c.ID(), "user": c.UserID(), "error": rep.Error.Error()}))
replyErrorCount.WithLabelValues(strings.ToLower(protocol.MethodType_name[int32(method)]), strconv.FormatUint(uint64(rep.Error.Code), 10)).Inc()
}
return writeFn(rep)
}
rw := &replyWriter{write, flush}
if cmd.ID == 0 && method != protocol.MethodTypeSend {
c.node.logger.log(newLogEntry(LogLevelInfo, "command ID required for commands with reply expected", map[string]interface{}{"client": c.ID(), "user": c.UserID()}))
_ = rw.write(&protocol.Reply{Error: ErrorBadRequest.toProto()})
return nil
}
if method != protocol.MethodTypeConnect && !c.authenticated {
// Client must send connect command first.
_ = rw.write(&protocol.Reply{Error: ErrorUnauthorized.toProto()})
return nil
}
started := time.Now()
switch method {
case protocol.MethodTypeConnect:
disconnect = c.handleConnect(params, rw)
case protocol.MethodTypeRefresh:
disconnect = c.handleRefresh(params, rw)
case protocol.MethodTypeSubscribe:
disconnect = c.handleSubscribe(params, rw)
case protocol.MethodTypeSubRefresh:
disconnect = c.handleSubRefresh(params, rw)
case protocol.MethodTypeUnsubscribe:
disconnect = c.handleUnsubscribe(params, rw)
case protocol.MethodTypePublish:
disconnect = c.handlePublish(params, rw)
case protocol.MethodTypePresence:
disconnect = c.handlePresence(params, rw)
case protocol.MethodTypePresenceStats:
disconnect = c.handlePresenceStats(params, rw)
case protocol.MethodTypeHistory:
disconnect = c.handleHistory(params, rw)
case protocol.MethodTypePing:
disconnect = c.handlePing(params, rw)
case protocol.MethodTypeRPC:
disconnect = c.handleRPC(params, rw)
case protocol.MethodTypeSend:
disconnect = c.handleSend(params)
default:
_ = rw.write(&protocol.Reply{Error: ErrorMethodNotFound.toProto()})
}
commandDurationSummary.WithLabelValues(strings.ToLower(protocol.MethodType_name[int32(method)])).Observe(time.Since(started).Seconds())
return disconnect
}
func (c *Client) expire() {
c.mu.RLock()
closed := c.closed
c.mu.RUnlock()
if closed {
return
}
now := time.Now().Unix()
if c.node.eventHub.refreshHandler != nil {
reply := c.node.eventHub.refreshHandler(c.ctx, c, RefreshEvent{})
if reply.Expired {
_ = c.Close(DisconnectExpired)
return
}
if reply.ExpireAt > 0 {
c.mu.Lock()
c.exp = reply.ExpireAt
if reply.Info != nil {
c.info = reply.Info
}
c.mu.Unlock()
}
}
c.mu.RLock()
exp := c.exp
c.mu.RUnlock()
if exp == 0 {
return
}
ttl := exp - now
if c.node.eventHub.refreshHandler != nil {
if ttl > 0 {
c.mu.RLock()
if c.expireTimer != nil {
c.expireTimer.Stop()
}
c.mu.RUnlock()
duration := time.Duration(ttl) * time.Second
c.mu.Lock()
if !c.closed {
c.expireTimer = time.AfterFunc(duration, c.expire)
}
c.mu.Unlock()
}
}
if ttl > 0 {
// Connection was successfully refreshed.
return
}
_ = c.Close(DisconnectExpired)
}
func (c *Client) handleConnect(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeConnect(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding connect", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
disconnect := c.connectCmd(cmd, rw)
if disconnect != nil {
return disconnect
}
if c.node.eventHub.connectedHandler != nil {
c.node.eventHub.connectedHandler(c.ctx, c)
}
return nil
}
func (c *Client) handleRefresh(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeRefresh(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding refresh", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.refreshCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeRefreshResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding refresh", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handleSubscribe(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeSubscribe(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding subscribe", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
ctx := c.subscribeCmd(cmd, rw, false)
if ctx.disconnect != nil {
return ctx.disconnect
}
if ctx.err != nil {
return nil
}
if ctx.chOpts.JoinLeave && ctx.clientInfo != nil {
join := &protocol.Join{
Info: *ctx.clientInfo,
}
// Flush prevents Join message to be delivered before subscribe response.
_ = rw.flush()
go func() { _ = c.node.publishJoin(cmd.Channel, join, &ctx.chOpts) }()
}
return nil
}
func (c *Client) handleSubRefresh(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeSubRefresh(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding sub refresh", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.subRefreshCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeSubRefreshResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding sub refresh", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handleUnsubscribe(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeUnsubscribe(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding unsubscribe", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.unsubscribeCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeUnsubscribeResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding unsubscribe", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePublish(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePublish(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding publish", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.publishCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodePublishResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding publish", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePresence(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePresence(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding presence", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.presenceCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodePresenceResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding presence", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePresenceStats(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePresenceStats(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding presence stats", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.presenceStatsCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodePresenceStatsResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding presence stats", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handleHistory(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeHistory(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding history", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.historyCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeHistoryResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding history", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
_ = rw.write(&protocol.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePing(params protocol.Raw, rw *replyWriter) *Disconnect {
cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePing(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding ping", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.pingCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
_ = rw.write(&protocol.Reply{Error: resp.Error})
return nil
}
var replyRes []byte