forked from centrifugal/centrifuge-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
1657 lines (1513 loc) · 37.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 (
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/centrifugal/protocol"
)
type disconnect struct {
Reason string
Reconnect bool
}
// Describe client connection statuses.
const (
DISCONNECTED = iota
CONNECTING
CONNECTED
CLOSED
)
type serverSub struct {
Offset uint64
Epoch string
Recoverable bool
}
// Client represents client connection to Centrifugo or Centrifuge
// library based server. It provides methods to set various event
// handlers, subscribe to channels, call RPC commands etc. Call client
// Connect method to trigger actual connection with server. Call client
// Close method to clean up state when you don't need client instance
// anymore.
type Client struct {
futureID uint64
msgID uint32
mu sync.RWMutex
url string
protocolType protocol.Type
config Config
token string
connectData protocol.Raw
transport transport
status int
id string
subs map[string]*Subscription
serverSubs map[string]*serverSub
requestsMu sync.RWMutex
requests map[uint32]request
receive chan []byte
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{}
reconnectCh chan struct{}
closeCh chan struct{}
connectFutures map[uint64]connectFuture
hasBeenDisconnected bool
cbQueue *cbQueue
}
func (c *Client) nextMsgID() uint32 {
return atomic.AddUint32(&c.msgID, 1)
}
// New initializes Client. After client initialized call its Connect method
// to trigger connection establishment with server.
// Deprecated: if you are using Centrifuge >= v0.18.0 or Centrifugo >= 3 then use NewJsonClient or NewProtobufClient.
//goland:noinspection GoUnusedExportedFunction
func New(u string, config Config) *Client {
return newClient(u, strings.Contains(u, "format=protobuf"), config)
}
// NewJsonClient initializes Client which uses JSON-based protocol internally.
// After client initialized call its Connect method.
func NewJsonClient(u string, config Config) *Client {
return newClient(u, false, config)
}
// NewProtobufClient initializes Client which uses Protobuf-based protocol internally.
// After client initialized call its Connect method.
func NewProtobufClient(u string, config Config) *Client {
return newClient(u, true, config)
}
func newClient(u string, isProtobuf bool, config Config) *Client {
if !strings.HasPrefix(u, "ws") {
panic(fmt.Sprintf("unsupported connection endpoint: %s", u))
}
protocolType := protocol.TypeJSON
if isProtobuf {
protocolType = protocol.TypeProtobuf
}
c := &Client{
url: u,
config: config,
status: DISCONNECTED,
protocolType: protocolType,
subs: make(map[string]*Subscription),
serverSubs: make(map[string]*serverSub),
requests: make(map[uint32]request),
reconnectStrategy: defaultBackoffReconnect,
paramsEncoder: newParamsEncoder(protocolType),
resultDecoder: newResultDecoder(protocolType),
commandEncoder: newCommandEncoder(protocolType),
pushEncoder: newPushEncoder(protocolType),
pushDecoder: newPushDecoder(protocolType),
delayPing: make(chan struct{}, 32),
reconnectCh: make(chan struct{}, 1),
closeCh: make(chan struct{}),
events: newEventHub(),
reconnect: true,
connectFutures: make(map[uint64]connectFuture),
}
// Create the async callback queue.
c.cbQueue = &cbQueue{}
c.cbQueue.cond = sync.NewCond(&c.cbQueue.mu)
go c.cbQueue.dispatch()
// Start reconnect management goroutine.
go c.reconnectRoutine()
return c
}
// SetToken allows to set connection token to let client
// authenticate itself on connect.
func (c *Client) SetToken(token string) {
c.mu.Lock()
defer c.mu.Unlock()
c.token = token
}
// SetConnectData allows to set data to send in connect command.
func (c *Client) SetConnectData(data []byte) {
c.mu.Lock()
defer c.mu.Unlock()
c.connectData = data
}
// SetHeader allows to set custom header to be 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) connected() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.status == CONNECTED
}
func (c *Client) subscribed(channel string) bool {
c.mu.RLock()
_, ok := c.subs[channel]
c.mu.RUnlock()
return ok
}
// clientID returns unique ID of this connection which is set by server after connect.
// It only available after connection was established and authorized.
func (c *Client) clientID() string {
c.mu.RLock()
defer c.mu.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 {
c.runHandler(func() {
handler.OnError(c, ErrorEvent{Message: err.Error()})
})
}
}
// Send message to server without waiting for response.
// Message handler must be registered on server.
func (c *Client) Send(data []byte) error {
cmd := &protocol.Command{
Method: protocol.Command_SEND,
}
params := &protocol.SendRequest{
Data: data,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
return err
}
cmd.Params = paramsData
return c.send(cmd)
}
// RPCResult contains data returned from server as RPC result.
type RPCResult struct {
Data []byte
}
// RPC allows to make RPC – send data to server and wait for response.
// RPC handler must be registered on server.
func (c *Client) RPC(data []byte) (RPCResult, 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) (RPCResult, error) {
resCh := make(chan RPCResult, 1)
errCh := make(chan error, 1)
c.rpc(method, data, func(result RPCResult, err error) {
resCh <- result
errCh <- err
})
return <-resCh, <-errCh
}
func (c *Client) rpc(method string, data []byte, fn func(RPCResult, error)) {
cmd := &protocol.Command{
Id: c.nextMsgID(),
Method: protocol.Command_RPC,
}
params := &protocol.RPCRequest{
Data: data,
Method: method,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
fn(RPCResult{}, fmt.Errorf("encode error: %v", err))
return
}
cmd.Params = paramsData
err = c.sendAsync(cmd, func(r *protocol.Reply, err error) {
if err != nil {
fn(RPCResult{}, err)
return
}
if r.Error != nil {
fn(RPCResult{}, errorFromProto(r.Error))
return
}
var res protocol.RPCResult
err = c.resultDecoder.Decode(r.Result, &res)
if err != nil {
fn(RPCResult{}, err)
return
}
fn(RPCResult{Data: res.Data}, nil)
})
if err != nil {
fn(RPCResult{}, err)
return
}
}
// Close closes Client forever and cleans up state.
func (c *Client) Close() error {
err := c.Disconnect()
c.mu.Lock()
if c.status == CLOSED {
c.mu.Unlock()
return nil
}
c.cbQueue.close()
close(c.closeCh)
c.status = CLOSED
c.mu.Unlock()
return err
}
// reconnectRoutine manages re-connections to a server. It does this using
// reconnectStrategy which is exponential back-off by default. It also ensures
// that no more than one connection attempt happens concurrently.
func (c *Client) reconnectRoutine() {
var semaphore chan struct{}
for {
select {
case <-c.closeCh:
return
case _, ok := <-c.reconnectCh:
if !ok {
return
}
if semaphore != nil {
<-semaphore
}
semaphore = make(chan struct{}, 1)
c.mu.RLock()
duration, err := c.reconnectStrategy.timeBeforeNextAttempt(c.reconnectAttempts)
c.mu.RUnlock()
if err != nil {
c.handleError(err)
return
}
select {
case <-c.closeCh:
case <-time.After(duration):
}
c.mu.Lock()
if c.status != CONNECTING {
c.mu.Unlock()
semaphore <- struct{}{}
continue
}
c.reconnectAttempts++
if !c.reconnect {
c.mu.Unlock()
semaphore <- struct{}{}
continue
}
c.mu.Unlock()
err = c.connectFromScratch(true, func() {
semaphore <- struct{}{}
})
if err != nil {
c.handleError(err)
}
}
}
}
func (c *Client) handleDisconnect(d *disconnect) {
if d == nil {
d = &disconnect{
Reason: "connection closed",
Reconnect: true,
}
}
c.mu.Lock()
if c.status == DISCONNECTED || c.status == CLOSED {
c.mu.Unlock()
return
}
c.requestsMu.Lock()
reqs := make(map[uint32]request, len(c.requests))
for uid, req := range c.requests {
reqs[uid] = req
}
c.requests = make(map[uint32]request)
c.requestsMu.Unlock()
if c.transport != nil {
_ = c.transport.Close()
c.transport = nil
}
subsToUnsubscribe := make([]*Subscription, 0, len(c.subs))
for _, s := range c.subs {
subsToUnsubscribe = append(subsToUnsubscribe, s)
}
serverSubsToUnsubscribe := make([]string, 0, len(c.serverSubs))
for ch := range c.serverSubs {
serverSubsToUnsubscribe = append(serverSubsToUnsubscribe, ch)
}
needDisconnectEvent := !c.hasBeenDisconnected || c.status == CONNECTED
c.reconnect = d.Reconnect
if c.reconnect {
c.status = CONNECTING
} else {
c.resolveConnectFutures(ErrClientDisconnected)
c.status = DISCONNECTED
}
c.hasBeenDisconnected = true
c.mu.Unlock()
for _, req := range reqs {
if req.cb != nil {
req.cb(nil, ErrClientDisconnected)
}
}
for _, s := range subsToUnsubscribe {
s.triggerOnUnsubscribe(true, d.Reconnect)
}
var handler DisconnectHandler
if c.events != nil && c.events.onDisconnect != nil {
handler = c.events.onDisconnect
}
var serverUnsubscribeHandler ServerUnsubscribeHandler
if c.events != nil && c.events.onServerUnsubscribe != nil {
serverUnsubscribeHandler = c.events.onServerUnsubscribe
}
if handler != nil && needDisconnectEvent {
c.runHandler(func() {
if serverUnsubscribeHandler != nil {
for _, ch := range serverSubsToUnsubscribe {
serverUnsubscribeHandler.OnServerUnsubscribe(c, ServerUnsubscribeEvent{Channel: ch})
}
}
handler.OnDisconnect(c, DisconnectEvent{Reason: d.Reason, Reconnect: d.Reconnect})
})
}
if !d.Reconnect {
return
}
select {
case c.reconnectCh <- struct{}{}:
default:
}
}
func (c *Client) periodicPing(closeCh chan struct{}) {
timeout := c.config.PingInterval
for {
select {
case <-c.delayPing:
case <-time.After(timeout):
c.sendPing(func(err error) {
if err != nil {
go c.handleDisconnect(&disconnect{Reason: "no ping", Reconnect: true})
return
}
})
case <-closeCh:
return
}
}
}
func (c *Client) readOnce(t transport) error {
reply, disconnect, err := t.Read()
if err != nil {
go c.handleDisconnect(disconnect)
return err
}
select {
case c.delayPing <- struct{}{}:
default:
}
err = c.handle(reply)
if err != nil {
c.handleError(err)
}
return nil
}
func (c *Client) reader(t transport, closeCh chan struct{}) {
defer close(closeCh)
for {
err := c.readOnce(t)
if err != nil {
return
}
}
}
func (c *Client) runHandler(fn func()) {
c.cbQueue.push(fn)
}
func (c *Client) handle(reply *protocol.Reply) error {
if reply.Id > 0 {
c.requestsMu.RLock()
req, ok := c.requests[reply.Id]
c.requestsMu.RUnlock()
if ok {
if req.cb != nil {
req.cb(reply, nil)
}
}
c.removeRequest(reply.Id)
} else {
push, err := c.pushDecoder.Decode(reply.Result)
if err != nil {
return err
}
err = c.handlePush(push)
if err != nil {
return err
}
}
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 {
event := MessageEvent{Data: msg.Data}
c.runHandler(func() {
handler.OnMessage(c, event)
})
}
return nil
}
func (c *Client) handlePush(msg *protocol.Push) error {
switch msg.Type {
case protocol.Push_MESSAGE:
m, err := c.pushDecoder.DecodeMessage(msg.Data)
if err != nil {
return err
}
_ = c.handleMessage(m)
case protocol.Push_UNSUBSCRIBE:
m, err := c.pushDecoder.DecodeUnsubscribe(msg.Data)
if err != nil {
return err
}
channel := msg.Channel
c.mu.RLock()
sub, ok := c.subs[channel]
c.mu.RUnlock()
if !ok {
return c.handleServerUnsub(channel, m)
}
sub.handleUnsubscribe(m)
case protocol.Push_PUBLICATION:
m, err := c.pushDecoder.DecodePublication(msg.Data)
if err != nil {
return err
}
channel := msg.Channel
c.mu.RLock()
sub, ok := c.subs[channel]
c.mu.RUnlock()
if !ok {
return c.handleServerPublication(channel, m)
}
sub.handlePublication(m)
case protocol.Push_JOIN:
m, err := c.pushDecoder.DecodeJoin(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.mu.RLock()
sub, ok := c.subs[channel]
c.mu.RUnlock()
if !ok {
return c.handleServerJoin(channel, m)
}
sub.handleJoin(m.Info)
case protocol.Push_LEAVE:
m, err := c.pushDecoder.DecodeLeave(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.mu.RLock()
sub, ok := c.subs[channel]
c.mu.RUnlock()
if !ok {
return c.handleServerLeave(channel, m)
}
sub.handleLeave(m.Info)
case protocol.Push_SUBSCRIBE:
m, err := c.pushDecoder.DecodeSubscribe(msg.Data)
if err != nil {
return nil
}
channel := msg.Channel
c.mu.RLock()
_, ok := c.subs[channel]
c.mu.RUnlock()
if ok {
// Client-side subscription exists.
return nil
}
return c.handleServerSub(channel, m)
default:
return nil
}
return nil
}
func (c *Client) handleServerPublication(channel string, pub *protocol.Publication) error {
c.mu.RLock()
_, ok := c.serverSubs[channel]
c.mu.RUnlock()
if !ok {
return nil
}
var handler ServerPublishHandler
if c.events != nil && c.events.onServerPublish != nil {
handler = c.events.onServerPublish
}
if handler != nil {
c.runHandler(func() {
handler.OnServerPublish(c, ServerPublishEvent{Channel: channel, Publication: pubFromProto(pub)})
c.mu.Lock()
serverSub, ok := c.serverSubs[channel]
if !ok {
c.mu.Unlock()
return
}
if serverSub.Recoverable && pub.Offset > 0 {
serverSub.Offset = pub.Offset
}
c.mu.Unlock()
})
}
return nil
}
func (c *Client) handleServerJoin(channel string, join *protocol.Join) error {
c.mu.RLock()
_, ok := c.serverSubs[channel]
c.mu.RUnlock()
if !ok {
return nil
}
var handler ServerJoinHandler
if c.events != nil && c.events.onServerJoin != nil {
handler = c.events.onServerJoin
}
if handler != nil {
c.runHandler(func() {
handler.OnServerJoin(c, ServerJoinEvent{Channel: channel, ClientInfo: infoFromProto(join.Info)})
})
}
return nil
}
func (c *Client) handleServerLeave(channel string, leave *protocol.Leave) error {
c.mu.RLock()
_, ok := c.serverSubs[channel]
c.mu.RUnlock()
if !ok {
return nil
}
var handler ServerLeaveHandler
if c.events != nil && c.events.onServerLeave != nil {
handler = c.events.onServerLeave
}
if handler != nil {
c.runHandler(func() {
handler.OnServerLeave(c, ServerLeaveEvent{Channel: channel, ClientInfo: infoFromProto(leave.Info)})
})
}
return nil
}
func (c *Client) handleServerSub(channel string, sub *protocol.Subscribe) error {
c.mu.Lock()
_, ok := c.serverSubs[channel]
if ok {
return nil
}
c.serverSubs[channel] = &serverSub{
Offset: sub.Offset,
Epoch: sub.Epoch,
Recoverable: sub.Recoverable,
}
c.mu.Unlock()
if !ok {
return nil
}
var handler ServerSubscribeHandler
if c.events != nil && c.events.onServerSubscribe != nil {
handler = c.events.onServerSubscribe
}
if handler != nil {
c.runHandler(func() {
handler.OnServerSubscribe(c, ServerSubscribeEvent{Channel: channel, Resubscribed: false, Recovered: false})
})
}
return nil
}
func (c *Client) handleServerUnsub(channel string, _ *protocol.Unsubscribe) error {
c.mu.Lock()
_, ok := c.serverSubs[channel]
if ok {
delete(c.serverSubs, channel)
}
c.mu.Unlock()
if !ok {
return nil
}
var handler ServerUnsubscribeHandler
if c.events != nil && c.events.onServerUnsubscribe != nil {
handler = c.events.onServerUnsubscribe
}
if handler != nil {
c.runHandler(func() {
handler.OnServerUnsubscribe(c, ServerUnsubscribeEvent{Channel: channel})
})
}
return nil
}
// Connect dials to server and sends connect message. Will return an error if first dial
// with server failed. In case of failure client will automatically reconnect with
// exponential backoff.
func (c *Client) Connect() error {
return c.connectFromScratch(false, func() {})
}
func (c *Client) connectFromScratch(isReconnect bool, reconnectWaitCB func()) error {
c.mu.Lock()
if isReconnect && c.status == DISCONNECTED {
c.mu.Unlock()
reconnectWaitCB()
return nil
}
if c.status == CLOSED {
c.mu.Unlock()
reconnectWaitCB()
return ErrClientClosed
}
c.status = CONNECTING
c.reconnect = true
c.mu.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.protocolType, wsConfig)
if err != nil {
go c.handleDisconnect(&disconnect{Reason: "connect error", Reconnect: true})
reconnectWaitCB()
return err
}
c.mu.Lock()
if c.status == CONNECTED || c.status == DISCONNECTED || c.status == CLOSED {
_ = t.Close()
c.mu.Unlock()
reconnectWaitCB()
return nil
}
closeCh := make(chan struct{})
c.receive = make(chan []byte, 64)
c.transport = t
go c.reader(t, closeCh)
err = c.sendConnect(isReconnect, func(res *protocol.ConnectResult, err error) {
defer reconnectWaitCB()
c.mu.Lock()
if c.status != CONNECTING {
c.mu.Unlock()
return
}
c.mu.Unlock()
if err != nil {
if isTokenExpiredError(err) {
// Try to refresh token before next connection attempt.
_ = c.refreshToken()
c.mu.Lock()
if c.status != CONNECTING {
c.mu.Unlock()
return
}
c.mu.Unlock()
}
go c.handleDisconnect(&disconnect{Reason: "connect error", Reconnect: true})
return
}
c.mu.Lock()
if c.status != CONNECTING {
c.mu.Unlock()
return
}
c.id = res.Client
prevStatus := c.status
c.status = CONNECTED
if res.Expires {
go func(interval uint32, closeCh chan struct{}) {
select {
case <-closeCh:
return
case <-time.After(time.Duration(interval) * time.Second):
c.sendRefresh(closeCh)
}
}(res.Ttl, closeCh)
}
c.resolveConnectFutures(nil)
c.mu.Unlock()
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,
}
c.runHandler(func() {
handler.OnConnect(c, ev)
})
}
var subscribeHandler ServerSubscribeHandler
if c.events != nil && c.events.onServerSubscribe != nil {
subscribeHandler = c.events.onServerSubscribe
}
var publishHandler ServerPublishHandler
if c.events != nil && c.events.onServerPublish != nil {
publishHandler = c.events.onServerPublish
}
for channel, subRes := range res.Subs {
c.mu.Lock()
sub, ok := c.serverSubs[channel]
if ok {
sub.Epoch = subRes.Epoch
sub.Recoverable = subRes.Recoverable
} else {
sub = &serverSub{
Epoch: subRes.Epoch,
Offset: subRes.Offset,
Recoverable: subRes.Recoverable,
}
}
if len(subRes.Publications) == 0 {
sub.Offset = subRes.Offset
}
c.serverSubs[channel] = sub
c.mu.Unlock()
if subscribeHandler != nil {
c.runHandler(func() {
subscribeHandler.OnServerSubscribe(c, ServerSubscribeEvent{
Channel: channel,
Resubscribed: isReconnect, // TODO: check request map.
Recovered: subRes.Recovered,
})
})
}
if publishHandler != nil {
c.runHandler(func() {
for _, pub := range subRes.Publications {
publishHandler.OnServerPublish(c, ServerPublishEvent{Channel: channel, Publication: pubFromProto(pub)})
c.mu.Lock()
if sub, ok := c.serverSubs[channel]; ok {
sub.Offset = pub.Offset
}
c.serverSubs[channel] = sub
c.mu.Unlock()
}
})
}
}
c.mu.Lock()
defer c.mu.Unlock()
if c.status != CONNECTED {
return
}
err = c.resubscribe(c.id)
if err != nil {
// we need just to close the connection and outgoing requests here
// but preserve all subscriptions.
go c.handleDisconnect(&disconnect{Reason: "subscribe error", Reconnect: true})
return
}
// Successfully connected – can reset reconnect attempts.
c.reconnectAttempts = 0
go c.periodicPing(closeCh)
})
c.mu.Unlock()
if err != nil {
reconnectWaitCB()
go c.handleDisconnect(&disconnect{Reason: "connect error", Reconnect: true})
}
return err
}
func (c *Client) resubscribe(clientID string) error {
for _, sub := range c.subs {
err := sub.resubscribe(true, clientID, SubscribeOptions{})
if err != nil {
return err
}
}
return nil
}
func isTokenExpiredError(err error) bool {
if e, ok := err.(*Error); ok && e.Code == 109 {
return true
}
return false
}
func (c *Client) disconnect(reconnect bool) error {
c.mu.Lock()
c.reconnect = reconnect
c.mu.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.mu.Lock()
c.token = token
c.mu.Unlock()
return nil
}
func (c *Client) sendRefresh(closeCh chan struct{}) {
err := c.refreshToken()
if err != nil {
return
}
c.mu.RLock()
cmd := &protocol.Command{
Id: c.nextMsgID(),
Method: protocol.Command_REFRESH,
}
params := &protocol.RefreshRequest{
Token: c.token,
}
paramsData, err := c.paramsEncoder.Encode(params)
if err != nil {
c.mu.RUnlock()
return
}
cmd.Params = paramsData
c.mu.RUnlock()
_ = c.sendAsync(cmd, func(r *protocol.Reply, err error) {
if err != nil {
return
}
if r.Error != nil {
return
}
var res protocol.RefreshResult
err = c.resultDecoder.Decode(r.Result, &res)
if err != nil {
return
}
if res.Expires {
go func(interval uint32) {
select {
case <-closeCh:
return