forked from hokapoka/go-mongo
/
connection.go
605 lines (547 loc) · 12.8 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
// Copyright 2011 Gary Burd
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package mongo
import (
"bufio"
"io"
"net"
"os"
"strconv"
"strings"
)
const (
updateUpsert = 1 << 0
updateMulti = 1 << 1
removeSingle = 1 << 0
queryTailable = 1 << 1
querySlaveOk = 1 << 2
queryNoCursorTimeout = 1 << 4
queryAwaitData = 1 << 5
queryExhaust = 1 << 6
queryPartialResults = 1 << 7
cursorNotFound = 1 << 0
queryFailure = 1 << 1
)
type connection struct {
conn net.Conn
addr string
requestId uint32
cursors map[uint32]*cursor
err os.Error
buf [1024]byte
responseLen int
responseCount int
cursor *cursor
br *bufio.Reader
}
type cursor struct {
conn *connection
namespace string
requestId uint32
cursorId uint64
limit int
batchSize int
count int
docs [][]byte
flags int
err os.Error
}
// Dial connects to server at addr.
func Dial(addr string) (Conn, os.Error) {
if strings.LastIndex(addr, ":") <= strings.LastIndex(addr, "]") {
addr = addr + ":27017"
}
c := connection{
addr: addr,
cursors: make(map[uint32]*cursor),
}
return &c, c.connect()
}
func (c *connection) connect() os.Error {
conn, err := net.Dial("tcp", c.addr)
if err != nil {
return err
}
if c.conn != nil {
c.conn.Close()
}
c.conn = conn
c.br = bufio.NewReader(conn)
return nil
}
func (c *connection) nextId() uint32 {
c.requestId += 1
return c.requestId
}
func (c *connection) fatal(err os.Error) os.Error {
if c.err == nil {
c.Close()
c.err = err
}
return err
}
// Close closes the connection to the server.
func (c *connection) Close() (err os.Error) {
if c.conn != nil {
err = c.conn.Close()
c.conn = nil
}
c.cursors = nil
c.cursor = nil
c.responseCount = 0
c.responseLen = 0
c.err = os.NewError("mongo: connection closed")
return err
}
func (c *connection) Error() os.Error {
return c.err
}
// send sets the message length and writes the message to the socket.
func (c *connection) send(msg []byte) os.Error {
if c.err != nil {
return c.err
}
wire.PutUint32(msg[0:4], uint32(len(msg)))
_, err := c.conn.Write(msg)
if err != nil {
return c.fatal(err)
}
return nil
}
func (c *connection) Update(namespace string, selector, update interface{}, options *UpdateOptions) (err os.Error) {
if selector == nil {
selector = emptyDoc
}
flags := 0
if options != nil {
if options.Upsert {
flags |= updateUpsert
}
if options.Multi {
flags |= updateMulti
}
}
b := buffer(c.buf[:0])
b.Next(4) // placeholder for message length
b.WriteUint32(c.nextId()) // requestId
b.WriteUint32(0) // responseTo
b.WriteUint32(2001) // opCode
b.WriteUint32(0) // reserved
b.WriteCString(namespace) // namespace
b.WriteUint32(uint32(flags)) // flags
b, err = Encode(b, selector)
if err != nil {
return err
}
b, err = Encode(b, update)
if err != nil {
return err
}
return c.send(b)
}
func (c *connection) Insert(namespace string, documents ...interface{}) (err os.Error) {
if len(documents) == 0 {
return os.NewError("mongo: insert with no documents")
}
b := buffer(c.buf[:0])
b.Next(4) // placeholder for message length
b.WriteUint32(c.nextId()) // requestId
b.WriteUint32(0) // responseTo
b.WriteUint32(2002) // opCode
b.WriteUint32(0) // reserved
b.WriteCString(namespace) // namespace
for _, document := range documents {
b, err = Encode(b, document)
if err != nil {
return err
}
}
return c.send(b)
}
func (c *connection) Remove(namespace string, selector interface{}, options *RemoveOptions) (err os.Error) {
if selector == nil {
selector = emptyDoc
}
flags := 0
if options != nil {
if options.Single {
flags |= removeSingle
}
}
b := buffer(c.buf[:0])
b.Next(4) // placeholder for message length
b.WriteUint32(c.nextId()) // requestId
b.WriteUint32(0) // responseTo
b.WriteUint32(2006) // opCode
b.WriteUint32(0) // reserved
b.WriteCString(namespace) // namespace
b.WriteUint32(uint32(flags)) // flags
b, err = Encode(b, selector)
if err != nil {
return err
}
return c.send(b)
}
func (c *connection) Find(namespace string, query interface{}, options *FindOptions) (Cursor, os.Error) {
r := cursor{
conn: c,
namespace: namespace,
requestId: c.nextId(),
}
if query == nil {
query = emptyDoc
}
var fields interface{}
var skip int
if options != nil {
skip = options.Skip
fields = options.Fields
r.limit = options.Limit
r.batchSize = options.BatchSize
if r.batchSize == 1 {
// Server handles numberToReturn == 1 as hard limit. Change value
// to two to avoid having batch size set hard limit.
r.batchSize = 2
}
if options.Tailable {
r.flags |= queryTailable
r.limit = 0
}
if options.SlaveOk {
r.flags |= querySlaveOk
}
if options.NoCursorTimeout {
r.flags |= queryNoCursorTimeout
}
if options.AwaitData {
r.flags |= queryAwaitData
}
if options.Exhaust {
r.flags |= queryExhaust
}
if options.PartialResults {
r.flags |= queryPartialResults
}
}
b := buffer(c.buf[:0])
b.Next(4) // placeholder for message length
b.WriteUint32(r.requestId) // requestId
b.WriteUint32(0) // responseTo
b.WriteUint32(2004) // opCode
b.WriteUint32(uint32(r.flags)) // flags
b.WriteCString(namespace) // namespace
b.WriteUint32(uint32(skip)) // numberToSkip
b.WriteUint32(r.numberToReturn()) // numberToReturn
b, err := Encode(b, query)
if err != nil {
return nil, err
}
if fields != nil {
b, err = Encode(b, fields)
if err != nil {
return nil, err
}
}
err = c.send(b)
if err != nil {
return nil, err
}
c.cursors[r.requestId] = &r
return &r, nil
}
func (c *connection) getMore(r *cursor) os.Error {
requestId := c.nextId()
b := buffer(c.buf[:0])
b.Next(4) // placeholder for message length
b.WriteUint32(requestId) // requestId
b.WriteUint32(0) // responseTo
b.WriteUint32(2005) // opCode
b.WriteUint32(0) // reserved
b.WriteCString(r.namespace) // namespace
b.WriteUint32(r.numberToReturn())
b.WriteUint64(r.cursorId)
if err := c.send(b); err != nil {
return err
}
r.requestId = requestId
c.cursors[requestId] = r
return nil
}
func (c *connection) killCursors(cursorIds ...uint64) os.Error {
b := buffer(c.buf[:0])
b.Next(4) // placeholder for message length
b.WriteUint32(c.nextId()) // requestId
b.WriteUint32(0) // responseTo
b.WriteUint32(2007) // opCode
b.WriteUint32(0) // zero
b.WriteUint32(uint32(len(cursorIds))) // number of cursor ids.
for _, cursorId := range cursorIds {
b.WriteUint64(cursorId)
}
return c.send(b)
}
// readDoc reads a single document from the connection.
func (c *connection) readDoc(alloc bool) ([]byte, os.Error) {
if c.responseLen < 4 {
return nil, c.fatal(os.NewError("mongo: incomplete document in message"))
}
b, err := c.br.Peek(4)
if err != nil {
return nil, c.fatal(err)
}
n := int(wire.Uint32(b))
if c.responseLen < n {
return nil, c.fatal(os.NewError("mongo: incomplete document in message"))
}
var p []byte
if n > len(c.buf) || alloc {
p = make([]byte, n)
} else {
p = c.buf[:n]
}
_, err = io.ReadFull(c.br, p)
if err != nil {
return nil, c.fatal(err)
}
c.responseLen -= n
c.responseCount -= 1
if c.responseCount == 0 {
c.cursor = nil
if c.responseLen != 0 {
return nil, c.fatal(os.NewError("mongo: unexpected data in message."))
}
}
return p, nil
}
// skipDocs skips over unread documents in the current batch.
func (c *connection) skipDocs() os.Error {
for c.responseLen > 0 {
n := c.responseLen
if n > len(c.buf) {
n = len(c.buf)
}
var err os.Error
n, err = c.br.Read(c.buf[0:n])
if err != nil {
return c.fatal(err)
}
c.responseLen -= n
}
c.responseLen = 0
c.responseCount = 0
c.cursor = nil
return nil
}
// receive recieves a single response from the server and delivers it to the appropriate cursor.
func (c *connection) receive() os.Error {
if c.err != nil {
return c.err
}
// Slurp up documents for current cursor.
for c.responseCount > 0 {
r := c.cursor
p, err := c.readDoc(true)
if err != nil {
return err
}
r.docs = append(r.docs, p)
}
// Read response message header.
if _, err := io.ReadFull(c.br, c.buf[:36]); err != nil {
return c.fatal(err)
}
c.responseLen = int(wire.Uint32(c.buf[0:4]))
requestId := wire.Uint32(c.buf[4:8])
responseTo := wire.Uint32(c.buf[8:12])
opCode := int32(wire.Uint32(c.buf[12:16]))
flags := wire.Uint32(c.buf[16:20])
cursorId := wire.Uint64(c.buf[20:28])
//startingFrom := int32(wire.Uint32(c.buf[28:32]))
c.responseCount = int(wire.Uint32(c.buf[32:36]))
c.responseLen -= 36
if opCode != 1 {
return c.fatal(os.NewError("mongo: unknown response opcode " + strconv.Itoa(int(opCode))))
}
r := c.cursors[responseTo]
if r == nil {
if cursorId != 0 {
if err := c.killCursors(cursorId); err != nil {
return err
}
}
if err := c.skipDocs(); err != nil {
return err
}
return c.err
}
c.cursors[responseTo] = nil, false
r.cursorId = cursorId
r.requestId = 0
if r.flags&queryExhaust != 0 && cursorId != 0 {
r.requestId = requestId
c.cursors[requestId] = r
}
if flags&cursorNotFound != 0 {
r.fatal(os.NewError("mongo: cursor not found"))
if c.responseCount != 0 || c.responseLen != 0 {
return c.fatal(os.NewError("mongo: unexpected data after cursor not found."))
}
}
if flags&queryFailure != 0 {
if c.responseCount != 1 {
return c.fatal(os.NewError("mongo: unexpected number of docs for query failure."))
}
p, err := c.readDoc(false)
if err != nil {
return err
}
var m M
err = Decode(p, &m)
if err != nil {
r.fatal(err)
} else if s, ok := m["$err"].(string); ok {
r.fatal(os.NewError(s))
} else {
r.fatal(os.NewError("mongo: query failure"))
}
return c.err
}
if c.responseCount > 0 {
c.cursor = r
}
return c.err
}
func (r *cursor) numberToReturn() uint32 {
batchSize := r.batchSize
if batchSize < 0 {
batchSize *= -1
}
remaining := 0
if r.limit > 0 {
remaining = r.limit - r.count
}
n := 0
switch {
case batchSize == 0 && remaining > 0:
n = remaining
case batchSize > 0 && remaining == 0:
n = batchSize
case remaining < batchSize:
n = remaining
default:
n = batchSize
}
if r.batchSize < 0 {
n *= -1
}
if n == 1 {
n = -1
}
return uint32(n)
}
func (r *cursor) Close() os.Error {
if r.err != nil {
return nil
}
if r.cursorId != 0 {
r.conn.killCursors(r.cursorId)
}
if r.conn.cursor == r {
r.conn.skipDocs()
}
if r.requestId != 0 && r.conn.cursors != nil {
r.conn.cursors[r.requestId] = nil, false
}
r.err = os.NewError("mongo: cursor closed")
r.conn = nil
return nil
}
func (r *cursor) fatal(err os.Error) os.Error {
if r.err == nil {
r.Close()
r.err = err
}
return err
}
func (r *cursor) Error() os.Error {
return r.err
}
func (r *cursor) HasNext() bool {
// If HasNext() dectects an error other than EOF, then HasNext returns true
// so that the error is returned to the application on a subsequent call to
// Next().
if r.err != nil {
return r.err != EOF
}
if len(r.docs) > 0 || r.conn.cursor == r {
return true
}
if r.requestId == 0 {
if r.cursorId == 0 {
r.fatal(EOF)
return false
}
if err := r.conn.getMore(r); err != nil {
r.fatal(err)
return true
}
}
requestId := r.requestId
for r.requestId == requestId {
if err := r.conn.receive(); err != nil {
r.fatal(err)
break
}
}
switch {
case r.err != nil:
return r.err != EOF
case r.conn.cursor == r:
return true
case r.cursorId == 0:
r.fatal(EOF)
return false
}
// Tailable cursor case
return false
}
func (r *cursor) Next(value interface{}) os.Error {
if !r.HasNext() {
return EOF
}
if r.err != nil {
return r.err
}
var p []byte
switch {
case len(r.docs) > 0:
p = r.docs[0]
r.docs[0] = nil
r.docs = r.docs[1:]
case r.conn.cursor == r:
var err os.Error
p, err = r.conn.readDoc(false)
if err != nil {
return r.fatal(err)
}
default:
panic("unexpected state")
}
err := Decode(p, value)
r.count += 1
if r.limit > 0 && r.count >= r.limit {
r.fatal(EOF)
}
return err
}