forked from rethinkdb/rethinkdb-go
/
session.go
367 lines (303 loc) · 8.38 KB
/
session.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
package gorethink
import (
"sync"
"sync/atomic"
"time"
"code.google.com/p/goprotobuf/proto"
p "github.com/dancannon/gorethink/ql2"
)
type Session struct {
token int64
address string
database string
timeout time.Duration
authkey string
timeFormat string
// Pool configuration options
maxIdle int
maxActive int
idleTimeout time.Duration
// Response cache, used for batched responses
sync.Mutex
cache map[int64]*Cursor
closed bool
pool *Pool
}
func newSession(args map[string]interface{}) *Session {
s := &Session{
cache: map[int64]*Cursor{},
}
if token, ok := args["token"]; ok {
s.token = token.(int64)
}
if address, ok := args["address"]; ok {
s.address = address.(string)
}
if database, ok := args["database"]; ok {
s.database = database.(string)
}
if timeout, ok := args["timeout"]; ok {
s.timeout = timeout.(time.Duration)
}
if authkey, ok := args["authkey"]; ok {
s.authkey = authkey.(string)
}
// Pool configuration options
if maxIdle, ok := args["maxIdle"]; ok {
s.maxIdle = maxIdle.(int)
} else {
s.maxIdle = 1
}
if maxActive, ok := args["maxActive"]; ok {
s.maxActive = maxActive.(int)
} else {
s.maxActive = 0
}
if idleTimeout, ok := args["idleTimeout"]; ok {
s.idleTimeout = idleTimeout.(time.Duration)
} else {
s.idleTimeout = 10 * time.Second
}
return s
}
type ConnectOpts struct {
Token int64 `gorethink:"token,omitempty"`
Address string `gorethink:"address,omitempty"`
Database string `gorethink:"database,omitempty"`
Timeout time.Duration `gorethink:"timeout,omitempty"`
AuthKey string `gorethink:"authkey,omitempty"`
MaxIdle int `gorethink:"max_idle,omitempty"`
MaxActive int `gorethink:"max_active,omitempty"`
IdleTimeout time.Duration `gorethink:"idle_timeout,omitempty"`
}
func (o *ConnectOpts) toMap() map[string]interface{} {
return optArgsToMap(o)
}
// Connect creates a new database session.
//
// Supported arguments include token, address, database, timeout, authkey,
// and timeFormat. Pool options include maxIdle, maxActive and idleTimeout.
//
// By default maxIdle and maxActive are set to 1: passing values greater
// than the default (e.g. maxIdle: "10", maxActive: "20") will provide a
// pool of re-usable connections.
//
// Basic connection example:
//
// var session *r.Session
// session, err := r.Connect(r.ConnectOpts{
// Address: "localhost:28015",
// Database: "test",
// AuthKey: "14daak1cad13dj",
// })
func Connect(args ConnectOpts) (*Session, error) {
s := newSession(args.toMap())
err := s.Reconnect()
return s, err
}
type CloseOpts struct {
NoReplyWait bool `gorethink:"noreplyWait,omitempty"`
}
func (o *CloseOpts) toMap() map[string]interface{} {
return optArgsToMap(o)
}
// Reconnect closes and re-opens a session.
func (s *Session) Reconnect(optArgs ...CloseOpts) error {
if err := s.Close(optArgs...); err != nil {
return err
}
s.closed = false
if s.pool == nil {
s.pool = &Pool{
Session: s,
MaxIdle: s.maxIdle,
MaxActive: s.maxActive,
IdleTimeout: s.idleTimeout,
}
}
// Check the connection
conn, err := s.pool.get()
if err == nil {
conn.Close()
}
return err
}
// Close closes the session
func (s *Session) Close(optArgs ...CloseOpts) error {
if s.closed {
return nil
}
if len(optArgs) >= 1 {
if optArgs[0].NoReplyWait {
s.NoReplyWait()
}
}
var err error
if s.pool != nil {
err = s.pool.Close()
}
s.closed = true
return err
}
// noreplyWait ensures that previous queries with the noreply flag have been
// processed by the server. Note that this guarantee only applies to queries
// run on the given connection
func (s *Session) NoReplyWait() {
s.noreplyWaitQuery()
}
// Use changes the default database used
func (s *Session) Use(database string) {
s.database = database
}
// SetTimeout causes any future queries that are run on this session to timeout
// after the given duration, returning a timeout error. Set to zero to disable.
func (s *Session) SetTimeout(timeout time.Duration) {
s.timeout = timeout
}
// SetMaxIdleConns sets the maximum number of connections in the idle
// connection pool.
//
// If MaxOpenConns is greater than 0 but less than the new MaxIdleConns
// then the new MaxIdleConns will be reduced to match the MaxOpenConns limit
//
// If n <= 0, no idle connections are retained.
func (s *Session) SetMaxIdleConns(n int) {
s.pool.MaxIdle = n
}
// SetMaxOpenConns sets the maximum number of open connections to the database.
//
// If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
// MaxIdleConns, then MaxIdleConns will be reduced to match the new
// MaxOpenConns limit
//
// If n <= 0, then there is no limit on the number of open connections.
// The default is 0 (unlimited).
func (s *Session) SetMaxOpenConns(n int) {
s.pool.MaxActive = n
}
// getToken generates the next query token, used to number requests and match
// responses with requests.
func (s *Session) nextToken() int64 {
return atomic.AddInt64(&s.token, 1)
}
// startQuery creates a query from the term given and sends it to the server.
// The result from the server is returned as a cursor
func (s *Session) startQuery(t Term, opts map[string]interface{}) (*Cursor, error) {
token := s.nextToken()
// Build query tree
pt := t.build()
// Build global options
globalOpts := []*p.Query_AssocPair{}
for k, v := range opts {
globalOpts = append(globalOpts, &p.Query_AssocPair{
Key: proto.String(k),
Val: Expr(v).build(),
})
}
// If no DB option was set default to the value set in the connection
if _, ok := opts["db"]; !ok {
globalOpts = append(globalOpts, &p.Query_AssocPair{
Key: proto.String("db"),
Val: Db(s.database).build(),
})
}
// Construct query
q := &p.Query{
AcceptsRJson: proto.Bool(true),
Type: p.Query_START.Enum(),
Token: proto.Int64(token),
Query: pt,
GlobalOptargs: globalOpts,
}
// Get a connection from the pool, do not close yet as it
// might be needed later if a partial response is returned
conn := s.pool.Get()
return conn.SendQuery(s, q, t, opts, false)
}
func (s *Session) handleBatchResponse(cursor *Cursor, response *p.Response) {
cursor.extend(response)
s.Lock()
cursor.outstandingRequests -= 1
if response.GetType() != p.Response_SUCCESS_PARTIAL &&
response.GetType() != p.Response_SUCCESS_FEED &&
cursor.outstandingRequests == 0 {
delete(s.cache, response.GetToken())
}
s.Unlock()
}
// continueQuery continues a previously run query.
// This is needed if a response is batched.
func (s *Session) continueQuery(cursor *Cursor) error {
err := s.asyncContinueQuery(cursor)
if err != nil {
return err
}
response, err := cursor.conn.ReadResponse(s, cursor.query.GetToken())
if err != nil {
return err
}
s.handleBatchResponse(cursor, response)
return nil
}
// asyncContinueQuery asynchronously continues a previously run query.
// This is needed if a response is batched.
func (s *Session) asyncContinueQuery(cursor *Cursor) error {
s.Lock()
if cursor.outstandingRequests != 0 {
s.Unlock()
return nil
}
cursor.outstandingRequests = 1
s.Unlock()
q := &p.Query{
Type: p.Query_CONTINUE.Enum(),
Token: cursor.query.Token,
}
_, err := cursor.conn.SendQuery(s, q, cursor.term, cursor.opts, true)
if err != nil {
return err
}
return nil
}
// stopQuery sends closes a query by sending Query_STOP to the server.
func (s *Session) stopQuery(cursor *Cursor) error {
cursor.mu.Lock()
cursor.outstandingRequests += 1
cursor.mu.Unlock()
q := &p.Query{
Type: p.Query_STOP.Enum(),
Token: cursor.query.Token,
}
_, err := cursor.conn.SendQuery(s, q, cursor.term, cursor.opts, false)
if err != nil {
return err
}
response, err := cursor.conn.ReadResponse(s, cursor.query.GetToken())
if err != nil {
return err
}
s.handleBatchResponse(cursor, response)
return nil
}
// noreplyWaitQuery sends the NOREPLY_WAIT query to the server.
func (s *Session) noreplyWaitQuery() error {
q := &p.Query{
Type: p.Query_NOREPLY_WAIT.Enum(),
Token: proto.Int64(s.nextToken()),
}
conn := s.pool.Get()
defer conn.Close()
_, err := conn.SendQuery(s, q, Term{}, map[string]interface{}{}, false)
return err
}
func (s *Session) checkCache(token int64) (*Cursor, bool) {
s.Lock()
defer s.Unlock()
cursor, ok := s.cache[token]
return cursor, ok
}
func (s *Session) setCache(token int64, cursor *Cursor) {
s.Lock()
defer s.Unlock()
s.cache[token] = cursor
}