/
connection.go
executable file
·831 lines (708 loc) · 21.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
// Copyright (C) MongoDB, Inc. 2017-present.
//
// 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
// Package connection contains the types for building and pooling connections that can speak the
// MongoDB Wire Protocol. Since this low level library is meant to be used in the context of either
// a driver or a server there are some extra identifiers on a connection so one can keep track of
// what a connection is. This package purposefully hides the underlying network and abstracts the
// writing to and reading from a connection to wireops.Op's. This package also provides types for
// listening for and accepting Connections, as well as some types for handling connections and
// proxying connections to another server.
package connection
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strings"
"sync/atomic"
"time"
"github.com/Vincent20101/mongo-go-driver/bson"
"github.com/Vincent20101/mongo-go-driver/core/address"
"github.com/Vincent20101/mongo-go-driver/core/compressor"
"github.com/Vincent20101/mongo-go-driver/core/description"
"github.com/Vincent20101/mongo-go-driver/core/event"
"github.com/Vincent20101/mongo-go-driver/core/wiremessage"
)
var globalClientConnectionID uint64
var emptyDoc = bson.NewDocument()
func nextClientConnectionID() uint64 {
return atomic.AddUint64(&globalClientConnectionID, 1)
}
// Connection is used to read and write wire protocol messages to a network.
type Connection interface {
WriteWireMessage(context.Context, wiremessage.WireMessage) error
ReadWireMessage(context.Context) (wiremessage.WireMessage, error)
Close() error
Expired() bool
Alive() bool
ID() string
}
// Dialer is used to make network connections.
type Dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
// DialerFunc is a type implemented by functions that can be used as a Dialer.
type DialerFunc func(ctx context.Context, network, address string) (net.Conn, error)
// DialContext implements the Dialer interface.
func (df DialerFunc) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return df(ctx, network, address)
}
// DefaultDialer is the Dialer implementation that is used by this package. Changing this
// will also change the Dialer used for this package. This should only be changed why all
// of the connections being made need to use a different Dialer. Most of the time, using a
// WithDialer option is more appropriate than changing this variable.
var DefaultDialer Dialer = &net.Dialer{}
// Handshaker is the interface implemented by types that can perform a MongoDB
// handshake over a provided ReadWriter. This is used during connection
// initialization.
type Handshaker interface {
Handshake(context.Context, address.Address, wiremessage.ReadWriter) (description.Server, error)
}
// HandshakerFunc is an adapter to allow the use of ordinary functions as
// connection handshakers.
type HandshakerFunc func(context.Context, address.Address, wiremessage.ReadWriter) (description.Server, error)
// Handshake implements the Handshaker interface.
func (hf HandshakerFunc) Handshake(ctx context.Context, addr address.Address, rw wiremessage.ReadWriter) (description.Server, error) {
return hf(ctx, addr, rw)
}
type connection struct {
addr address.Address
id string
conn net.Conn
compressBuf []byte // buffer to compress messages
compressor compressor.Compressor // use for compressing messages
// server can compress response with any compressor supported by driver
compressorMap map[wiremessage.CompressorID]compressor.Compressor
commandMap map[int64]*event.CommandMetadata // map for monitoring commands sent to server
dead bool
idleTimeout time.Duration
idleDeadline time.Time
lifetimeDeadline time.Time
cmdMonitor *event.CommandMonitor
readTimeout time.Duration
uncompressBuf []byte // buffer to uncompress messages
writeTimeout time.Duration
readBuf []byte
writeBuf []byte
wireMessageBuf []byte // buffer to store uncompressed wire message before compressing
}
// New opens a connection to a given Addr
//
// The server description returned is nil if there was no handshaker provided.
func New(ctx context.Context, addr address.Address, opts ...Option) (Connection, *description.Server, error) {
cfg, err := newConfig(opts...)
if err != nil {
return nil, nil, err
}
nc, err := cfg.dialer.DialContext(ctx, addr.Network(), addr.String())
if err != nil {
return nil, nil, err
}
if cfg.tlsConfig != nil {
tlsConfig := cfg.tlsConfig.Clone()
nc, err = configureTLS(ctx, nc, addr, tlsConfig)
if err != nil {
return nil, nil, err
}
}
var lifetimeDeadline time.Time
if cfg.lifeTimeout > 0 {
lifetimeDeadline = time.Now().Add(cfg.lifeTimeout)
}
id := fmt.Sprintf("%s[-%d]", addr, nextClientConnectionID())
compressorMap := make(map[wiremessage.CompressorID]compressor.Compressor)
for _, comp := range cfg.compressors {
compressorMap[comp.CompressorID()] = comp
}
c := &connection{
id: id,
conn: nc,
compressBuf: make([]byte, 256),
compressorMap: compressorMap,
commandMap: make(map[int64]*event.CommandMetadata),
addr: addr,
idleTimeout: cfg.idleTimeout,
lifetimeDeadline: lifetimeDeadline,
readTimeout: cfg.readTimeout,
writeTimeout: cfg.writeTimeout,
readBuf: make([]byte, 256),
uncompressBuf: make([]byte, 256),
writeBuf: make([]byte, 0, 256),
wireMessageBuf: make([]byte, 256),
}
c.bumpIdleDeadline()
var desc *description.Server
if cfg.handshaker != nil {
d, err := cfg.handshaker.Handshake(ctx, c.addr, c)
if err != nil {
return nil, nil, err
}
if len(d.Compression) > 0 {
clientMethodLoop:
for _, comp := range cfg.compressors {
method := comp.Name()
for _, serverMethod := range d.Compression {
if method != serverMethod {
continue
}
c.compressor = comp // found matching compressor
break clientMethodLoop
}
}
}
desc = &d
}
c.cmdMonitor = cfg.cmdMonitor // attach the command monitor later to avoid monitoring auth
return c, desc, nil
}
func configureTLS(ctx context.Context, nc net.Conn, addr address.Address, config *TLSConfig) (net.Conn, error) {
if !config.InsecureSkipVerify {
hostname := addr.String()
colonPos := strings.LastIndex(hostname, ":")
if colonPos == -1 {
colonPos = len(hostname)
}
hostname = hostname[:colonPos]
config.ServerName = hostname
}
client := tls.Client(nc, config.Config)
errChan := make(chan error, 1)
go func() {
errChan <- client.Handshake()
}()
select {
case err := <-errChan:
if err != nil {
return nil, err
}
case <-ctx.Done():
return nil, errors.New("server connection cancelled/timeout during TLS handshake")
}
return client, nil
}
func (c *connection) Alive() bool {
return !c.dead
}
func (c *connection) Expired() bool {
now := time.Now()
if !c.idleDeadline.IsZero() && now.After(c.idleDeadline) {
return true
}
if !c.lifetimeDeadline.IsZero() && now.After(c.lifetimeDeadline) {
return true
}
return c.dead
}
func canCompress(cmd string) bool {
if cmd == "isMaster" || cmd == "saslStart" || cmd == "saslContinue" || cmd == "getnonce" || cmd == "authenticate" ||
cmd == "createUser" || cmd == "updateUser" || cmd == "copydbSaslStart" || cmd == "copydbgetnonce" || cmd == "copydb" {
return false
}
return true
}
func (c *connection) compressMessage(wm wiremessage.WireMessage) (wiremessage.WireMessage, error) {
var requestID int32
var responseTo int32
var origOpcode wiremessage.OpCode
switch converted := wm.(type) {
case wiremessage.Query:
firstElem, err := converted.Query.ElementAt(0)
if err != nil {
return wiremessage.Compressed{}, err
}
key := firstElem.Key()
if !canCompress(key) {
return wm, nil // return original message because this command can't be compressed
}
requestID = converted.MsgHeader.RequestID
origOpcode = wiremessage.OpQuery
responseTo = converted.MsgHeader.ResponseTo
case wiremessage.Msg:
firstElem, err := converted.Sections[0].(wiremessage.SectionBody).Document.ElementAt(0)
if err != nil {
return wiremessage.Compressed{}, err
}
key := firstElem.Key()
if !canCompress(key) {
return wm, nil
}
requestID = converted.MsgHeader.RequestID
origOpcode = wiremessage.OpMsg
responseTo = converted.MsgHeader.ResponseTo
}
// can compress
c.wireMessageBuf = c.wireMessageBuf[:0] // truncate
var err error
c.wireMessageBuf, err = wm.AppendWireMessage(c.wireMessageBuf)
if err != nil {
return wiremessage.Compressed{}, err
}
c.wireMessageBuf = c.wireMessageBuf[16:] // strip header
c.compressBuf = c.compressBuf[:0]
compressedBytes, err := c.compressor.CompressBytes(c.wireMessageBuf, c.compressBuf)
if err != nil {
return wiremessage.Compressed{}, err
}
compressedMessage := wiremessage.Compressed{
MsgHeader: wiremessage.Header{
// MessageLength and OpCode will be set when marshalling wire message by SetDefaults()
RequestID: requestID,
ResponseTo: responseTo,
},
OriginalOpCode: origOpcode,
UncompressedSize: int32(len(c.wireMessageBuf)), // length of uncompressed message excluding MsgHeader
CompressorID: wiremessage.CompressorID(c.compressor.CompressorID()),
CompressedMessage: compressedBytes,
}
return compressedMessage, nil
}
// returns []byte of uncompressed message with reconstructed header, original opcode, error
func (c *connection) uncompressMessage(compressed wiremessage.Compressed) ([]byte, wiremessage.OpCode, error) {
// server doesn't guarantee the same compression method will be used each time so the CompressorID field must be
// used to find the correct method for uncompressing data
uncompressor := c.compressorMap[compressed.CompressorID]
// reset uncompressBuf
c.uncompressBuf = c.uncompressBuf[:0]
if int(compressed.UncompressedSize) > cap(c.uncompressBuf) {
c.uncompressBuf = make([]byte, 0, compressed.UncompressedSize)
}
uncompressedMessage, err := uncompressor.UncompressBytes(compressed.CompressedMessage, c.uncompressBuf)
if err != nil {
return nil, 0, err
}
origHeader := wiremessage.Header{
MessageLength: int32(len(uncompressedMessage)) + 16, // add 16 for original header
RequestID: compressed.MsgHeader.RequestID,
ResponseTo: compressed.MsgHeader.ResponseTo,
}
switch compressed.OriginalOpCode {
case wiremessage.OpReply:
origHeader.OpCode = wiremessage.OpReply
case wiremessage.OpMsg:
origHeader.OpCode = wiremessage.OpMsg
default:
return nil, 0, fmt.Errorf("opcode %s not implemented", compressed.OriginalOpCode)
}
var fullMessage []byte
fullMessage = origHeader.AppendHeader(fullMessage)
fullMessage = append(fullMessage, uncompressedMessage...)
return fullMessage, origHeader.OpCode, nil
}
func canMonitor(cmd string) bool {
if cmd == "authenticate" || cmd == "saslStart" || cmd == "saslContinue" || cmd == "getnonce" || cmd == "createUser" ||
cmd == "updateUser" || cmd == "copydbgetnonce" || cmd == "copydbsaslstart" || cmd == "copydb" {
return false
}
return true
}
func (c *connection) commandStartedEvent(wm wiremessage.WireMessage) error {
if c.cmdMonitor == nil || c.cmdMonitor.Started == nil {
return nil
}
startedEvent := &event.CommandStartedEvent{
ConnectionID: c.id,
}
var cmd *bson.Document
var err error
var acknowledged bool
switch converted := wm.(type) {
case wiremessage.Query:
cmd, err = bson.ReadDocument([]byte(converted.Query))
if err != nil {
return err
}
acknowledged = converted.AcknowledgedWrite()
startedEvent.DatabaseName = converted.FullCollectionName[:len(converted.FullCollectionName)-5] // remove $.cmd
startedEvent.RequestID = int64(converted.MsgHeader.RequestID)
cmdElem := cmd.ElementAt(0)
if cmdElem.Key() == "$query" {
cmd = cmdElem.Value().MutableDocument()
}
case wiremessage.Msg:
cmd, err = converted.GetMainDocument()
if err != nil {
return err
}
acknowledged = converted.AcknowledgedWrite()
arr, identifier, err := converted.GetSequenceArray()
if err != nil {
return err
}
if arr != nil {
cmd = cmd.Copy() // make copy to avoid changing original command
cmd.Append(bson.EC.Array(identifier, arr))
}
dbVal, err := cmd.LookupErr("$db")
if err != nil {
return err
}
startedEvent.DatabaseName = dbVal.StringValue()
startedEvent.RequestID = int64(converted.MsgHeader.RequestID)
}
startedEvent.Command = cmd
startedEvent.CommandName = cmd.ElementAt(0).Key()
if !canMonitor(startedEvent.CommandName) {
startedEvent.Command = emptyDoc
}
c.cmdMonitor.Started(startedEvent)
if !acknowledged {
if c.cmdMonitor.Succeeded == nil {
return nil
}
// unack writes must provide a CommandSucceededEvent with an { ok: 1 } reply
finishedEvent := event.CommandFinishedEvent{
DurationNanos: 0,
CommandName: startedEvent.CommandName,
RequestID: startedEvent.RequestID,
ConnectionID: c.id,
}
c.cmdMonitor.Succeeded(&event.CommandSucceededEvent{
CommandFinishedEvent: finishedEvent,
Reply: bson.NewDocument(
bson.EC.Int32("ok", 1),
),
})
return nil
}
c.commandMap[startedEvent.RequestID] = event.CreateMetadata(startedEvent.CommandName)
return nil
}
func processReply(reply *bson.Document) (bool, string) {
iter := reply.Iterator()
var success bool
var errmsg string
var errCode int32
for iter.Next() {
elem := iter.Element()
switch elem.Key() {
case "ok":
switch elem.Value().Type() {
case bson.TypeInt32:
if elem.Value().Int32() == 1 {
success = true
}
case bson.TypeInt64:
if elem.Value().Int64() == 1 {
success = true
}
case bson.TypeDouble:
if elem.Value().Double() == 1 {
success = true
}
}
case "errmsg":
if str, ok := elem.Value().StringValueOK(); ok {
errmsg = str
}
case "code":
if c, ok := elem.Value().Int32OK(); ok {
errCode = c
}
}
}
if success {
return true, ""
}
fullErrMsg := fmt.Sprintf("Error code %d: %s", errCode, errmsg)
return false, fullErrMsg
}
func (c *connection) commandFinishedEvent(wm wiremessage.WireMessage) error {
if c.cmdMonitor == nil {
return nil
}
var reply *bson.Document
var requestID int64
var err error
switch converted := wm.(type) {
case wiremessage.Reply:
requestID = int64(converted.MsgHeader.ResponseTo)
reply, err = converted.GetMainDocument()
case wiremessage.Msg:
requestID = int64(converted.MsgHeader.ResponseTo)
reply, err = converted.GetMainDocument()
}
if err != nil {
return err
}
cmdMetadata := c.commandMap[requestID]
delete(c.commandMap, requestID)
success, errmsg := processReply(reply)
if (success && c.cmdMonitor.Succeeded == nil) || (!success && c.cmdMonitor.Failed == nil) {
return nil
}
finishedEvent := event.CommandFinishedEvent{
DurationNanos: cmdMetadata.TimeDifference(),
CommandName: cmdMetadata.Name,
RequestID: requestID,
ConnectionID: c.id,
}
if success {
if !canMonitor(finishedEvent.CommandName) {
successEvent := &event.CommandSucceededEvent{
Reply: emptyDoc,
CommandFinishedEvent: finishedEvent,
}
c.cmdMonitor.Succeeded(successEvent)
return nil
}
// if response has type 1 document sequence, the sequence must be included as a BSON array in the event's reply.
if opmsg, ok := wm.(wiremessage.Msg); ok {
arr, identifier, err := opmsg.GetSequenceArray()
if err != nil {
return err
}
if arr != nil {
reply = reply.Copy() // make copy to avoid changing original command
reply.Append(bson.EC.Array(identifier, arr))
}
}
successEvent := &event.CommandSucceededEvent{
Reply: reply,
CommandFinishedEvent: finishedEvent,
}
c.cmdMonitor.Succeeded(successEvent)
return nil
}
failureEvent := &event.CommandFailedEvent{
Failure: errmsg,
CommandFinishedEvent: finishedEvent,
}
c.cmdMonitor.Failed(failureEvent)
return nil
}
func (c *connection) WriteWireMessage(ctx context.Context, wm wiremessage.WireMessage) error {
var err error
if c.dead {
return Error{
ConnectionID: c.id,
message: "connection is dead",
}
}
select {
case <-ctx.Done():
return Error{
ConnectionID: c.id,
Wrapped: ctx.Err(),
message: "failed to write",
}
default:
}
deadline := time.Time{}
if c.writeTimeout != 0 {
deadline = time.Now().Add(c.writeTimeout)
}
if dl, ok := ctx.Deadline(); ok && (deadline.IsZero() || dl.Before(deadline)) {
deadline = dl
}
if err := c.conn.SetWriteDeadline(deadline); err != nil {
return Error{
ConnectionID: c.id,
Wrapped: err,
message: "failed to set write deadline",
}
}
// Truncate the write buffer
c.writeBuf = c.writeBuf[:0]
messageToWrite := wm
// Compress if possible
if c.compressor != nil {
compressed, err := c.compressMessage(wm)
if err != nil {
return Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to compress wire message",
}
}
messageToWrite = compressed
}
c.writeBuf, err = messageToWrite.AppendWireMessage(c.writeBuf)
if err != nil {
return Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to encode wire message",
}
}
_, err = c.conn.Write(c.writeBuf)
if err != nil {
c.Close()
return Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to write wire message to network",
}
}
c.bumpIdleDeadline()
err = c.commandStartedEvent(wm)
if err != nil {
return err
}
return nil
}
func (c *connection) ReadWireMessage(ctx context.Context) (wiremessage.WireMessage, error) {
if c.dead {
return nil, Error{
ConnectionID: c.id,
message: "connection is dead",
}
}
select {
case <-ctx.Done():
// We close the connection because we don't know if there
// is an unread message on the wire.
c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: ctx.Err(),
message: "failed to read",
}
default:
}
deadline := time.Time{}
if c.readTimeout != 0 {
deadline = time.Now().Add(c.readTimeout)
}
if ctxDL, ok := ctx.Deadline(); ok && (deadline.IsZero() || ctxDL.Before(deadline)) {
deadline = ctxDL
}
if err := c.conn.SetReadDeadline(deadline); err != nil {
return nil, Error{
ConnectionID: c.id,
Wrapped: ctx.Err(),
message: "failed to set read deadline",
}
}
var sizeBuf [4]byte
_, err := io.ReadFull(c.conn, sizeBuf[:])
if err != nil {
c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to decode message length",
}
}
size := readInt32(sizeBuf[:], 0)
// Isn't the best reuse, but resizing a []byte to be larger
// is difficult.
if len(c.readBuf) > int(size) {
c.readBuf = c.readBuf[:size]
} else {
c.readBuf = make([]byte, size)
}
c.readBuf[0], c.readBuf[1], c.readBuf[2], c.readBuf[3] = sizeBuf[0], sizeBuf[1], sizeBuf[2], sizeBuf[3]
_, err = io.ReadFull(c.conn, c.readBuf[4:])
if err != nil {
c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to read full message",
}
}
hdr, err := wiremessage.ReadHeader(c.readBuf, 0)
if err != nil {
c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to decode header",
}
}
messageToDecode := c.readBuf
opcodeToCheck := hdr.OpCode
if hdr.OpCode == wiremessage.OpCompressed {
var compressed wiremessage.Compressed
err := compressed.UnmarshalWireMessage(c.readBuf)
if err != nil {
defer c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to decode OP_COMPRESSED",
}
}
uncompressed, origOpcode, err := c.uncompressMessage(compressed)
if err != nil {
defer c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to uncompress message",
}
}
messageToDecode = uncompressed
opcodeToCheck = origOpcode
}
var wm wiremessage.WireMessage
switch opcodeToCheck {
case wiremessage.OpReply:
var r wiremessage.Reply
err := r.UnmarshalWireMessage(messageToDecode)
if err != nil {
c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to decode OP_REPLY",
}
}
wm = r
case wiremessage.OpMsg:
var reply wiremessage.Msg
err := reply.UnmarshalWireMessage(messageToDecode)
if err != nil {
c.Close()
return nil, Error{
ConnectionID: c.id,
Wrapped: err,
message: "unable to decode OP_MSG",
}
}
wm = reply
default:
c.Close()
return nil, Error{
ConnectionID: c.id,
message: fmt.Sprintf("opcode %s not implemented", hdr.OpCode),
}
}
c.bumpIdleDeadline()
err = c.commandFinishedEvent(wm)
if err != nil {
return nil, err // TODO: do we care if monitoring fails?
}
return wm, nil
}
func (c *connection) bumpIdleDeadline() {
if c.idleTimeout > 0 {
c.idleDeadline = time.Now().Add(c.idleTimeout)
}
}
func (c *connection) Close() error {
c.dead = true
err := c.conn.Close()
if err != nil {
return Error{
ConnectionID: c.id,
Wrapped: err,
message: "failed to close net.Conn",
}
}
return nil
}
func (c *connection) ID() string {
return c.id
}
func (c *connection) initialize(ctx context.Context, appName string) error {
return nil
}
func readInt32(b []byte, pos int32) int32 {
return (int32(b[pos+0])) | (int32(b[pos+1]) << 8) | (int32(b[pos+2]) << 16) | (int32(b[pos+3]) << 24)
}