forked from centrifugal/centrifuge-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1401 lines (1251 loc) · 30.4 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 (
"crypto/tls"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/centrifugal/centrifuge-go/internal/proto"
"github.com/jpillora/backoff"
)
type disconnect struct {
Reason string
Reconnect bool
}
var (
// ErrTimeout ...
ErrTimeout = errors.New("timeout")
// ErrClientClosed ...
ErrClientClosed = errors.New("client closed")
// ErrClientDisconnected ...
ErrClientDisconnected = errors.New("client disconnected")
// ErrClientExpired ...
ErrClientExpired = errors.New("client connection expired")
// ErrReconnectFailed ...
ErrReconnectFailed = errors.New("reconnect failed")
// ErrDuplicateSubscription ...
ErrDuplicateSubscription = errors.New("duplicate subscription")
)
const (
// DefaultReadTimeout ...
DefaultReadTimeout = 5 * time.Second
// DefaultWriteTimeout ...
DefaultWriteTimeout = 1 * time.Second
// DefaultPingInterval ...
DefaultPingInterval = 25 * time.Second
// DefaultPrivateChannelPrefix ...
DefaultPrivateChannelPrefix = "$"
)
// Config contains various client options.
type Config struct {
// PrivateChannelPrefix is private channel prefix.
PrivateChannelPrefix string
// ReadTimeout is how long to wait read operations to complete.
ReadTimeout time.Duration
// WriteTimeout is Websocket write timeout.
WriteTimeout time.Duration
// PingInterval is how often to send ping commands to server.
PingInterval time.Duration
// HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration
// TLSConfig specifies the TLS configuration to use with tls.Client.
// If nil, the default configuration is used.
TLSConfig *tls.Config
// EnableCompression specifies if the client should attempt to negotiate
// per message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
// CookieJar specifies the cookie jar.
// If CookieJar is nil, cookies are not sent in requests and ignored
// in responses.
CookieJar http.CookieJar
// Header specifies custom HTTP Header to send.
Header http.Header
}
// DefaultConfig returns Config with default options.
func DefaultConfig() Config {
return Config{
PingInterval: DefaultPingInterval,
ReadTimeout: DefaultReadTimeout,
WriteTimeout: DefaultWriteTimeout,
PrivateChannelPrefix: DefaultPrivateChannelPrefix,
Header: http.Header{},
}
}
// PrivateSubEvent contains info required to create PrivateSign when client
// wants to subscribe on private channel.
type PrivateSubEvent struct {
ClientID string
Channel string
}
// ConnectEvent is a connect event context passed to OnConnect callback.
type ConnectEvent struct {
ClientID string
Version string
Data []byte
}
// DisconnectEvent is a disconnect event context passed to OnDisconnect callback.
type DisconnectEvent struct {
Reason string
Reconnect bool
}
// ErrorEvent is an error event context passed to OnError callback.
type ErrorEvent struct {
Message string
}
// MessageEvent is an event for async message from server to client.
type MessageEvent struct {
Data []byte
}
// ConnectHandler is an interface describing how to handle connect event.
type ConnectHandler interface {
OnConnect(*Client, ConnectEvent)
}
// DisconnectHandler is an interface describing how to handle disconnect event.
type DisconnectHandler interface {
OnDisconnect(*Client, DisconnectEvent)
}
// MessageHandler is an interface describing how to async message from server.
type MessageHandler interface {
OnMessage(*Client, MessageEvent)
}
// PrivateSubHandler is an interface describing how to handle private subscription request.
type PrivateSubHandler interface {
OnPrivateSub(*Client, PrivateSubEvent) (string, error)
}
// RefreshHandler is an interface describing how to handle token refresh event.
type RefreshHandler interface {
OnRefresh(*Client) (string, error)
}
// ErrorHandler is an interface describing how to handle error event.
type ErrorHandler interface {
OnError(*Client, ErrorEvent)
}
// EventHub has all event handlers for client.
type EventHub struct {
onConnect ConnectHandler
onDisconnect DisconnectHandler
onPrivateSub PrivateSubHandler
onRefresh RefreshHandler
onError ErrorHandler
onMessage MessageHandler
}
// newEventHub initializes new EventHub.
func newEventHub() *EventHub {
return &EventHub{}
}
// Describe client connection statuses.
const (
DISCONNECTED = iota
CONNECTING
CONNECTED
CLOSED
)
// Client describes client connection to Centrifugo server.
type Client struct {
mutex sync.RWMutex
url string
encoding proto.Encoding
config Config
token string
connectData proto.Raw
transport transport
msgID uint32
status int
id string
subsMutex sync.RWMutex
subs map[string]*Subscription
requestsMutex sync.RWMutex
requests map[uint32]chan proto.Reply
receive chan []byte
closeCh chan struct{}
reconnect bool
reconnectStrategy reconnectStrategy
events *EventHub
paramsEncoder proto.ParamsEncoder
resultDecoder proto.ResultDecoder
commandEncoder proto.CommandEncoder
pushEncoder proto.PushEncoder
pushDecoder proto.PushDecoder
delayPing chan struct{}
}
func (c *Client) nextMsgID() uint32 {
return atomic.AddUint32(&c.msgID, 1)
}
// New initializes Client.
func New(u string, config Config) *Client {
var encoding proto.Encoding
if strings.HasPrefix(u, "ws") {
if strings.Contains(u, "format=protobuf") {
encoding = proto.EncodingProtobuf
} else {
encoding = proto.EncodingJSON
}
} else {
panic(fmt.Sprintf("unsupported connection endpoint: %s", u))
}
c := &Client{
url: u,
encoding: encoding,
subs: make(map[string]*Subscription),
config: config,
requests: make(map[uint32]chan proto.Reply),
reconnect: true,
reconnectStrategy: defaultBackoffReconnect,
paramsEncoder: proto.NewParamsEncoder(encoding),
resultDecoder: proto.NewResultDecoder(encoding),
commandEncoder: proto.NewCommandEncoder(encoding),
pushEncoder: proto.NewPushEncoder(encoding),
pushDecoder: proto.NewPushDecoder(encoding),
delayPing: make(chan struct{}, 32),
events: newEventHub(),
}
return c
}
// OnConnect is a function to handle connect event.
func (c *Client) OnConnect(handler ConnectHandler) {
c.events.onConnect = handler
}
// OnDisconnect is a function to handle disconnect event.
func (c *Client) OnDisconnect(handler DisconnectHandler) {
c.events.onDisconnect = handler
}
// OnPrivateSub needed to handle private channel subscriptions.
func (c *Client) OnPrivateSub(handler PrivateSubHandler) {
c.events.onPrivateSub = handler
}
// OnRefresh handles refresh event when client's credentials expired and must be refreshed.
func (c *Client) OnRefresh(handler RefreshHandler) {
c.events.onRefresh = handler
}
// OnError is a function that will receive unhandled errors for logging.
func (c *Client) OnError(handler ErrorHandler) {
c.events.onError = handler
}
// OnMessage allows to process async message from server to client.
func (c *Client) OnMessage(handler MessageHandler) {
c.events.onMessage = handler
}
// SetToken allows to set connection JWT token to let client
// authenticate itself on connect.
func (c *Client) SetToken(token string) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.token = token
}
// SetConnectData allows to set data to send in connect message.
func (c *Client) SetConnectData(data proto.Raw) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.connectData = data
}
// SetHeader allows to set custom header sent in Upgrade HTTP request.
func (c *Client) SetHeader(key, value string) {
if c.config.Header == nil {
c.config.Header = http.Header{}
}
c.config.Header.Set(key, value)
}
func (c *Client) subscribed(channel string) bool {
c.subsMutex.RLock()
_, ok := c.subs[channel]
c.subsMutex.RUnlock()
return ok
}
// clientID returns client ID of this connection. It only available after
// connection was established and authorized.
func (c *Client) clientID() string {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.id
}
func (c *Client) handleError(err error) {
var handler ErrorHandler
if c.events != nil && c.events.onError != nil {
handler = c.events.onError
}
if handler != nil {
handler.OnError(c, ErrorEvent{Message: err.Error()})
}
}
// Send data to server asynchronously.
func (c *Client) Send(data []byte) error {
cmd := &proto.Command{
Method: proto.MethodTypeSend,
}
params := &proto.SendRequest{
Data: data,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
return err
}
cmd.Params = paramsData
return c.send(cmd)
}
// RPC allows to make RPC – send data to server ant wait for response.
// RPC handler must be registered on server.
func (c *Client) RPC(data []byte) ([]byte, error) {
cmd := &proto.Command{
ID: c.nextMsgID(),
Method: proto.MethodTypeRPC,
}
params := &proto.RPCRequest{
Data: data,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
return nil, fmt.Errorf("encode error: %v", err)
}
cmd.Params = paramsData
r, err := c.sendSync(cmd)
if err != nil {
return nil, err
}
if r.Error != nil {
return nil, r.Error
}
var res proto.RPCResult
err = c.resultDecoder.Decode(r.Result, &res)
if err != nil {
return nil, err
}
return res.Data, nil
}
// Close closes Client connection and cleans up state.
func (c *Client) Close() error {
c.mutex.Lock()
c.status = CLOSED
c.mutex.Unlock()
return c.Disconnect()
}
// close clean ups ws connection and all outgoing requests.
// Instance Lock must be held outside.
func (c *Client) close() {
c.requestsMutex.Lock()
for uid, ch := range c.requests {
close(ch)
delete(c.requests, uid)
}
c.requestsMutex.Unlock()
if c.transport != nil {
c.transport.Close()
c.transport = nil
}
}
func (c *Client) handleDisconnect(d *disconnect) {
if d == nil {
d = &disconnect{
Reason: "connection closed",
Reconnect: true,
}
}
c.mutex.Lock()
if c.status == DISCONNECTED || c.status == CLOSED {
c.mutex.Unlock()
return
}
c.reconnect = d.Reconnect
c.requestsMutex.Lock()
for uid, ch := range c.requests {
close(ch)
delete(c.requests, uid)
}
c.requestsMutex.Unlock()
if c.transport != nil {
c.transport.Close()
c.transport = nil
}
select {
case <-c.closeCh:
default:
close(c.closeCh)
}
c.status = DISCONNECTED
c.subsMutex.RLock()
unsubs := make([]*Subscription, 0, len(c.subs))
for _, s := range c.subs {
unsubs = append(unsubs, s)
}
c.subsMutex.RUnlock()
for _, s := range unsubs {
s.triggerOnUnsubscribe(true)
if c.reconnect {
s.mu.Lock()
s.recover = true
s.mu.Unlock()
} else {
s.mu.Lock()
s.recover = false
s.mu.Unlock()
}
}
reconnect := c.reconnect
c.mutex.Unlock()
var handler DisconnectHandler
if c.events != nil && c.events.onDisconnect != nil {
handler = c.events.onDisconnect
}
if handler != nil {
handler.OnDisconnect(c, DisconnectEvent{Reason: d.Reason, Reconnect: reconnect})
}
if !reconnect {
return
}
err := c.reconnectStrategy.reconnect(c)
if err != nil {
c.Close()
}
}
type reconnectStrategy interface {
reconnect(c *Client) error
}
type backoffReconnect struct {
// NumReconnect is maximum number of reconnect attempts, 0 means reconnect forever.
NumReconnect int
// Factor is the multiplying factor for each increment step.
Factor float64
// Jitter eases contention by randomizing backoff steps.
Jitter bool
// MinMilliseconds is a minimum value of the reconnect interval.
MinMilliseconds int
// MaxMilliseconds is a maximum value of the reconnect interval.
MaxMilliseconds int
}
var defaultBackoffReconnect = &backoffReconnect{
NumReconnect: 0,
MinMilliseconds: 100,
MaxMilliseconds: 20 * 1000,
Factor: 2,
Jitter: true,
}
func (r *backoffReconnect) reconnect(c *Client) error {
b := &backoff.Backoff{
Min: time.Duration(r.MinMilliseconds) * time.Millisecond,
Max: time.Duration(r.MaxMilliseconds) * time.Millisecond,
Factor: r.Factor,
Jitter: r.Jitter,
}
reconnects := 0
for {
if r.NumReconnect > 0 && reconnects >= r.NumReconnect {
break
}
time.Sleep(b.Duration())
reconnects++
err := c.doReconnect()
if err != nil {
if err == ErrClientClosed {
return nil
}
continue
}
// successfully reconnected
return nil
}
return ErrReconnectFailed
}
func (c *Client) doReconnect() error {
c.mutex.RLock()
if c.status == CLOSED {
c.mutex.RUnlock()
return ErrClientClosed
}
c.mutex.RUnlock()
err := c.connect()
if err != nil {
c.close()
return err
}
err = c.resubscribe()
if err != nil {
// we need just to close the connection and outgoing requests here
// but preserve all subscriptions.
c.close()
return err
}
return nil
}
func (c *Client) pinger(closeCh chan struct{}) {
timeout := time.Duration(c.config.PingInterval)
for {
select {
case <-c.delayPing:
case <-time.After(timeout):
err := c.sendPing()
if err != nil {
go c.handleDisconnect(&disconnect{Reason: "no ping", Reconnect: true})
return
}
case <-closeCh:
return
}
}
}
func (c *Client) reader(t transport, closeCh chan struct{}) {
for {
reply, disconnect, err := t.Read()
if err != nil {
c.handleDisconnect(disconnect)
return
}
select {
case <-closeCh:
return
default:
select {
case c.delayPing <- struct{}{}:
default:
}
err := c.handle(reply)
if err != nil {
c.handleError(err)
}
}
}
}
func (c *Client) handle(reply *proto.Reply) error {
if reply.ID > 0 {
c.requestsMutex.RLock()
if waiter, ok := c.requests[reply.ID]; ok {
waiter <- *reply
}
c.requestsMutex.RUnlock()
} else {
push, err := c.pushDecoder.Decode(reply.Result)
if err != nil {
c.handleError(err)
return err
}
err = c.handlePush(*push)
if err != nil {
c.handleError(err)
}
}
return nil
}
func (c *Client) handleMessage(msg proto.Message) error {
var handler MessageHandler
if c.events != nil && c.events.onMessage != nil {
handler = c.events.onMessage
}
if handler != nil {
ctx := MessageEvent{Data: msg.Data}
handler.OnMessage(c, ctx)
}
return nil
}
func (c *Client) handlePush(msg proto.Push) error {
switch msg.Type {
case proto.PushTypeMessage:
m, err := c.pushDecoder.DecodeMessage(msg.Data)
if err != nil {
return err
}
c.handleMessage(*m)
case proto.PushTypeUnsub:
m, err := c.pushDecoder.DecodeUnsub(msg.Data)
if err != nil {
return err
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[string(channel)]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handleUnsub(*m)
case proto.PushTypePublication:
m, err := c.pushDecoder.DecodePublication(msg.Data)
if err != nil {
return err
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[string(channel)]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handlePublication(*m)
case proto.PushTypeJoin:
m, err := c.pushDecoder.DecodeJoin(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[string(channel)]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handleJoin(m.Info)
case proto.PushTypeLeave:
m, err := c.pushDecoder.DecodeLeave(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[string(channel)]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handleLeave(m.Info)
default:
return nil
}
return nil
}
// Connect dials to server and sends connect message.
func (c *Client) Connect() error {
c.mutex.Lock()
if c.status == CONNECTED || c.status == CONNECTING {
c.mutex.Unlock()
return nil
}
if c.status == CLOSED {
c.mutex.Unlock()
return ErrClientClosed
}
c.status = CONNECTING
c.reconnect = true
c.mutex.Unlock()
err := c.connect()
if err != nil {
if c.transport == nil {
c.handleError(err)
c.handleDisconnect(nil)
}
return nil
}
err = c.resubscribe()
if err != nil {
// we need just to close the connection and outgoing requests here
// but preserve all subscriptions.
c.close()
return nil
}
return nil
}
func (c *Client) connect() error {
c.mutex.Lock()
if c.status == CONNECTED {
c.mutex.Unlock()
return nil
}
c.status = CONNECTING
c.closeCh = make(chan struct{})
c.mutex.Unlock()
wsConfig := websocketConfig{
TLSConfig: c.config.TLSConfig,
HandshakeTimeout: c.config.HandshakeTimeout,
EnableCompression: c.config.EnableCompression,
CookieJar: c.config.CookieJar,
Header: c.config.Header,
}
t, err := newWebsocketTransport(c.url, c.encoding, wsConfig)
if err != nil {
return err
}
c.mutex.Lock()
if c.status == DISCONNECTED {
c.mutex.Unlock()
return nil
}
c.transport = t
closeCh := make(chan struct{})
c.closeCh = closeCh
c.receive = make(chan []byte, 64)
c.mutex.Unlock()
go c.reader(t, closeCh)
var res proto.ConnectResult
res, err = c.sendConnect()
if err != nil {
refreshed := false
if e, ok := err.(*Error); ok {
if e.Code == 109 {
// Try to refresh token and repeat connection attempt.
err = c.refreshToken()
if err != nil {
c.Close()
return err
}
res, err = c.sendConnect()
if err != nil {
c.Close()
return err
}
refreshed = true
}
}
if !refreshed {
return err
}
}
c.mutex.Lock()
c.id = res.Client
prevStatus := c.status
c.status = CONNECTED
c.mutex.Unlock()
if res.Expires {
go func(interval uint32) {
select {
case <-closeCh:
return
case <-time.After(time.Duration(interval) * time.Second):
c.sendRefresh(closeCh)
}
}(res.TTL)
}
go c.pinger(closeCh)
if c.events != nil && c.events.onConnect != nil && prevStatus != CONNECTED {
handler := c.events.onConnect
ev := ConnectEvent{
ClientID: c.clientID(),
Version: res.Version,
Data: res.Data,
}
handler.OnConnect(c, ev)
}
return nil
}
func (c *Client) resubscribe() error {
c.subsMutex.RLock()
defer c.subsMutex.RUnlock()
for _, sub := range c.subs {
err := sub.resubscribe(true)
if err != nil {
return err
}
}
return nil
}
func (c *Client) disconnect(reconnect bool) error {
c.mutex.Lock()
c.reconnect = reconnect
c.mutex.Unlock()
c.handleDisconnect(&disconnect{
Reconnect: reconnect,
Reason: "clean disconnect",
})
return nil
}
// Disconnect client from server.
func (c *Client) Disconnect() error {
c.disconnect(false)
return nil
}
func (c *Client) refreshToken() error {
var handler RefreshHandler
if c.events != nil && c.events.onRefresh != nil {
handler = c.events.onRefresh
}
if handler == nil {
return errors.New("RefreshHandler must be set to handle expired token")
}
token, err := handler.OnRefresh(c)
if err != nil {
return err
}
c.mutex.Lock()
c.token = token
c.mutex.Unlock()
return nil
}
func (c *Client) sendRefresh(closeCh chan struct{}) error {
err := c.refreshToken()
if err != nil {
return err
}
c.mutex.RLock()
cmd := &proto.Command{
ID: c.nextMsgID(),
Method: proto.MethodTypeRefresh,
}
params := &proto.RefreshRequest{
Token: c.token,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
c.mutex.RUnlock()
return err
}
cmd.Params = paramsData
c.mutex.RUnlock()
r, err := c.sendSync(cmd)
if err != nil {
return err
}
if r.Error != nil {
return r.Error
}
var res proto.RefreshResult
err = c.resultDecoder.Decode(r.Result, &res)
if err != nil {
return err
}
if res.Expires {
go func(interval uint32) {
select {
case <-closeCh:
return
case <-time.After(time.Duration(interval) * time.Second):
c.sendRefresh(closeCh)
}
}(res.TTL)
}
return nil
}
func (c *Client) sendSubRefresh(channel string) error {
sub, ok := c.subs[channel]
if !ok {
return nil
}
if sub.Status() != SUBSCRIBED {
return nil
}
token, err := c.privateSign(channel)
if err != nil {
return err
}
c.mutex.RLock()
cmd := &proto.Command{
ID: c.nextMsgID(),
Method: proto.MethodTypeSubRefresh,
}
params := &proto.SubRefreshRequest{
Channel: channel,
Token: token,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
c.mutex.RUnlock()
return err
}
cmd.Params = paramsData
c.mutex.RUnlock()
r, err := c.sendSync(cmd)
if err != nil {
return err
}
if r.Error != nil {
return r.Error
}
var res proto.SubRefreshResult
err = c.resultDecoder.Decode(r.Result, &res)
if err != nil {
return err
}
if res.Expires {
if sub.Status() != SUBSCRIBED {
return nil
}
go func(interval uint32) {
select {
case <-c.closeCh:
return
case <-time.After(time.Duration(interval) * time.Second):
c.sendSubRefresh(channel)
}
}(res.TTL)
}
return nil
}
func (c *Client) sendConnect() (proto.ConnectResult, error) {
cmd := &proto.Command{
ID: uint32(c.nextMsgID()),
Method: proto.MethodTypeConnect,
}
c.mutex.RLock()
if c.token != "" || c.connectData != nil {
params := &proto.ConnectRequest{}
if c.token != "" {
params.Token = c.token
}
if c.connectData != nil {
params.Data = c.connectData
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
c.mutex.RUnlock()
return proto.ConnectResult{}, err
}
cmd.Params = paramsData
}
c.mutex.RUnlock()
r, err := c.sendSync(cmd)
if err != nil {
return proto.ConnectResult{}, err
}
if r.Error != nil {
return proto.ConnectResult{}, r.Error
}