forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
2028 lines (1768 loc) · 58.6 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"
"encoding/base64"
"fmt"
"io"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/centrifugal/centrifuge/internal/proto"
"github.com/centrifugal/centrifuge/internal/uuid"
"github.com/dgrijalva/jwt-go"
)
// 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
refreshHandler RefreshHandler
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
}
// Refresh allows to set RefreshHandler.
// RefreshHandler called when it's time to refresh client connection credentials.
func (c *ClientEventHub) Refresh(h RefreshHandler) {
c.refreshHandler = 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
}
// Credentials allows to authenticate connection when set into context.
type Credentials struct {
UserID string
ExpireAt int64
Info []byte
}
// credentialsContextKeyType is special type to safely use
// context for setting and getting Credentials.
type credentialsContextKeyType int
// CredentialsContextKey allows Go code to set Credentials into context.
var credentialsContextKey credentialsContextKeyType
// SetCredentials allows to set connection Credentials to context.
func SetCredentials(ctx context.Context, creds *Credentials) context.Context {
ctx = context.WithValue(ctx, credentialsContextKey, creds)
return ctx
}
// ChannelContext contains extra context for channel connection subscribed to.
type ChannelContext struct {
Info proto.Raw
expireAt int64
}
// Client represents client connection to server.
type Client struct {
mu sync.RWMutex
ctx context.Context
node *Node
transport transport
closed bool
authenticated bool
uid string
user string
exp int64
info proto.Raw
channels map[string]ChannelContext
staleTimer *time.Timer
expireTimer *time.Timer
presenceTimer *time.Timer
disconnect *Disconnect
eventHub *ClientEventHub
// The following fields help us to synchronize PUB/SUB and history messages during
// publication recovery process. At moment we use the fact that subscription requests
// processed by client in sequence so only keep a reference to one channel that is
// in subscribe process. If we want to process subscriptions in parallel in future
// then we have to use separate flags and buffers for each channel here - i.e. maybe
// use map.
inSubscribe uint32
inSubscribeChMu sync.RWMutex
inSubscribeCh string
pubBufferMu sync.Mutex
pubBuffer []*Publication
}
// newClient initializes new Client.
func newClient(ctx context.Context, n *Node, t transport) (*Client, error) {
uuidObject, err := uuid.NewV4()
if err != nil {
return nil, err
}
c := &Client{
ctx: ctx,
uid: uuidObject.String(),
node: n,
transport: t,
eventHub: &ClientEventHub{},
pubBuffer: make([]*Publication, 0),
}
config := n.Config()
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)
}
}
// 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 ErrorNamespaceNotFound
}
if !chOpts.Presence {
return nil
}
info := c.clientInfo(ch)
return c.node.addPresence(ch, c.uid, info)
}
// updatePresence updates presence info for all client channels.
// At moment it also checks for expired subscriptions. As this happens
// once in configured presence ping interval then subscription
// expiration time resolution is pretty big. Though on practice
// this should be reasonable for most use cases.
func (c *Client) updatePresence() {
config := c.node.Config()
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
for channel, channelContext := range c.channels {
now := time.Now().Unix()
expireAt := channelContext.expireAt
if expireAt > 0 && now > expireAt+int64(config.ClientExpiredSubCloseDelay.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) {
// 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 c.Close(DisconnectSubExpired)
// No need to update channel presence.
continue
}
ctx := c.channels[channel]
if len(reply.Info) > 0 {
ctx.Info = reply.Info
}
ctx.expireAt = reply.ExpireAt
c.channels[channel] = ctx
} 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.
go c.Close(DisconnectSubExpired)
// No need to update channel presence.
continue
}
}
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.addPresenceUpdate()
}
// Lock must be held outside.
func (c *Client) addPresenceUpdate() {
config := c.node.Config()
presenceInterval := config.ClientPresencePingInterval
c.presenceTimer = time.AfterFunc(presenceInterval, c.updatePresence)
}
// 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 used by client connection.
func (c *Client) Transport() Transport {
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 Raw) error {
p := &proto.Message{
Data: data,
}
pushEncoder := proto.GetPushEncoder(c.transport.Encoding())
data, err := pushEncoder.EncodeMessage(p)
if err != nil {
return err
}
result, err := pushEncoder.Encode(proto.NewMessagePush(data))
if err != nil {
return err
}
reply := newPreparedReply(&proto.Reply{
Result: result,
}, c.transport.Encoding())
return c.transport.Send(reply)
}
// Unsubscribe allows to unsubscribe client from channel.
func (c *Client) Unsubscribe(ch string, resubscribe bool) error {
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, resubscribe)
}
func (c *Client) sendUnsub(ch string, resubscribe bool) error {
pushEncoder := proto.GetPushEncoder(c.transport.Encoding())
data, err := pushEncoder.EncodeUnsub(&proto.Unsub{Resubscribe: resubscribe})
if err != nil {
return err
}
result, err := pushEncoder.Encode(proto.NewUnsubPush(ch, data))
if err != nil {
return err
}
reply := newPreparedReply(&proto.Reply{
Result: result,
}, c.transport.Encoding())
c.transport.Send(reply)
return nil
}
// Close closes client connection.
func (c *Client) Close(disconnect *Disconnect) error {
c.mu.Lock()
c.disconnect = disconnect
c.mu.Unlock()
// Closed transport will cause transport connection handler to
// return and thus calling client's close method.
return c.transport.Close(disconnect)
}
// close client connection with specific disconnect reason.
func (c *Client) close(disconnect *Disconnect) error {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil
}
c.closed = true
if c.disconnect != nil {
disconnect = c.disconnect
}
channels := c.channels
c.mu.Unlock()
if len(channels) > 0 {
// Unsubscribe from all channels.
for channel := range c.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()
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}))
}
c.transport.Close(disconnect)
if c.eventHub.disconnectHandler != nil {
c.eventHub.disconnectHandler(DisconnectEvent{
Disconnect: disconnect,
})
}
return nil
}
func (c *Client) isInSubscribe(ch string) bool {
if atomic.LoadUint32(&c.inSubscribe) == 1 {
c.inSubscribeChMu.RLock()
channelMatch := c.inSubscribeCh == ch
c.inSubscribeChMu.RUnlock()
return channelMatch
}
return false
}
func (c *Client) setInSubscribe(ch string, flag bool) {
c.inSubscribeChMu.Lock()
if flag {
atomic.StoreUint32(&c.inSubscribe, 1)
c.inSubscribeCh = ch
} else {
atomic.StoreUint32(&c.inSubscribe, 0)
c.inSubscribeCh = ""
}
c.inSubscribeChMu.Unlock()
}
// Lock must be held outside.
func (c *Client) clientInfo(ch string) *proto.ClientInfo {
var channelInfo proto.Raw
channelContext, ok := c.channels[ch]
if ok {
channelInfo = channelContext.Info
}
return &proto.ClientInfo{
User: c.user,
Client: c.uid,
ConnInfo: c.info,
ChanInfo: channelInfo,
}
}
// common data handling logic for Websocket and Sockjs handlers.
func (c *Client) handleRawData(data []byte, writer *writer) bool {
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
}
enc := c.transport.Encoding()
encoder := proto.GetReplyEncoder(enc)
decoder := proto.GetCommandDecoder(enc, 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)
proto.PutCommandDecoder(enc, decoder)
proto.PutReplyEncoder(enc, encoder)
return false
}
var encodeErr error
write := func(rep *proto.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 := writer.write(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}))
}
proto.PutCommandDecoder(enc, decoder)
proto.PutReplyEncoder(enc, encoder)
c.close(disconnect)
return fmt.Errorf("flush error")
}
}
encoder.Reset()
return nil
}
disconnect := c.handle(cmd, write, flush)
if disconnect != nil {
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)
proto.PutCommandDecoder(enc, decoder)
proto.PutReplyEncoder(enc, encoder)
return false
}
if encodeErr != nil {
c.close(DisconnectServerError)
return false
}
}
buf := encoder.Finish()
if len(buf) > 0 {
disconnect := writer.write(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)
proto.PutCommandDecoder(enc, decoder)
proto.PutReplyEncoder(enc, encoder)
return false
}
}
proto.PutCommandDecoder(enc, decoder)
proto.PutReplyEncoder(enc, encoder)
return true
}
type replyWriter struct {
write func(*proto.Reply) error
flush func() error
}
// handle dispatches Command into correct command handler.
func (c *Client) handle(cmd *proto.Command, writeFn func(*proto.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 *proto.Reply) error {
rep.ID = cmd.ID
if rep.Error != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error in reply", 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(proto.MethodType_name[int32(method)]), strconv.FormatUint(uint64(rep.Error.Code), 10)).Inc()
}
return writeFn(rep)
}
rw := &replyWriter{write, flush}
if cmd.ID == 0 && method != proto.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(&proto.Reply{Error: ErrorBadRequest})
return nil
}
if method != proto.MethodTypeConnect && !c.authenticated {
// Client must send connect command first.
rw.write(&proto.Reply{Error: ErrorUnauthorized})
return nil
}
started := time.Now()
switch method {
case proto.MethodTypeConnect:
disconnect = c.handleConnect(params, rw)
case proto.MethodTypeRefresh:
disconnect = c.handleRefresh(params, rw)
case proto.MethodTypeSubscribe:
disconnect = c.handleSubscribe(params, rw)
case proto.MethodTypeSubRefresh:
disconnect = c.handleSubRefresh(params, rw)
case proto.MethodTypeUnsubscribe:
disconnect = c.handleUnsubscribe(params, rw)
case proto.MethodTypePublish:
disconnect = c.handlePublish(params, rw)
case proto.MethodTypePresence:
disconnect = c.handlePresence(params, rw)
case proto.MethodTypePresenceStats:
disconnect = c.handlePresenceStats(params, rw)
case proto.MethodTypeHistory:
disconnect = c.handleHistory(params, rw)
case proto.MethodTypePing:
disconnect = c.handlePing(params, rw)
case proto.MethodTypeRPC:
disconnect = c.handleRPC(params, rw)
case proto.MethodTypeSend:
disconnect = c.handleSend(params, rw)
default:
rw.write(&proto.Reply{Error: ErrorMethodNotFound})
}
commandDurationSummary.WithLabelValues(strings.ToLower(proto.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
}
if c.eventHub.refreshHandler != nil {
reply := c.eventHub.refreshHandler(RefreshEvent{})
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 - time.Now().Unix()
if c.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()
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 proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).DecodeConnect(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding connect", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
resp, disconnect := c.connectCmd(cmd)
if disconnect != nil {
return disconnect
}
if resp.Error != nil {
rw.write(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).EncodeConnectResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding connect", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
rw.write(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handleRefresh(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handleSubscribe(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).DecodeSubscribe(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding subscribe", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
return c.subscribeCmd(cmd, rw)
}
func (c *Client) handleSubRefresh(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handleUnsubscribe(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePublish(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePresence(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePresenceStats(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handleHistory(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).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(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handlePing(params proto.Raw, rw *replyWriter) *Disconnect {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).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(&proto.Reply{Error: resp.Error})
return nil
}
var replyRes []byte
if resp.Result != nil {
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).EncodePingResult(resp.Result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding ping", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
}
rw.write(&proto.Reply{Result: replyRes})
return nil
}
func (c *Client) handleRPC(params proto.Raw, rw *replyWriter) *Disconnect {
if c.eventHub.rpcHandler != nil {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).DecodeRPC(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding rpc", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
rpcReply := c.eventHub.rpcHandler(RPCEvent{
Data: cmd.Data,
})
if rpcReply.Disconnect != nil {
return rpcReply.Disconnect
}
if rpcReply.Error != nil {
rw.write(&proto.Reply{Error: rpcReply.Error})
return nil
}
result := &proto.RPCResult{
Data: rpcReply.Data,
}
var replyRes []byte
replyRes, err = proto.GetResultEncoder(c.transport.Encoding()).EncodeRPCResult(result)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelError, "error encoding rpc", map[string]interface{}{"error": err.Error()}))
return DisconnectServerError
}
rw.write(&proto.Reply{Result: replyRes})
return nil
}
rw.write(&proto.Reply{Error: ErrorNotAvailable})
return nil
}
func (c *Client) handleSend(params proto.Raw, rw *replyWriter) *Disconnect {
if c.eventHub.messageHandler != nil {
cmd, err := proto.GetParamsDecoder(c.transport.Encoding()).DecodeSend(params)
if err != nil {
c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding message", map[string]interface{}{"error": err.Error()}))
return DisconnectBadRequest
}
messageReply := c.eventHub.messageHandler(MessageEvent{
Data: cmd.Data,
})
if messageReply.Disconnect != nil {
return messageReply.Disconnect
}
return nil
}
return nil
}
type connectTokenClaims struct {
Info proto.Raw `json:"info"`
Base64Info string `json:"b64info"`
jwt.StandardClaims
}
type subscribeTokenClaims struct {
Client string `json:"client"`
Channel string `json:"channel"`
Info proto.Raw `json:"info"`
Base64Info string `json:"b64info"`
jwt.StandardClaims
}
// connectCmd handles connect command from client - client must send connect
// command immediately after establishing connection with server.
func (c *Client) connectCmd(cmd *proto.ConnectRequest) (*proto.ConnectResponse, *Disconnect) {
resp := &proto.ConnectResponse{}
c.mu.RLock()
authenticated := c.authenticated
closed := c.closed
c.mu.RUnlock()
if closed {