-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
1560 lines (1310 loc) · 29.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 zk
import (
"encoding/binary"
"errors"
"io"
"log"
"net"
"slices"
"sync"
"sync/atomic"
"time"
)
// NewClient ...
func NewClient(servers []string, sessionTimeout time.Duration, options ...Option) (*Client, error) {
c, err := newClientInternal(servers, sessionTimeout, options...)
if err != nil {
return nil, err
}
c.wg.Add(3)
go func() {
defer c.wg.Done()
c.connectAndRunTCPHandlers()
}()
go func() {
defer c.wg.Done()
c.runHandler()
}()
go func() {
defer c.wg.Done()
c.runPingLoop()
}()
return c, nil
}
// Client ...
type Client struct {
logger Logger
dialFunc func(addr string, timeout time.Duration) (NetworkConn, error)
dialRetryDuration time.Duration
writeCodec codecBuffer // not need to lock
readCodec codecBuffer // not need to lock
authReadCodec codecBuffer // not need to lock
selector ServerSelector
sessEstablishedCallback func(c *Client)
sessExpiredCallback func(c *Client)
reconnectingCallback func(c *Client)
// =================================
// doesn't need to protect by mutex
// =================================
lastZxid int64
passwd []byte
sessionTimeoutMs int32
sessionID int64
recvTimeout atomic.Int64
pingInterval time.Duration
// =================================
// =================================
// mutex protect following fields
// =================================
mut sync.Mutex
nextXidValue uint32
state State
sendQueue []clientRequest
sendCond *sync.Cond
sendShutdown bool
recvMap map[int32]clientRequest
handleQueue []handleEvent
handleCond *sync.Cond
handleShutdown bool
conn NetworkConn
creds []authCreds
watchers map[watchPathType][]func(ev Event)
// =================================
wg sync.WaitGroup
pingSignalChan chan struct{}
pingCloseChan chan struct{} // for closing ping loop
}
func (c *Client) getRecvTimeout() time.Duration {
return time.Duration(c.recvTimeout.Load())
}
// Option ...
type Option func(c *Client)
// WithSessionEstablishedCallback ...
func WithSessionEstablishedCallback(callback func(c *Client)) Option {
return func(c *Client) {
c.sessEstablishedCallback = callback
}
}
// WithSessionExpiredCallback ...
func WithSessionExpiredCallback(callback func(c *Client)) Option {
return func(c *Client) {
c.sessExpiredCallback = callback
}
}
// WithReconnectingCallback is the callback when a new connection is re-established after disconnect
// and session is not expired yet
func WithReconnectingCallback(callback func(c *Client)) Option {
return func(c *Client) {
c.reconnectingCallback = callback
}
}
// WithDialRetryDuration ...
func WithDialRetryDuration(d time.Duration) Option {
return func(c *Client) {
c.dialRetryDuration = d
}
}
// WithServerSelector ...
func WithServerSelector(selector ServerSelector) Option {
return func(c *Client) {
c.selector = selector
}
}
// WithDialTimeoutFunc ...
func WithDialTimeoutFunc(
dialFunc func(addr string, timeout time.Duration) (NetworkConn, error),
) Option {
return func(c *Client) {
c.dialFunc = dialFunc
}
}
// WithLogger ...
func WithLogger(l Logger) Option {
return func(c *Client) {
c.logger = l
}
}
type clientRequest struct {
xid int32
opcode int32
request any
response any
watch clientWatchRequest
callback func(res any, zxid int64, err error)
}
type handleEvent struct {
zxid int64
err error
req clientRequest
}
type clientWatchRequest struct {
pathType watchPathType
callback func(ev Event)
}
// NetworkConn for connections when connecting to zookeeper.
type NetworkConn interface {
io.Reader
io.Writer
io.Closer
// SetReadDeadline sets the deadline for future Read calls
// and any currently-blocked Read call.
// A zero value for t means Read will not time out.
SetReadDeadline(d time.Duration) error
// SetWriteDeadline sets the deadline for future Write calls
// and any currently-blocked Write call.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
// A zero value for t means Write will not time out.
SetWriteDeadline(d time.Duration) error
}
func newClientInternal(servers []string, sessionTimeout time.Duration, options ...Option) (*Client, error) {
if len(servers) == 0 {
return nil, errors.New("zk: server list must not be empty")
}
if sessionTimeout < 1*time.Second {
return nil, errors.New("zk: session timeout must not be too small")
}
c := &Client{
logger: &defaultLoggerImpl{},
selector: NewServerListSelector(time.Now().UnixNano()),
dialFunc: func(addr string, timeout time.Duration) (NetworkConn, error) {
netConn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return nil, err
}
return NewTCPConn(netConn), nil
},
dialRetryDuration: 2 * connectTimeout,
state: StateDisconnected,
passwd: emptyPassword,
recvMap: map[int32]clientRequest{},
watchers: map[watchPathType][]func(ev Event){},
pingSignalChan: make(chan struct{}, 10),
pingCloseChan: make(chan struct{}),
}
for _, option := range options {
option(c)
}
c.selector.Init(servers)
c.sendCond = sync.NewCond(&c.mut)
c.handleCond = sync.NewCond(&c.mut)
c.setTimeouts(int32(sessionTimeout / time.Millisecond))
return c, nil
}
func (c *Client) getFromSendQueue() ([]clientRequest, bool) {
c.mut.Lock()
defer c.mut.Unlock()
for {
if c.state != StateHasSession {
return nil, false
}
if len(c.sendQueue) > 0 {
requests := c.sendQueue
for _, req := range requests {
if req.xid == pingRequestXid {
continue
}
c.recvMap[req.xid] = req
}
c.sendQueue = nil
return requests, true
}
if c.sendShutdown {
return nil, false
}
c.sendCond.Wait()
}
}
func (c *Client) disconnectAndClose() (closed bool) {
conn := c.updateStateDisconnectedAndFlushRequests()
if conn != nil {
_ = conn.Close()
return true
}
return false
}
func (c *Client) tryToConnect() (NetworkConn, bool) {
for {
output := c.doConnect()
if output.closed {
c.disconnectAndClose()
c.notifyHandleEventShutdown()
return nil, false
}
if !output.needRetry {
return output.conn, true
}
if output.withSleep {
time.Sleep(c.dialRetryDuration)
}
}
}
const connectTimeout = 1 * time.Second
type connectOutput struct {
conn NetworkConn
closed bool
needRetry bool
withSleep bool
}
func (c *Client) notifyHandleEventShutdown() {
c.mut.Lock()
defer c.mut.Unlock()
c.handleShutdown = true
c.handleCond.Signal()
}
func (c *Client) doConnect() connectOutput {
c.mut.Lock()
if c.sendShutdown {
c.mut.Unlock()
return connectOutput{
closed: true,
}
}
c.state = StateConnecting
c.mut.Unlock()
nextOutput := c.selector.Next()
serverAddr := nextOutput.Server
c.logger.Infof("Connecting to address: '%s'", serverAddr)
conn, err := c.dialFunc(serverAddr, connectTimeout)
if err != nil {
c.mut.Lock()
c.state = StateDisconnected
c.mut.Unlock()
c.logger.Warnf("Failed to connect to server: '%s', error: %v", serverAddr, err)
return connectOutput{
needRetry: true,
withSleep: nextOutput.RetryStart,
}
}
c.logger.Infof("Connected to server: '%s'", serverAddr)
c.mut.Lock()
c.state = StateConnected
c.mut.Unlock()
err = c.authenticate(conn)
if err != nil {
c.mut.Lock()
c.state = StateDisconnected
c.mut.Unlock()
_ = conn.Close()
c.logger.Warnf("Failed to authenticate to server: '%s', error: %v", serverAddr, err)
if errors.Is(err, ErrSessionExpired) {
c.selector.NotifyConnected()
}
return connectOutput{
needRetry: true,
}
}
c.selector.NotifyConnected()
c.mut.Lock()
defer c.mut.Unlock()
return connectOutput{
conn: conn,
closed: c.sendShutdown,
}
}
func (c *Client) connectAndRunTCPHandlers() {
for {
conn, ok := c.tryToConnect()
if !ok {
return
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
c.runSender(conn)
}()
go func() {
defer wg.Done()
c.runReceiver(conn)
}()
wg.Wait()
// Wait for handle queue is empty (mostly)
ch := make(chan struct{})
c.appendHandleQueueError(opWatcherEvent, nil, func(res any, zxid int64, err error) {
close(ch)
})
<-ch
}
}
func (c *Client) runSender(conn NetworkConn) {
for {
requests, ok := c.getFromSendQueue()
if !ok {
return
}
select {
case c.pingSignalChan <- struct{}{}:
default:
}
for _, req := range requests {
output := c.sendData(conn, req)
if output.broken {
c.closeTCPConn(output)
return
}
}
}
}
func (c *Client) connectionRunnerStopped(output connIOOutput) bool {
if output.closed {
c.disconnectAndClose()
return true
}
if output.broken {
closed := c.disconnectAndClose()
if closed {
c.logger.Warnf("Close connection with error: %v", output.err)
}
return true
}
return false
}
func (c *Client) runReceiver(conn NetworkConn) {
for {
output := c.readSingleData(conn)
if c.connectionRunnerStopped(output) {
return
}
}
}
func (c *Client) getHandleEvents() ([]handleEvent, bool) {
c.mut.Lock()
defer c.mut.Unlock()
for {
if len(c.handleQueue) > 0 {
events := c.handleQueue
c.handleQueue = nil
return events, true
}
if c.handleShutdown {
return nil, false
}
c.handleCond.Wait()
}
}
func (c *Client) runHandler() {
for {
events, ok := c.getHandleEvents()
if !ok {
return
}
for _, e := range events {
c.handleEventCallback(e)
}
}
}
func (c *Client) getPingDuration() time.Duration {
c.mut.Lock()
duration := c.pingInterval
c.mut.Unlock()
return duration
}
func (c *Client) runPingLoop() {
d := c.getPingDuration()
timer := time.NewTimer(d)
for {
select {
case <-timer.C:
timer.Reset(c.getPingDuration())
c.sendPingRequest()
case <-c.pingSignalChan:
if !timer.Stop() {
<-timer.C
}
timer.Reset(c.getPingDuration())
case <-c.pingCloseChan:
return
}
}
}
func (c *Client) sendPingRequest() {
c.enqueueRequest(
opPing, &pingRequest{}, &pingResponse{},
nil,
)
}
func (c *Client) handleEventCallback(ev handleEvent) {
if ev.req.callback != nil {
ev.req.callback(ev.req.response, ev.zxid, ev.err)
}
}
func (c *Client) setTimeouts(sessionTimeoutMs int32) {
c.sessionTimeoutMs = sessionTimeoutMs
sessionTimeout := time.Duration(sessionTimeoutMs) * time.Millisecond
c.recvTimeout.Store(int64(sessionTimeout * 2 / 3))
c.pingInterval = c.getRecvTimeout() / 2
}
func (c *Client) nextXid() int32 {
c.nextXidValue++
return int32(c.nextXidValue & 0x7fffffff)
}
func (c *Client) authenticate(conn NetworkConn) error {
req := &connectRequest{
ProtocolVersion: protocolVersion,
LastZxidSeen: c.lastZxid,
TimeOut: c.sessionTimeoutMs,
SessionID: c.sessionID,
Passwd: c.passwd,
}
authTimeout := c.getRecvTimeout() * 10
// Encode and send connect request
_ = conn.SetWriteDeadline(authTimeout)
_, err := encodeObject[connectRequest](req, &c.writeCodec, conn)
_ = conn.SetWriteDeadline(0)
if err != nil {
return err
}
// Receive and decode a connect response.
r := connectResponse{}
_ = conn.SetReadDeadline(authTimeout)
err = decodeObject[connectResponse](&r, &c.authReadCodec, conn)
_ = conn.SetReadDeadline(0)
if err != nil {
return err
}
if r.SessionID == 0 {
c.mut.Lock()
c.logger.Warnf("Session expired")
c.sessionID = 0
c.passwd = emptyPassword
c.lastZxid = 0
c.state = StateExpired
if c.sessExpiredCallback != nil {
c.appendHandleQueueGlobalEvent(c.sessExpiredCallback)
}
c.watchers = map[watchPathType][]func(ev Event){}
c.mut.Unlock()
return ErrSessionExpired
}
c.mut.Lock()
prevIsZero := c.sessionID == 0
c.sessionID = r.SessionID
c.setTimeouts(r.TimeOut)
c.passwd = r.Passwd
c.state = StateHasSession
c.conn = conn
c.handleGlobalCallbacks(prevIsZero)
c.reapplyAuthCreds()
c.reapplyAllWatches()
c.mut.Unlock()
return nil
}
func (c *Client) reapplyAuthCreds() {
for _, cred := range c.creds {
c.enqueueAlreadyLocked(
opSetAuth,
&setAuthRequest{
Type: 0,
Scheme: cred.scheme,
Auth: cred.auth,
},
&setAuthResponse{},
func(resp any, zxid int64, err error) {
},
clientWatchRequest{},
false,
)
}
}
func (c *Client) appendHandleQueueGlobalEvent(callback func(c *Client)) {
req := clientRequest{
opcode: opWatcherEvent,
response: nil,
callback: func(res any, zxid int64, err error) {
callback(c)
},
}
c.appendHandleQueue(req, nil)
}
func (c *Client) handleGlobalCallbacks(prevIsZero bool) {
if c.sessEstablishedCallback != nil && prevIsZero {
c.logger.Infof("Session established")
c.appendHandleQueueGlobalEvent(c.sessEstablishedCallback)
}
if c.reconnectingCallback != nil && !prevIsZero {
c.logger.Warnf("Connection is reconnected")
c.appendHandleQueueGlobalEvent(c.reconnectingCallback)
}
}
func (c *Client) reapplyAllWatches() {
if len(c.watchers) == 0 {
return
}
keys := make([]watchPathType, 0, len(c.watchers))
for wpt := range c.watchers {
keys = append(keys, wpt)
}
slices.SortFunc(keys, func(a, b watchPathType) int {
if a.path < b.path {
return -1
}
if a.path > b.path {
return 1
}
return int(a.wType - b.wType)
})
const batchSize = 64
for i := 0; i < len(keys); i += batchSize {
end := i + batchSize
if end > len(keys) {
end = len(keys)
}
subKeys := keys[i:end]
req := &setWatchesRequest{
RelativeZxid: c.lastZxid,
}
for _, wpt := range subKeys {
switch wpt.wType {
case watchTypeExist:
req.ExistWatches = append(req.ExistWatches, wpt.path)
case watchTypeChild:
req.ChildWatches = append(req.ChildWatches, wpt.path)
case watchTypeData:
req.DataWatches = append(req.DataWatches, wpt.path)
default:
}
}
c.enqueueAlreadyLocked(
opSetWatches, req, &setWatchesResponse{},
func(resp any, zxid int64, err error) {},
clientWatchRequest{},
false,
)
}
}
func (c *Client) enqueueRequest(
opCode int32, request any, response any,
callback func(resp any, zxid int64, err error),
) {
c.enqueueRequestWithWatcher(
opCode, request,
response, callback, clientWatchRequest{},
)
}
func (c *Client) enqueueRequestWithWatcher(
opCode int32, request any, response any,
callback func(resp any, zxid int64, err error),
watch clientWatchRequest,
) {
c.mut.Lock()
defer c.mut.Unlock()
if c.sendShutdown {
c.logger.Infof("Zookeeper client being accessed after Close()")
return
}
c.enqueueAlreadyLocked(opCode, request, response, callback, watch, true)
}
const watchEventXid int32 = -1
const pingRequestXid int32 = -2
func (c *Client) addToWatcherMap(req clientRequest, err error) {
if err != nil {
if req.opcode != opExists {
return
}
// if cmd = exists and err = ErrNoNode => add watch
if !errors.Is(err, ErrNoNode) {
return
}
}
watch := req.watch
pathType := watch.pathType
if len(pathType.path) > 0 {
c.watchers[pathType] = append(c.watchers[pathType], watch.callback)
}
}
func (c *Client) enqueueAlreadyLocked(
opCode int32, request any, response any,
callback func(resp any, zxid int64, err error),
watch clientWatchRequest, setAuth bool,
) {
xid := pingRequestXid
if opCode != opPing {
xid = c.nextXid()
}
req := clientRequest{
xid: xid,
opcode: opCode,
request: request,
response: response,
watch: watch,
callback: callback,
}
if setAuth && opCode == opSetAuth {
r := request.(*setAuthRequest)
c.creds = append(c.creds, authCreds{
scheme: r.Scheme,
auth: r.Auth,
})
}
if c.state == StateHasSession {
c.sendQueue = append(c.sendQueue, req)
c.sendCond.Signal()
return
}
c.appendHandleQueue(req, ErrConnectionClosed)
}
func (c *Client) appendHandleQueue(req clientRequest, err error) {
c.appendHandleQueueZxid(req, 0, err)
}
func (c *Client) appendHandleQueueZxid(req clientRequest, zxid int64, err error) {
c.handleQueue = append(c.handleQueue, handleEvent{
zxid: zxid,
err: err,
req: req,
})
c.handleCond.Signal()
}
func (c *Client) appendHandleQueueError(
opCode int32, err error,
callback func(res any, zxid int64, err error),
) {
c.mut.Lock()
defer c.mut.Unlock()
c.appendHandleQueue(clientRequest{
opcode: opCode,
callback: callback,
}, err)
}
func (c *Client) updateStateDisconnectedAndFlushRequests() NetworkConn {
c.mut.Lock()
defer c.mut.Unlock()
c.state = StateDisconnected
oldConn := c.conn
c.conn = nil
events := make([]handleEvent, 0, len(c.recvMap)+len(c.sendQueue))
for _, req := range c.recvMap {
events = append(events, handleEvent{
err: ErrConnectionClosed,
req: req,
})
}
c.recvMap = map[int32]clientRequest{}
for _, req := range c.sendQueue {
events = append(events, handleEvent{
err: ErrConnectionClosed,
req: req,
})
}
c.sendQueue = nil
slices.SortFunc(events, func(a, b handleEvent) int {
return int(a.req.xid - b.req.xid)
})
c.handleQueue = append(c.handleQueue, events...)
c.handleCond.Signal()
c.sendCond.Signal() // notify when state is changed
return oldConn
}
func (c *Client) getTCPConn() NetworkConn {
c.mut.Lock()
defer c.mut.Unlock()
oldConn := c.conn
c.conn = nil
return oldConn
}
func (c *Client) closeTCPConn(output connIOOutput) {
conn := c.getTCPConn()
if conn != nil {
_ = conn.Close()
c.logger.Warnf("Close connection with error: %v", output.err)
}
}
type connIOOutput struct {
closed bool
broken bool
err error
}
func connError(err error) connIOOutput {
return connIOOutput{
broken: true,
err: err,
}
}
func connNormal() connIOOutput {
return connIOOutput{}
}
func (c *Client) sendData(conn NetworkConn, req clientRequest) connIOOutput {
header := &requestHeader{Xid: req.xid, Opcode: req.opcode}
buf := c.writeCodec.buf[:]
// encode header
n, err := encodePacket(buf[4:], header)
if err != nil {
return connError(err)
}
// encode request object
n2, err := encodePacket(buf[4+n:], req.request)
if err != nil {
return connError(err)
}
n += n2
// write length to the first 4 bytes
binary.BigEndian.PutUint32(buf[:4], uint32(n))
_ = conn.SetWriteDeadline(c.getRecvTimeout())
_, err = conn.Write(buf[:n+4])
_ = conn.SetWriteDeadline(0)
if err != nil {
return connError(err)
}
return connNormal()
}
func (c *Client) readSingleData(conn NetworkConn) connIOOutput {
buf := c.readCodec.buf
recvTimeout := c.getRecvTimeout()
// read package length
_ = conn.SetReadDeadline(recvTimeout)
_, err := io.ReadFull(conn, buf[:4])
if err != nil {
return connError(err)
}
blen := int(binary.BigEndian.Uint32(buf[:4]))
if len(buf) < blen {
return connError(errors.New("message length too big"))
}
_ = conn.SetReadDeadline(recvTimeout)
_, err = io.ReadFull(conn, buf[:blen])
_ = conn.SetReadDeadline(0)
if err != nil {
return connError(err)
}
res := responseHeader{}
_, err = decodePacket(buf[:16], &res)
if err != nil {
return connError(err)
}
if res.Zxid > 0 {
c.lastZxid = res.Zxid
}
if res.Xid == watchEventXid {
return c.handleWatchEvent(buf[:], blen, res)
}
if res.Xid == pingRequestXid {
// Ping response. Ignore.
return connNormal()
}
if res.Xid < 0 {
c.logger.Warnf("Xid < 0 (%d) but not ping or watcher event", res.Xid)
return connNormal()
}
return c.handleNormalResponse(res, buf[:], blen)
}
func (c *Client) handleNormalResponse(res responseHeader, buf []byte, blen int) connIOOutput {
c.mut.Lock()
defer c.mut.Unlock()
req, ok := c.recvMap[res.Xid]
if ok {
delete(c.recvMap, res.Xid)
}
if !ok {
c.logger.Warnf("Response for unknown request with xid %d", res.Xid)
return connNormal()
}
c.mut.Unlock()
// not need to decode in a mutex lock
var err error
if res.Err != 0 {
err = res.Err.toError()
} else {
const responseHeaderSize = 16
_, err = decodePacket(buf[responseHeaderSize:blen], req.response)
}
c.mut.Lock()