forked from centrifugal/centrifuge-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
1305 lines (1173 loc) · 27.9 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 (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/centrifugal/protocol"
"github.com/jpillora/backoff"
)
type disconnect struct {
Reason string
Reconnect bool
}
// Describe client connection statuses.
const (
DISCONNECTED = iota
CONNECTING
CONNECTED
RECONNECTING
CLOSED
)
// Client describes client connection to Centrifugo server.
type Client struct {
mutex sync.RWMutex
url string
encoding protocol.Type
config WsConfig
token string
connectData protocol.Raw
transport transport
msgID uint32
status int
id string
subsMutex sync.RWMutex
subs map[string]*Subscription
requestsMutex sync.RWMutex
requests map[uint32]chan protocol.Reply
receive chan []byte
closeCh chan struct{}
reconnect bool
reconnectAttempts int
reconnectStrategy reconnectStrategy
events *EventHub
paramsEncoder protocol.ParamsEncoder
resultDecoder protocol.ResultDecoder
commandEncoder protocol.CommandEncoder
pushEncoder protocol.PushEncoder
pushDecoder protocol.PushDecoder
delayPing chan struct{}
}
func (c *Client) nextMsgID() uint32 {
return atomic.AddUint32(&c.msgID, 1)
}
func newPushEncoder(enc protocol.Type) protocol.PushEncoder {
if enc == protocol.TypeJSON {
return protocol.NewJSONPushEncoder()
}
return protocol.NewProtobufPushEncoder()
}
func newPushDecoder(enc protocol.Type) protocol.PushDecoder {
if enc == protocol.TypeJSON {
return protocol.NewJSONPushDecoder()
}
return protocol.NewProtobufPushDecoder()
}
func newReplyDecoder(enc protocol.Type, data []byte) protocol.ReplyDecoder {
if enc == protocol.TypeJSON {
return protocol.NewJSONReplyDecoder(data)
}
return protocol.NewProtobufReplyDecoder(data)
}
func newResultDecoder(enc protocol.Type) protocol.ResultDecoder {
if enc == protocol.TypeJSON {
return protocol.NewJSONResultDecoder()
}
return protocol.NewProtobufResultDecoder()
}
func newParamsEncoder(enc protocol.Type) protocol.ParamsEncoder {
if enc == protocol.TypeJSON {
return protocol.NewJSONParamsEncoder()
}
return protocol.NewProtobufParamsEncoder()
}
func newCommandEncoder(enc protocol.Type) protocol.CommandEncoder {
if enc == protocol.TypeJSON {
return protocol.NewJSONCommandEncoder()
}
return protocol.NewProtobufCommandEncoder()
}
// New initializes Client.
func New(u string, config Config) *Client {
var encoding protocol.Type
if strings.HasPrefix(u, "ws") {
if strings.Contains(u, "format=protobuf") {
encoding = protocol.TypeProtobuf
} else {
encoding = protocol.TypeJSON
}
} else {
panic(fmt.Sprintf("unsupported connection endpoint: %s", u))
}
c := &Client{
url: u,
encoding: encoding,
subs: make(map[string]*Subscription),
config: config.WsConfig,
requests: make(map[uint32]chan protocol.Reply),
reconnect: true,
reconnectStrategy: config.getBackoffReconnect(),
paramsEncoder: newParamsEncoder(encoding),
resultDecoder: newResultDecoder(encoding),
commandEncoder: newCommandEncoder(encoding),
pushEncoder: newPushEncoder(encoding),
pushDecoder: newPushDecoder(encoding),
delayPing: make(chan struct{}, 32),
events: newEventHub(),
}
return c
}
// 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 protocol.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 := &protocol.Command{
Method: protocol.MethodTypeSend,
}
params := &protocol.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) {
return c.NamedRPC("", data)
}
// NamedRPC allows to make RPC – send data to server ant wait for response.
// RPC handler must be registered on server.
// In contrast to RPC method it allows to pass method name.
func (c *Client) NamedRPC(method string, data []byte) ([]byte, error) {
cmd := &protocol.Command{
ID: c.nextMsgID(),
Method: protocol.MethodTypeRPC,
}
params := &protocol.RPCRequest{
Data: data,
Method: method,
}
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 protocol.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 {
err := c.Disconnect()
c.mutex.Lock()
c.status = CLOSED
c.mutex.Unlock()
return err
}
// 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
}
isReconnecting := c.status == RECONNECTING
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 && !isReconnecting {
handler.OnDisconnect(c, DisconnectEvent{Reason: d.Reason, Reconnect: reconnect})
}
if !reconnect {
return
}
go func() {
c.mutex.Lock()
duration, err := c.reconnectStrategy.timeBeforeNextAttempt(c.reconnectAttempts)
c.mutex.Unlock()
if err != nil {
c.handleError(err)
return
}
time.Sleep(duration)
c.mutex.Lock()
c.reconnectAttempts++
if !c.reconnect {
c.mutex.Unlock()
return
}
c.mutex.Unlock()
err = c.connectFromScratch(true)
if err != nil {
c.handleError(err)
}
}()
}
type reconnectStrategy interface {
timeBeforeNextAttempt(attempt int) (time.Duration, 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
}
func (c *Config) getBackoffReconnect() (bor *backoffReconnect) {
bor = &backoffReconnect{
NumReconnect: c.BackoffConfig.NumReconnect,
Factor: c.BackoffConfig.Factor,
Jitter: c.BackoffConfig.Jitter,
MaxMilliseconds: c.BackoffConfig.MaxMilliseconds,
MinMilliseconds: c.BackoffConfig.MinMilliseconds,
}
return
}
func (r *backoffReconnect) timeBeforeNextAttempt(attempt int) (time.Duration, error) {
b := &backoff.Backoff{
Min: time.Duration(r.MinMilliseconds) * time.Millisecond,
Max: time.Duration(r.MaxMilliseconds) * time.Millisecond,
Factor: r.Factor,
Jitter: r.Jitter,
}
if r.NumReconnect > 0 && attempt >= r.NumReconnect {
return 0, ErrReconnectFailed
}
return b.ForAttempt(float64(attempt)), nil
}
func (c *Client) pinger(closeCh chan struct{}) {
timeout := 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, syncReplyCh, asyncReplyCh chan *protocol.Reply, closeCh chan struct{}) {
for {
reply, disconnect, err := t.Read()
if err != nil {
go c.handleDisconnect(disconnect)
return
}
select {
case <-closeCh:
return
default:
select {
case c.delayPing <- struct{}{}:
default:
}
err := c.handle(reply, syncReplyCh, asyncReplyCh, closeCh)
if err != nil {
c.handleError(err)
}
}
}
}
func (c *Client) processSyncReplies(syncReplyCh chan *protocol.Reply, closeCh chan struct{}) {
for {
select {
case reply := <-syncReplyCh:
c.requestsMutex.RLock()
if waiter, ok := c.requests[reply.ID]; ok {
waiter <- *reply
}
c.requestsMutex.RUnlock()
case <-closeCh:
close(syncReplyCh)
return
}
}
}
func (c *Client) processAsyncReplies(asyncReplyCh chan *protocol.Reply, closeCh chan struct{}) {
for {
select {
case reply := <-asyncReplyCh:
push, err := c.pushDecoder.Decode(reply.Result)
if err != nil {
c.handleError(err)
continue
}
err = c.handlePush(*push)
if err != nil {
c.handleError(err)
}
case <-closeCh:
close(asyncReplyCh)
return
}
}
}
func (c *Client) handle(reply *protocol.Reply, syncReplyCh, asyncReplyCh chan *protocol.Reply, closeCh chan struct{}) error {
if reply.ID > 0 {
syncReplyCh <- reply
} else {
select {
case asyncReplyCh <- reply:
case <-closeCh:
return nil
}
}
return nil
}
func (c *Client) handleMessage(msg protocol.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 protocol.Push) error {
switch msg.Type {
case protocol.PushTypeMessage:
m, err := c.pushDecoder.DecodeMessage(msg.Data)
if err != nil {
return err
}
_ = c.handleMessage(*m)
case protocol.PushTypeUnsub:
m, err := c.pushDecoder.DecodeUnsub(msg.Data)
if err != nil {
return err
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[channel]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handleUnsub(*m)
case protocol.PushTypePublication:
m, err := c.pushDecoder.DecodePublication(msg.Data)
if err != nil {
return err
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[channel]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handlePublication(*m)
case protocol.PushTypeJoin:
m, err := c.pushDecoder.DecodeJoin(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[channel]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handleJoin(m.Info)
case protocol.PushTypeLeave:
m, err := c.pushDecoder.DecodeLeave(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.subsMutex.RLock()
sub, ok := c.subs[channel]
c.subsMutex.RUnlock()
if !ok {
return nil
}
sub.handleLeave(m.Info)
default:
return nil
}
return nil
}
func (c *Client) connectFromScratch(isReconnect bool) error {
c.mutex.Lock()
if c.status == CONNECTED || c.status == CONNECTING || c.status == RECONNECTING {
c.mutex.Unlock()
return nil
}
if c.status == CLOSED {
c.mutex.Unlock()
return ErrClientClosed
}
if isReconnect {
c.status = RECONNECTING
} else {
c.status = CONNECTING
}
c.reconnect = true
c.mutex.Unlock()
err := c.connect(isReconnect)
if err != nil {
if c.transport == nil {
c.handleError(err)
go 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.handleError(err)
c.close()
return nil
}
// Looks like we successfully reconnected so can reset reconnect attempts.
c.mutex.Lock()
c.reconnectAttempts = 0
c.mutex.Unlock()
return nil
}
// Connect dials to server and sends connect message.
func (c *Client) Connect() error {
return c.connectFromScratch(false)
}
func isTokenExpiredError(err error) bool {
if e, ok := err.(*Error); ok && e.Code == 109 {
return true
}
return false
}
func (c *Client) connect(isReconnect bool) error {
c.mutex.Lock()
if c.status == CONNECTED {
c.mutex.Unlock()
return nil
}
if isReconnect {
c.status = RECONNECTING
} else {
c.status = CONNECTING
}
c.closeCh = make(chan struct{})
c.mutex.Unlock()
wsConfig := websocketConfig{
NetDialContext: c.config.NetDialContext,
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()
syncReplyCh := make(chan *protocol.Reply)
asyncReplyCh := make(chan *protocol.Reply, 128)
go c.reader(t, syncReplyCh, asyncReplyCh, closeCh)
go c.processSyncReplies(syncReplyCh, closeCh)
go c.processAsyncReplies(asyncReplyCh, closeCh)
var res protocol.ConnectResult
res, err = c.sendConnect()
if err != nil {
refreshed := false
if isTokenExpiredError(err) {
// 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 {
return c.disconnect(false)
}
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 := &protocol.Command{
ID: c.nextMsgID(),
Method: protocol.MethodTypeRefresh,
}
params := &protocol.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 protocol.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
}
c.mutex.RLock()
clientID := c.id
c.mutex.RUnlock()
token, err := c.privateSign(channel)
if err != nil {
return err
}
c.mutex.RLock()
if c.id != clientID {
c.mutex.RUnlock()
return nil
}
cmd := &protocol.Command{
ID: c.nextMsgID(),
Method: protocol.MethodTypeSubRefresh,
}
params := &protocol.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 protocol.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() (protocol.ConnectResult, error) {
cmd := &protocol.Command{
ID: c.nextMsgID(),
Method: protocol.MethodTypeConnect,
}
c.mutex.RLock()
if c.token != "" || c.connectData != nil {
params := &protocol.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 protocol.ConnectResult{}, err
}
cmd.Params = paramsData
}
c.mutex.RUnlock()
r, err := c.sendSync(cmd)
if err != nil {
return protocol.ConnectResult{}, err
}
if r.Error != nil {
return protocol.ConnectResult{}, r.Error
}
var res protocol.ConnectResult
err = c.resultDecoder.Decode(r.Result, &res)
if err != nil {
return protocol.ConnectResult{}, err
}
return res, nil
}
func (c *Client) privateSign(channel string) (string, error) {
var token string
if strings.HasPrefix(channel, c.config.PrivateChannelPrefix) && c.events != nil {
handler := c.events.onPrivateSub
if handler != nil {
ev := PrivateSubEvent{
ClientID: c.clientID(),
Channel: channel,
}
ps, err := handler.OnPrivateSub(c, ev)
if err != nil {
return "", err
}
token = ps
} else {
return "", errors.New("PrivateSubHandler must be set to handle private channel subscriptions")
}
}
return token, nil
}
// NewSubscription allows to create new subscription on channel.
func (c *Client) NewSubscription(channel string) (*Subscription, error) {
c.subsMutex.Lock()
var sub *Subscription
if _, ok := c.subs[channel]; ok {
c.subsMutex.Unlock()
return nil, ErrDuplicateSubscription
}
sub = c.newSubscription(channel)
c.subs[channel] = sub
c.subsMutex.Unlock()
return sub, nil
}
type streamPosition struct {
Seq uint32
Gen uint32
Offset uint64
Epoch string
}
func (c *Client) sendSubscribe(channel string, recover bool, streamPos streamPosition, token string) (protocol.SubscribeResult, error) {
params := &protocol.SubscribeRequest{
Channel: channel,
}
if recover {
params.Recover = true
if streamPos.Seq > 0 || streamPos.Gen > 0 {
params.Seq = streamPos.Seq
params.Gen = streamPos.Gen
} else if streamPos.Offset > 0 {
params.Offset = streamPos.Offset
}
params.Epoch = streamPos.Epoch
}
if token != "" {
params.Token = token
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
return protocol.SubscribeResult{}, err
}