Skip to content

Commit 1ecc707

Browse files
committed
api: context support
This patch adds the support of using context in API. The API is based on using request objects. Added tests that cover almost all cases of using the context in a query. Added benchamrk tests are equivalent to other, that use the same query but without any context. Closes #48
1 parent e1bb59c commit 1ecc707

File tree

7 files changed

+548
-58
lines changed

7 files changed

+548
-58
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Versioning](http://semver.org/spec/v2.0.0.html) except to the first release.
1616
- Support decimal type in msgpack (#96)
1717
- Support datetime type in msgpack (#118)
1818
- Prepared SQL statements (#117)
19+
- Context support for request objects (#48)
1920

2021
### Changed
2122

connection.go

+146-56
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package tarantool
55
import (
66
"bufio"
77
"bytes"
8+
"context"
89
"errors"
910
"fmt"
1011
"io"
@@ -125,8 +126,11 @@ type Connection struct {
125126
c net.Conn
126127
mutex sync.Mutex
127128
// Schema contains schema loaded on connection.
128-
Schema *Schema
129+
Schema *Schema
130+
// requestId contains the last request ID for requests with nil context.
129131
requestId uint32
132+
// contextRequestId contains the last request ID for requests with context.
133+
contextRequestId uint32
130134
// Greeting contains first message sent by Tarantool.
131135
Greeting *Greeting
132136

@@ -143,16 +147,57 @@ type Connection struct {
143147

144148
var _ = Connector(&Connection{}) // Check compatibility with connector interface.
145149

150+
type futureList struct {
151+
first *Future
152+
last **Future
153+
}
154+
155+
func (list *futureList) findFuture(reqid uint32, fetch bool) *Future {
156+
root := &list.first
157+
for {
158+
fut := *root
159+
if fut == nil {
160+
return nil
161+
}
162+
if fut.requestId == reqid {
163+
if fetch {
164+
*root = fut.next
165+
if fut.next == nil {
166+
list.last = root
167+
} else {
168+
fut.next = nil
169+
}
170+
}
171+
return fut
172+
}
173+
root = &fut.next
174+
}
175+
}
176+
177+
func (list *futureList) addFuture(fut *Future) {
178+
*list.last = fut
179+
list.last = &fut.next
180+
}
181+
182+
func (list *futureList) clear(err error, conn *Connection) {
183+
fut := list.first
184+
list.first = nil
185+
list.last = &list.first
186+
for fut != nil {
187+
fut.SetError(err)
188+
conn.markDone(fut)
189+
fut, fut.next = fut.next, nil
190+
}
191+
}
192+
146193
type connShard struct {
147-
rmut sync.Mutex
148-
requests [requestsMap]struct {
149-
first *Future
150-
last **Future
151-
}
152-
bufmut sync.Mutex
153-
buf smallWBuf
154-
enc *msgpack.Encoder
155-
_pad [16]uint64 //nolint: unused,structcheck
194+
rmut sync.Mutex
195+
requests [requestsMap]futureList
196+
requestsWithCtx [requestsMap]futureList
197+
bufmut sync.Mutex
198+
buf smallWBuf
199+
enc *msgpack.Encoder
200+
_pad [16]uint64 //nolint: unused,structcheck
156201
}
157202

158203
// Greeting is a message sent by Tarantool on connect.
@@ -262,12 +307,13 @@ type SslOpts struct {
262307
// and will not finish to make attempts on authorization failures.
263308
func Connect(addr string, opts Opts) (conn *Connection, err error) {
264309
conn = &Connection{
265-
addr: addr,
266-
requestId: 0,
267-
Greeting: &Greeting{},
268-
control: make(chan struct{}),
269-
opts: opts,
270-
dec: msgpack.NewDecoder(&smallBuf{}),
310+
addr: addr,
311+
requestId: 0,
312+
contextRequestId: 1,
313+
Greeting: &Greeting{},
314+
control: make(chan struct{}),
315+
opts: opts,
316+
dec: msgpack.NewDecoder(&smallBuf{}),
271317
}
272318
maxprocs := uint32(runtime.GOMAXPROCS(-1))
273319
if conn.opts.Concurrency == 0 || conn.opts.Concurrency > maxprocs*128 {
@@ -283,8 +329,11 @@ func Connect(addr string, opts Opts) (conn *Connection, err error) {
283329
conn.shard = make([]connShard, conn.opts.Concurrency)
284330
for i := range conn.shard {
285331
shard := &conn.shard[i]
286-
for j := range shard.requests {
287-
shard.requests[j].last = &shard.requests[j].first
332+
requestsLists := []*[requestsMap]futureList{&shard.requests, &shard.requestsWithCtx}
333+
for _, requests := range requestsLists {
334+
for j := range requests {
335+
requests[j].last = &requests[j].first
336+
}
288337
}
289338
}
290339

@@ -387,6 +436,13 @@ func (conn *Connection) Handle() interface{} {
387436
return conn.opts.Handle
388437
}
389438

439+
func (conn *Connection) cancelFuture(fut *Future, err error) {
440+
if fut = conn.fetchFuture(fut.requestId); fut != nil {
441+
fut.SetError(err)
442+
conn.markDone(fut)
443+
}
444+
}
445+
390446
func (conn *Connection) dial() (err error) {
391447
var connection net.Conn
392448
network := "tcp"
@@ -580,15 +636,10 @@ func (conn *Connection) closeConnection(neterr error, forever bool) (err error)
580636
}
581637
for i := range conn.shard {
582638
conn.shard[i].buf.Reset()
583-
requests := &conn.shard[i].requests
584-
for pos := range requests {
585-
fut := requests[pos].first
586-
requests[pos].first = nil
587-
requests[pos].last = &requests[pos].first
588-
for fut != nil {
589-
fut.SetError(neterr)
590-
conn.markDone(fut)
591-
fut, fut.next = fut.next, nil
639+
requestsLists := []*[requestsMap]futureList{&conn.shard[i].requests, &conn.shard[i].requestsWithCtx}
640+
for _, requests := range requestsLists {
641+
for pos := range requests {
642+
requests[pos].clear(neterr, conn)
592643
}
593644
}
594645
}
@@ -721,7 +772,7 @@ func (conn *Connection) reader(r *bufio.Reader, c net.Conn) {
721772
}
722773
}
723774

724-
func (conn *Connection) newFuture() (fut *Future) {
775+
func (conn *Connection) newFuture(ctx context.Context) (fut *Future) {
725776
fut = NewFuture()
726777
if conn.rlimit != nil && conn.opts.RLimitAction == RLimitDrop {
727778
select {
@@ -736,7 +787,7 @@ func (conn *Connection) newFuture() (fut *Future) {
736787
return
737788
}
738789
}
739-
fut.requestId = conn.nextRequestId()
790+
fut.requestId = conn.nextRequestId(ctx != nil)
740791
shardn := fut.requestId & (conn.opts.Concurrency - 1)
741792
shard := &conn.shard[shardn]
742793
shard.rmut.Lock()
@@ -761,11 +812,20 @@ func (conn *Connection) newFuture() (fut *Future) {
761812
return
762813
}
763814
pos := (fut.requestId / conn.opts.Concurrency) & (requestsMap - 1)
764-
pair := &shard.requests[pos]
765-
*pair.last = fut
766-
pair.last = &fut.next
767-
if conn.opts.Timeout > 0 {
768-
fut.timeout = time.Since(epoch) + conn.opts.Timeout
815+
if ctx != nil {
816+
select {
817+
case <-ctx.Done():
818+
fut.SetError(fmt.Errorf("context is done"))
819+
shard.rmut.Unlock()
820+
return
821+
default:
822+
}
823+
shard.requestsWithCtx[pos].addFuture(fut)
824+
} else {
825+
shard.requests[pos].addFuture(fut)
826+
if conn.opts.Timeout > 0 {
827+
fut.timeout = time.Since(epoch) + conn.opts.Timeout
828+
}
769829
}
770830
shard.rmut.Unlock()
771831
if conn.rlimit != nil && conn.opts.RLimitAction == RLimitWait {
@@ -785,12 +845,43 @@ func (conn *Connection) newFuture() (fut *Future) {
785845
return
786846
}
787847

848+
// This method removes a future from the internal queue if the context
849+
// is "done" before the response is come. Such select logic is inspired
850+
// from this thread: https://groups.google.com/g/golang-dev/c/jX4oQEls3uk
851+
func (conn *Connection) contextWatchdog(fut *Future, ctx context.Context) {
852+
select {
853+
case <-fut.done:
854+
default:
855+
select {
856+
case <-ctx.Done():
857+
conn.cancelFuture(fut, fmt.Errorf("context is done"))
858+
default:
859+
select {
860+
case <-fut.done:
861+
case <-ctx.Done():
862+
conn.cancelFuture(fut, fmt.Errorf("context is done"))
863+
}
864+
}
865+
}
866+
}
867+
788868
func (conn *Connection) send(req Request) *Future {
789-
fut := conn.newFuture()
869+
fut := conn.newFuture(req.Ctx())
790870
if fut.ready == nil {
791871
return fut
792872
}
873+
if req.Ctx() != nil {
874+
select {
875+
case <-req.Ctx().Done():
876+
conn.cancelFuture(fut, fmt.Errorf("context is done"))
877+
return fut
878+
default:
879+
}
880+
}
793881
conn.putFuture(fut, req)
882+
if req.Ctx() != nil {
883+
go conn.contextWatchdog(fut, req.Ctx())
884+
}
794885
return fut
795886
}
796887

@@ -877,25 +968,11 @@ func (conn *Connection) fetchFuture(reqid uint32) (fut *Future) {
877968
func (conn *Connection) getFutureImp(reqid uint32, fetch bool) *Future {
878969
shard := &conn.shard[reqid&(conn.opts.Concurrency-1)]
879970
pos := (reqid / conn.opts.Concurrency) & (requestsMap - 1)
880-
pair := &shard.requests[pos]
881-
root := &pair.first
882-
for {
883-
fut := *root
884-
if fut == nil {
885-
return nil
886-
}
887-
if fut.requestId == reqid {
888-
if fetch {
889-
*root = fut.next
890-
if fut.next == nil {
891-
pair.last = root
892-
} else {
893-
fut.next = nil
894-
}
895-
}
896-
return fut
897-
}
898-
root = &fut.next
971+
// futures with even requests id belong to requests list with nil context
972+
if reqid%2 == 0 {
973+
return shard.requests[pos].findFuture(reqid, fetch)
974+
} else {
975+
return shard.requestsWithCtx[pos].findFuture(reqid, fetch)
899976
}
900977
}
901978

@@ -984,8 +1061,12 @@ func (conn *Connection) read(r io.Reader) (response []byte, err error) {
9841061
return
9851062
}
9861063

987-
func (conn *Connection) nextRequestId() (requestId uint32) {
988-
return atomic.AddUint32(&conn.requestId, 1)
1064+
func (conn *Connection) nextRequestId(context bool) (requestId uint32) {
1065+
if context {
1066+
return atomic.AddUint32(&conn.contextRequestId, 2)
1067+
} else {
1068+
return atomic.AddUint32(&conn.requestId, 2)
1069+
}
9891070
}
9901071

9911072
// Do performs a request asynchronously on the connection.
@@ -1000,6 +1081,15 @@ func (conn *Connection) Do(req Request) *Future {
10001081
return fut
10011082
}
10021083
}
1084+
if req.Ctx() != nil {
1085+
select {
1086+
case <-req.Ctx().Done():
1087+
fut := NewFuture()
1088+
fut.SetError(fmt.Errorf("context is done"))
1089+
return fut
1090+
default:
1091+
}
1092+
}
10031093
return conn.send(req)
10041094
}
10051095

example_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package tarantool_test
22

33
import (
4+
"context"
45
"fmt"
56
"time"
67

@@ -691,3 +692,33 @@ func ExampleConnection_NewPrepared() {
691692
fmt.Printf("Failed to prepare")
692693
}
693694
}
695+
696+
// To pass contexts to request objects, use the Context() method.
697+
// Pay attention that when using context with request objects,
698+
// the timeout option for Connection will not affect the lifetime
699+
// of the request. For those purposes use context.WithTimeout() as
700+
// the root context.
701+
func ExamplePingRequest_Context() {
702+
conn := example_connect()
703+
defer conn.Close()
704+
705+
timeout := time.Nanosecond
706+
707+
// this way you may set the common timeout for requests with context
708+
rootCtx, cancelRoot := context.WithTimeout(context.Background(), timeout)
709+
defer cancelRoot()
710+
711+
// this context will be canceled with the root after commonTimeout
712+
ctx, cancel := context.WithCancel(rootCtx)
713+
defer cancel()
714+
715+
req := tarantool.NewPingRequest().Context(ctx)
716+
717+
// Ping a Tarantool instance to check connection.
718+
resp, err := conn.Do(req).Get()
719+
fmt.Println("Ping Resp", resp)
720+
fmt.Println("Ping Error", err)
721+
// Output:
722+
// Ping Resp <nil>
723+
// Ping Error context is done
724+
}

0 commit comments

Comments
 (0)