forked from fl00r/go-tarantool-1.6
-
Notifications
You must be signed in to change notification settings - Fork 58
/
connection.go
1584 lines (1427 loc) · 41.3 KB
/
connection.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 with implementation of methods and structures for work with
// Tarantool instance.
package tarantool
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"math"
"net"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/tarantool/go-iproto"
"github.com/vmihailenco/msgpack/v5"
)
const requestsMap = 128
const ignoreStreamId = 0
const (
connDisconnected = 0
connConnected = 1
connShutdown = 2
connClosed = 3
)
const shutdownEventKey = "box.shutdown"
type ConnEventKind int
type ConnLogKind int
var (
errUnknownRequest = errors.New("the passed connected request doesn't belong " +
"to the current connection or connection pool")
)
const (
// Connected signals that connection is established or reestablished.
Connected ConnEventKind = iota + 1
// Disconnected signals that connection is broken.
Disconnected
// ReconnectFailed signals that attempt to reconnect has failed.
ReconnectFailed
// Shutdown signals that shutdown callback is processing.
Shutdown
// Either reconnect attempts exhausted, or explicit Close is called.
Closed
// LogReconnectFailed is logged when reconnect attempt failed.
LogReconnectFailed ConnLogKind = iota + 1
// LogLastReconnectFailed is logged when last reconnect attempt failed,
// connection will be closed after that.
LogLastReconnectFailed
// LogUnexpectedResultId is logged when response with unknown id was received.
// Most probably it is due to request timeout.
LogUnexpectedResultId
// LogWatchEventReadFailed is logged when failed to read a watch event.
LogWatchEventReadFailed
// LogAppendPushFailed is logged when failed to append a push response.
LogAppendPushFailed
)
// ConnEvent is sent throw Notify channel specified in Opts.
type ConnEvent struct {
Conn *Connection
Kind ConnEventKind
When time.Time
}
// A raw watch event.
type connWatchEvent struct {
key string
value interface{}
}
var epoch = time.Now()
// Logger is logger type expected to be passed in options.
type Logger interface {
Report(event ConnLogKind, conn *Connection, v ...interface{})
}
type defaultLogger struct{}
func (d defaultLogger) Report(event ConnLogKind, conn *Connection, v ...interface{}) {
switch event {
case LogReconnectFailed:
reconnects := v[0].(uint)
err := v[1].(error)
log.Printf("tarantool: reconnect (%d/%d) to %s failed: %s",
reconnects, conn.opts.MaxReconnects, conn.Addr(), err)
case LogLastReconnectFailed:
err := v[0].(error)
log.Printf("tarantool: last reconnect to %s failed: %s, giving it up",
conn.Addr(), err)
case LogUnexpectedResultId:
header := v[0].(Header)
log.Printf("tarantool: connection %s got unexpected request ID (%d) in response "+
"(probably cancelled request)",
conn.Addr(), header.RequestId)
case LogWatchEventReadFailed:
err := v[0].(error)
log.Printf("tarantool: unable to parse watch event: %s", err)
case LogAppendPushFailed:
err := v[0].(error)
log.Printf("tarantool: unable to append a push response: %s", err)
default:
args := append([]interface{}{"tarantool: unexpected event ", event, conn}, v...)
log.Print(args...)
}
}
// Connection is a handle with a single connection to a Tarantool instance.
//
// It is created and configured with Connect function, and could not be
// reconfigured later.
//
// Connection could be in three possible states:
//
// - In "Connected" state it sends queries to Tarantool.
//
// - In "Disconnected" state it rejects queries with ClientError{Code:
// ErrConnectionNotReady}
//
// - In "Shutdown" state it rejects queries with ClientError{Code:
// ErrConnectionShutdown}. The state indicates that a graceful shutdown
// in progress. The connection waits for all active requests to
// complete.
//
// - In "Closed" state it rejects queries with ClientError{Code:
// ErrConnectionClosed}. Connection could become "Closed" when
// Connection.Close() method called, or when Tarantool disconnected and
// Reconnect pause is not specified or MaxReconnects is specified and
// MaxReconnect reconnect attempts already performed.
//
// You may perform data manipulation operation by calling its methods:
// Call*, Insert*, Replace*, Update*, Upsert*, Call*, Eval*.
//
// In any method that accepts space you my pass either space number or space
// name (in this case it will be looked up in schema). Same is true for index.
//
// ATTENTION: tuple, key, ops and args arguments for any method should be
// and array or should serialize to msgpack array.
//
// ATTENTION: result argument for *Typed methods should deserialize from
// msgpack array, cause Tarantool always returns result as an array.
// For all space related methods and Call16* (but not Call17*) methods Tarantool
// always returns array of array (array of tuples for space related methods).
// For Eval* and Call* Tarantool always returns array, but does not forces
// array of arrays.
//
// If connected to Tarantool 2.10 or newer, connection supports server graceful
// shutdown. In this case, server will wait until all client requests will be
// finished and client disconnects before going down (server also may go down
// by timeout). Client reconnect will happen if connection options enable
// reconnect. Beware that graceful shutdown event initialization is asynchronous.
//
// More on graceful shutdown:
// https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/
type Connection struct {
addr net.Addr
dialer Dialer
c Conn
mutex sync.Mutex
cond *sync.Cond
// schemaResolver contains a SchemaResolver implementation.
schemaResolver SchemaResolver
// requestId contains the last request ID for requests with nil context.
requestId uint32
// contextRequestId contains the last request ID for requests with context.
contextRequestId uint32
// Greeting contains first message sent by Tarantool.
Greeting *Greeting
shard []connShard
dirtyShard chan uint32
control chan struct{}
rlimit chan struct{}
opts Opts
state uint32
dec *msgpack.Decoder
lenbuf [packetLengthBytes]byte
lastStreamId uint64
serverProtocolInfo ProtocolInfo
// watchMap is a map of key -> chan watchState.
watchMap sync.Map
// shutdownWatcher is the "box.shutdown" event watcher.
shutdownWatcher Watcher
// requestCnt is a counter of active requests.
requestCnt int64
}
var _ = Connector(&Connection{}) // Check compatibility with connector interface.
type futureList struct {
first *Future
last **Future
}
func (list *futureList) findFuture(reqid uint32, fetch bool) *Future {
root := &list.first
for {
fut := *root
if fut == nil {
return nil
}
if fut.requestId == reqid {
if fetch {
*root = fut.next
if fut.next == nil {
list.last = root
} else {
fut.next = nil
}
}
return fut
}
root = &fut.next
}
}
func (list *futureList) addFuture(fut *Future) {
*list.last = fut
list.last = &fut.next
}
func (list *futureList) clear(err error, conn *Connection) {
fut := list.first
list.first = nil
list.last = &list.first
for fut != nil {
fut.SetError(err)
conn.markDone(fut)
fut, fut.next = fut.next, nil
}
}
type connShard struct {
rmut sync.Mutex
requests [requestsMap]futureList
requestsWithCtx [requestsMap]futureList
bufmut sync.Mutex
buf smallWBuf
enc *msgpack.Encoder
}
// RLimitActions is an enumeration type for an action to do when a rate limit
// is reached.
type RLimitAction int
const (
// RLimitDrop immediately aborts the request.
RLimitDrop RLimitAction = iota
// RLimitWait waits during timeout period for some request to be answered.
// If no request answered during timeout period, this request is aborted.
// If no timeout period is set, it will wait forever.
RLimitWait
)
// Opts is a way to configure Connection
type Opts struct {
// Timeout for response to a particular request. The timeout is reset when
// push messages are received. If Timeout is zero, any request can be
// blocked infinitely.
// Also used to setup net.TCPConn.Set(Read|Write)Deadline.
//
// Pay attention, when using contexts with request objects,
// the timeout option for Connection does not affect the lifetime
// of the request. For those purposes use context.WithTimeout() as
// the root context.
Timeout time.Duration
// Timeout between reconnect attempts. If Reconnect is zero, no
// reconnect attempts will be made.
// If specified, then when Tarantool is not reachable or disconnected,
// new connect attempt is performed after pause.
// By default, no reconnection attempts are performed,
// so once disconnected, connection becomes Closed.
Reconnect time.Duration
// Maximum number of reconnect failures; after that we give it up to
// on. If MaxReconnects is zero, the client will try to reconnect
// endlessly.
// After MaxReconnects attempts Connection becomes closed.
MaxReconnects uint
// RateLimit limits number of 'in-fly' request, i.e. already put into
// requests queue, but not yet answered by server or timeouted.
// It is disabled by default.
// See RLimitAction for possible actions when RateLimit.reached.
RateLimit uint
// RLimitAction tells what to do when RateLimit is reached.
// It is required if RateLimit is specified.
RLimitAction RLimitAction
// Concurrency is amount of separate mutexes for request
// queues and buffers inside of connection.
// It is rounded up to nearest power of 2.
// By default it is runtime.GOMAXPROCS(-1) * 4
Concurrency uint32
// SkipSchema disables schema loading. Without disabling schema loading,
// there is no way to create Connection for currently not accessible Tarantool.
SkipSchema bool
// Notify is a channel which receives notifications about Connection status
// changes.
Notify chan<- ConnEvent
// Handle is user specified value, that could be retrivied with
// Handle() method.
Handle interface{}
// Logger is user specified logger used for error messages.
Logger Logger
}
// Connect creates and configures a new Connection.
func Connect(ctx context.Context, dialer Dialer, opts Opts) (conn *Connection, err error) {
conn = &Connection{
dialer: dialer,
requestId: 0,
contextRequestId: 1,
Greeting: &Greeting{},
control: make(chan struct{}),
opts: opts,
dec: msgpack.NewDecoder(&smallBuf{}),
}
maxprocs := uint32(runtime.GOMAXPROCS(-1))
if conn.opts.Concurrency == 0 || conn.opts.Concurrency > maxprocs*128 {
conn.opts.Concurrency = maxprocs * 4
}
if c := conn.opts.Concurrency; c&(c-1) != 0 {
for i := uint(1); i < 32; i *= 2 {
c |= c >> i
}
conn.opts.Concurrency = c + 1
}
conn.dirtyShard = make(chan uint32, conn.opts.Concurrency*2)
conn.shard = make([]connShard, conn.opts.Concurrency)
for i := range conn.shard {
shard := &conn.shard[i]
requestsLists := []*[requestsMap]futureList{&shard.requests, &shard.requestsWithCtx}
for _, requests := range requestsLists {
for j := range requests {
requests[j].last = &requests[j].first
}
}
}
if conn.opts.RateLimit > 0 {
conn.rlimit = make(chan struct{}, conn.opts.RateLimit)
if conn.opts.RLimitAction != RLimitDrop && conn.opts.RLimitAction != RLimitWait {
return nil, errors.New("RLimitAction should be specified to RLimitDone nor RLimitWait")
}
}
if conn.opts.Logger == nil {
conn.opts.Logger = defaultLogger{}
}
conn.cond = sync.NewCond(&conn.mutex)
if err = conn.createConnection(ctx); err != nil {
return nil, err
}
go conn.pinger()
if conn.opts.Timeout > 0 {
go conn.timeouts()
}
// TODO: reload schema after reconnect.
if !conn.opts.SkipSchema {
schema, err := GetSchema(conn)
if err != nil {
conn.mutex.Lock()
defer conn.mutex.Unlock()
conn.closeConnection(err, true)
return nil, err
}
conn.SetSchema(schema)
}
return conn, err
}
// ConnectedNow reports if connection is established at the moment.
func (conn *Connection) ConnectedNow() bool {
return atomic.LoadUint32(&conn.state) == connConnected
}
// ClosedNow reports if connection is closed by user or after reconnect.
func (conn *Connection) ClosedNow() bool {
return atomic.LoadUint32(&conn.state) == connClosed
}
// Close closes Connection.
// After this method called, there is no way to reopen this Connection.
func (conn *Connection) Close() error {
err := ClientError{ErrConnectionClosed, "connection closed by client"}
conn.mutex.Lock()
defer conn.mutex.Unlock()
return conn.closeConnection(err, true)
}
// CloseGraceful closes Connection gracefully. It waits for all requests to
// complete.
// After this method called, there is no way to reopen this Connection.
func (conn *Connection) CloseGraceful() error {
return conn.shutdown(true)
}
// Addr returns a configured address of Tarantool socket.
func (conn *Connection) Addr() net.Addr {
return conn.addr
}
// Handle returns a user-specified handle from Opts.
func (conn *Connection) Handle() interface{} {
return conn.opts.Handle
}
func (conn *Connection) cancelFuture(fut *Future, err error) {
if fut = conn.fetchFuture(fut.requestId); fut != nil {
fut.SetError(err)
conn.markDone(fut)
}
}
func (conn *Connection) dial(ctx context.Context) error {
opts := conn.opts
var c Conn
c, err := conn.dialer.Dial(ctx, DialOpts{
IoTimeout: opts.Timeout,
})
if err != nil {
return err
}
conn.addr = c.Addr()
connGreeting := c.Greeting()
conn.Greeting.Version = connGreeting.Version
conn.Greeting.Salt = connGreeting.Salt
conn.serverProtocolInfo = c.ProtocolInfo()
spaceAndIndexNamesSupported :=
isFeatureInSlice(iproto.IPROTO_FEATURE_SPACE_AND_INDEX_NAMES,
conn.serverProtocolInfo.Features)
conn.schemaResolver = &noSchemaResolver{
SpaceAndIndexNamesSupported: spaceAndIndexNamesSupported,
}
// Watchers.
conn.watchMap.Range(func(key, value interface{}) bool {
st := value.(chan watchState)
state := <-st
if state.unready != nil {
st <- state
return true
}
req := newWatchRequest(key.(string))
if err = writeRequest(c, req); err != nil {
st <- state
return false
}
state.ack = true
st <- state
return true
})
if err != nil {
c.Close()
return fmt.Errorf("unable to register watch: %w", err)
}
// Only if connected and fully initialized.
conn.lockShards()
conn.c = c
atomic.StoreUint32(&conn.state, connConnected)
conn.cond.Broadcast()
conn.unlockShards()
go conn.writer(c, c)
go conn.reader(c, c)
// Subscribe shutdown event to process graceful shutdown.
if conn.shutdownWatcher == nil &&
isFeatureInSlice(iproto.IPROTO_FEATURE_WATCHERS,
conn.serverProtocolInfo.Features) {
watcher, werr := conn.newWatcherImpl(shutdownEventKey, shutdownEventCallback)
if werr != nil {
return werr
}
conn.shutdownWatcher = watcher
}
return nil
}
func pack(h *smallWBuf, enc *msgpack.Encoder, reqid uint32,
req Request, streamId uint64, res SchemaResolver) (err error) {
const uint32Code = 0xce
const uint64Code = 0xcf
const streamBytesLenUint64 = 10
const streamBytesLenUint32 = 6
hl := h.Len()
var streamBytesLen = 0
var streamBytes [streamBytesLenUint64]byte
hMapLen := byte(0x82) // 2 element map.
if streamId != ignoreStreamId {
hMapLen = byte(0x83) // 3 element map.
streamBytes[0] = byte(iproto.IPROTO_STREAM_ID)
if streamId > math.MaxUint32 {
streamBytesLen = streamBytesLenUint64
streamBytes[1] = uint64Code
binary.BigEndian.PutUint64(streamBytes[2:], streamId)
} else {
streamBytesLen = streamBytesLenUint32
streamBytes[1] = uint32Code
binary.BigEndian.PutUint32(streamBytes[2:], uint32(streamId))
}
}
hBytes := append([]byte{
uint32Code, 0, 0, 0, 0, // Length.
hMapLen,
byte(iproto.IPROTO_REQUEST_TYPE), byte(req.Type()), // Request type.
byte(iproto.IPROTO_SYNC), uint32Code,
byte(reqid >> 24), byte(reqid >> 16),
byte(reqid >> 8), byte(reqid),
}, streamBytes[:streamBytesLen]...)
h.Write(hBytes)
if err = req.Body(res, enc); err != nil {
return
}
l := uint32(h.Len() - 5 - hl)
h.b[hl+1] = byte(l >> 24)
h.b[hl+2] = byte(l >> 16)
h.b[hl+3] = byte(l >> 8)
h.b[hl+4] = byte(l)
return
}
func (conn *Connection) createConnection(ctx context.Context) error {
var err error
if conn.c == nil && conn.state == connDisconnected {
if err = conn.dial(ctx); err == nil {
conn.notify(Connected)
return nil
}
}
if conn.state == connClosed {
err = ClientError{ErrConnectionClosed, "using closed connection"}
}
return err
}
func (conn *Connection) closeConnection(neterr error, forever bool) (err error) {
conn.lockShards()
defer conn.unlockShards()
if forever {
if conn.state != connClosed {
close(conn.control)
atomic.StoreUint32(&conn.state, connClosed)
conn.cond.Broadcast()
// Free the resources.
if conn.shutdownWatcher != nil {
go conn.shutdownWatcher.Unregister()
conn.shutdownWatcher = nil
}
conn.notify(Closed)
}
} else {
atomic.StoreUint32(&conn.state, connDisconnected)
conn.cond.Broadcast()
conn.notify(Disconnected)
}
if conn.c != nil {
err = conn.c.Close()
conn.c = nil
}
for i := range conn.shard {
conn.shard[i].buf.Reset()
requestsLists := []*[requestsMap]futureList{
&conn.shard[i].requests,
&conn.shard[i].requestsWithCtx,
}
for _, requests := range requestsLists {
for pos := range requests {
requests[pos].clear(neterr, conn)
}
}
}
return
}
func (conn *Connection) getDialTimeout() time.Duration {
dialTimeout := conn.opts.Reconnect / 2
if dialTimeout == 0 {
dialTimeout = 500 * time.Millisecond
} else if dialTimeout > 5*time.Second {
dialTimeout = 5 * time.Second
}
return dialTimeout
}
func (conn *Connection) runReconnects() error {
dialTimeout := conn.getDialTimeout()
var reconnects uint
var err error
for conn.opts.MaxReconnects == 0 || reconnects <= conn.opts.MaxReconnects {
now := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
err = conn.createConnection(ctx)
cancel()
if err != nil {
if clientErr, ok := err.(ClientError); ok &&
clientErr.Code == ErrConnectionClosed {
return err
}
} else {
return nil
}
conn.opts.Logger.Report(LogReconnectFailed, conn, reconnects, err)
conn.notify(ReconnectFailed)
reconnects++
conn.mutex.Unlock()
time.Sleep(time.Until(now.Add(conn.opts.Reconnect)))
conn.mutex.Lock()
}
conn.opts.Logger.Report(LogLastReconnectFailed, conn, err)
// mark connection as closed to avoid reopening by another goroutine
return ClientError{ErrConnectionClosed, "last reconnect failed"}
}
func (conn *Connection) reconnectImpl(neterr error, c Conn) {
if conn.opts.Reconnect > 0 {
if c == conn.c {
conn.closeConnection(neterr, false)
if err := conn.runReconnects(); err != nil {
conn.closeConnection(err, true)
}
}
} else {
conn.closeConnection(neterr, true)
}
}
func (conn *Connection) reconnect(neterr error, c Conn) {
conn.mutex.Lock()
defer conn.mutex.Unlock()
conn.reconnectImpl(neterr, c)
conn.cond.Broadcast()
}
func (conn *Connection) lockShards() {
for i := range conn.shard {
conn.shard[i].rmut.Lock()
conn.shard[i].bufmut.Lock()
}
}
func (conn *Connection) unlockShards() {
for i := range conn.shard {
conn.shard[i].rmut.Unlock()
conn.shard[i].bufmut.Unlock()
}
}
func (conn *Connection) pinger() {
to := conn.opts.Timeout
if to == 0 {
to = 3 * time.Second
}
t := time.NewTicker(to / 3)
defer t.Stop()
for {
select {
case <-conn.control:
return
case <-t.C:
}
conn.Ping()
}
}
func (conn *Connection) notify(kind ConnEventKind) {
if conn.opts.Notify != nil {
select {
case conn.opts.Notify <- ConnEvent{Kind: kind, Conn: conn, When: time.Now()}:
default:
}
}
}
func (conn *Connection) writer(w writeFlusher, c Conn) {
var shardn uint32
var packet smallWBuf
for atomic.LoadUint32(&conn.state) != connClosed {
select {
case shardn = <-conn.dirtyShard:
default:
runtime.Gosched()
if len(conn.dirtyShard) == 0 {
if err := w.Flush(); err != nil {
err = ClientError{
ErrIoError,
fmt.Sprintf("failed to flush data to the connection: %s", err),
}
conn.reconnect(err, c)
return
}
}
select {
case shardn = <-conn.dirtyShard:
case <-conn.control:
return
}
}
shard := &conn.shard[shardn]
shard.bufmut.Lock()
if conn.c != c {
conn.dirtyShard <- shardn
shard.bufmut.Unlock()
return
}
packet, shard.buf = shard.buf, packet
shard.bufmut.Unlock()
if packet.Len() == 0 {
continue
}
if _, err := w.Write(packet.b); err != nil {
err = ClientError{
ErrIoError,
fmt.Sprintf("failed to write data to the connection: %s", err),
}
conn.reconnect(err, c)
return
}
packet.Reset()
}
}
func readWatchEvent(reader io.Reader) (connWatchEvent, error) {
keyExist := false
event := connWatchEvent{}
d := msgpack.NewDecoder(reader)
l, err := d.DecodeMapLen()
if err != nil {
return event, err
}
for ; l > 0; l-- {
cd, err := d.DecodeInt()
if err != nil {
return event, err
}
switch iproto.Key(cd) {
case iproto.IPROTO_EVENT_KEY:
if event.key, err = d.DecodeString(); err != nil {
return event, err
}
keyExist = true
case iproto.IPROTO_EVENT_DATA:
if event.value, err = d.DecodeInterface(); err != nil {
return event, err
}
default:
if err = d.Skip(); err != nil {
return event, err
}
}
}
if !keyExist {
return event, errors.New("watch event does not have a key")
}
return event, nil
}
func (conn *Connection) reader(r io.Reader, c Conn) {
events := make(chan connWatchEvent, 1024)
defer close(events)
go conn.eventer(events)
for atomic.LoadUint32(&conn.state) != connClosed {
respBytes, err := read(r, conn.lenbuf[:])
if err != nil {
err = ClientError{
ErrIoError,
fmt.Sprintf("failed to read data from the connection: %s", err),
}
conn.reconnect(err, c)
return
}
buf := smallBuf{b: respBytes}
header, code, err := decodeHeader(conn.dec, &buf)
if err != nil {
err = ClientError{
ErrProtocolError,
fmt.Sprintf("failed to decode IPROTO header: %s", err),
}
conn.reconnect(err, c)
return
}
var fut *Future = nil
if code == iproto.IPROTO_EVENT {
if event, err := readWatchEvent(&buf); err == nil {
events <- event
} else {
err = ClientError{
ErrProtocolError,
fmt.Sprintf("failed to decode IPROTO_EVENT: %s", err),
}
conn.opts.Logger.Report(LogWatchEventReadFailed, conn, err)
}
continue
} else if code == iproto.IPROTO_CHUNK {
if fut = conn.peekFuture(header.RequestId); fut != nil {
if err := fut.AppendPush(header, &buf); err != nil {
err = ClientError{
ErrProtocolError,
fmt.Sprintf("failed to append push response: %s", err),
}
conn.opts.Logger.Report(LogAppendPushFailed, conn, err)
}
}
} else {
if fut = conn.fetchFuture(header.RequestId); fut != nil {
if err := fut.SetResponse(header, &buf); err != nil {
fut.SetError(fmt.Errorf("failed to set response: %w", err))
}
conn.markDone(fut)
}
}
if fut == nil {
conn.opts.Logger.Report(LogUnexpectedResultId, conn, header)
}
}
}
// eventer goroutine gets watch events and updates values for watchers.
func (conn *Connection) eventer(events <-chan connWatchEvent) {
for event := range events {
if value, ok := conn.watchMap.Load(event.key); ok {
st := value.(chan watchState)
state := <-st
state.value = event.value
if state.version == math.MaxUint {
state.version = initWatchEventVersion + 1
} else {
state.version += 1
}
state.ack = false
if state.changed != nil {
close(state.changed)
state.changed = nil
}
st <- state
}
// It is possible to get IPROTO_EVENT after we already send
// IPROTO_UNWATCH due to processing on a Tarantool side or slow
// read from the network, so it looks like an expected behavior.
}
}
func (conn *Connection) newFuture(req Request) (fut *Future) {
ctx := req.Ctx()
fut = NewFuture(req)
if conn.rlimit != nil && conn.opts.RLimitAction == RLimitDrop {
select {
case conn.rlimit <- struct{}{}:
default:
fut.err = ClientError{
ErrRateLimited,
"Request is rate limited on client",
}
fut.ready = nil
fut.done = nil
return
}
}
fut.requestId = conn.nextRequestId(ctx != nil)
shardn := fut.requestId & (conn.opts.Concurrency - 1)
shard := &conn.shard[shardn]
shard.rmut.Lock()
switch atomic.LoadUint32(&conn.state) {
case connClosed:
fut.err = ClientError{
ErrConnectionClosed,
"using closed connection",
}
fut.ready = nil
fut.done = nil
shard.rmut.Unlock()
return
case connDisconnected:
fut.err = ClientError{
ErrConnectionNotReady,
"client connection is not ready",
}
fut.ready = nil
fut.done = nil
shard.rmut.Unlock()
return
case connShutdown:
fut.err = ClientError{
ErrConnectionShutdown,
"server shutdown in progress",
}
fut.ready = nil
fut.done = nil
shard.rmut.Unlock()
return
}
pos := (fut.requestId / conn.opts.Concurrency) & (requestsMap - 1)
if ctx != nil {
select {
case <-ctx.Done():
fut.SetError(fmt.Errorf("context is done (request ID %d)", fut.requestId))
shard.rmut.Unlock()
return
default:
}
shard.requestsWithCtx[pos].addFuture(fut)
} else {
shard.requests[pos].addFuture(fut)
if conn.opts.Timeout > 0 {
fut.timeout = time.Since(epoch) + conn.opts.Timeout
}
}
shard.rmut.Unlock()
if conn.rlimit != nil && conn.opts.RLimitAction == RLimitWait {
select {
case conn.rlimit <- struct{}{}:
default:
runtime.Gosched()
select {
case conn.rlimit <- struct{}{}:
case <-fut.done:
if fut.err == nil {
panic("fut.done is closed, but err is nil")
}
}
}
}
return
}
// This method removes a future from the internal queue if the context
// is "done" before the response is come.
func (conn *Connection) contextWatchdog(fut *Future, ctx context.Context) {
select {
case <-fut.done:
case <-ctx.Done():
}
select {
case <-fut.done:
return
default:
conn.cancelFuture(fut, fmt.Errorf("context is done (request ID %d)", fut.requestId))
}
}
func (conn *Connection) incrementRequestCnt() {
atomic.AddInt64(&conn.requestCnt, int64(1))
}
func (conn *Connection) decrementRequestCnt() {
if atomic.AddInt64(&conn.requestCnt, int64(-1)) == 0 {
conn.cond.Broadcast()
}
}
func (conn *Connection) send(req Request, streamId uint64) *Future {