From 868e9c0054472826699c252ed16ab3cf12156edd Mon Sep 17 00:00:00 2001 From: Qingyang Hu <103950869+qingyang-hu@users.noreply.github.com> Date: Wed, 29 Nov 2023 19:36:10 -0500 Subject: [PATCH 1/5] GODRIVER-3009 Fix concurrent panic in struct codec. (#1477) --- bson/bsoncodec/registry.go | 9 +++------ bson/bsoncodec/registry_test.go | 30 ++++++++++++++++++++++++++++++ bson/marshal_test.go | 17 +++++++++++++++++ bson/unmarshal_test.go | 19 +++++++++++++++++++ 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/bson/bsoncodec/registry.go b/bson/bsoncodec/registry.go index f309ee2b39..196c491bbb 100644 --- a/bson/bsoncodec/registry.go +++ b/bson/bsoncodec/registry.go @@ -388,6 +388,9 @@ func (r *Registry) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) { // If no encoder is found, an error of type ErrNoEncoder is returned. LookupEncoder is safe for // concurrent use by multiple goroutines after all codecs and encoders are registered. func (r *Registry) LookupEncoder(valueType reflect.Type) (ValueEncoder, error) { + if valueType == nil { + return nil, ErrNoEncoder{Type: valueType} + } enc, found := r.lookupTypeEncoder(valueType) if found { if enc == nil { @@ -400,15 +403,10 @@ func (r *Registry) LookupEncoder(valueType reflect.Type) (ValueEncoder, error) { if found { return r.typeEncoders.LoadOrStore(valueType, enc), nil } - if valueType == nil { - r.storeTypeEncoder(valueType, nil) - return nil, ErrNoEncoder{Type: valueType} - } if v, ok := r.kindEncoders.Load(valueType.Kind()); ok { return r.storeTypeEncoder(valueType, v), nil } - r.storeTypeEncoder(valueType, nil) return nil, ErrNoEncoder{Type: valueType} } @@ -474,7 +472,6 @@ func (r *Registry) LookupDecoder(valueType reflect.Type) (ValueDecoder, error) { if v, ok := r.kindDecoders.Load(valueType.Kind()); ok { return r.storeTypeDecoder(valueType, v), nil } - r.storeTypeDecoder(valueType, nil) return nil, ErrNoDecoder{Type: valueType} } diff --git a/bson/bsoncodec/registry_test.go b/bson/bsoncodec/registry_test.go index d09f32be5e..131981f1d8 100644 --- a/bson/bsoncodec/registry_test.go +++ b/bson/bsoncodec/registry_test.go @@ -789,6 +789,36 @@ func TestRegistry(t *testing.T) { }) }) } + t.Run("nil type", func(t *testing.T) { + t.Parallel() + + t.Run("Encoder", func(t *testing.T) { + t.Parallel() + + wanterr := ErrNoEncoder{Type: reflect.TypeOf(nil)} + + gotcodec, goterr := reg.LookupEncoder(nil) + if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) + } + if !cmp.Equal(gotcodec, nil, allowunexported, cmp.Comparer(comparepc)) { + t.Errorf("codecs did not match: got %#v, want nil", gotcodec) + } + }) + t.Run("Decoder", func(t *testing.T) { + t.Parallel() + + wanterr := ErrNilType + + gotcodec, goterr := reg.LookupDecoder(nil) + if !cmp.Equal(goterr, wanterr, cmp.Comparer(compareErrors)) { + t.Errorf("errors did not match: got %#v, want %#v", goterr, wanterr) + } + if !cmp.Equal(gotcodec, nil, allowunexported, cmp.Comparer(comparepc)) { + t.Errorf("codecs did not match: got %v: want nil", gotcodec) + } + }) + }) // lookup a type whose pointer implements an interface and expect that the registered hook is // returned t.Run("interface implementation with hook (pointer)", func(t *testing.T) { diff --git a/bson/marshal_test.go b/bson/marshal_test.go index 54b27dfcf1..99a3bba67e 100644 --- a/bson/marshal_test.go +++ b/bson/marshal_test.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "reflect" + "sync" "testing" "time" @@ -380,3 +381,19 @@ func TestMarshalExtJSONIndent(t *testing.T) { }) } } + +func TestMarshalConcurrently(t *testing.T) { + t.Parallel() + + const size = 10_000 + + wg := sync.WaitGroup{} + wg.Add(size) + for i := 0; i < size; i++ { + go func() { + defer wg.Done() + _, _ = Marshal(struct{ LastError error }{}) + }() + } + wg.Wait() +} diff --git a/bson/unmarshal_test.go b/bson/unmarshal_test.go index 11452a895c..2283b96771 100644 --- a/bson/unmarshal_test.go +++ b/bson/unmarshal_test.go @@ -9,6 +9,7 @@ package bson import ( "math/rand" "reflect" + "sync" "testing" "go.mongodb.org/mongo-driver/bson/bsoncodec" @@ -773,3 +774,21 @@ func TestUnmarshalByteSlicesUseDistinctArrays(t *testing.T) { }) } } + +func TestUnmarshalConcurrently(t *testing.T) { + t.Parallel() + + const size = 10_000 + + data := []byte{16, 0, 0, 0, 10, 108, 97, 115, 116, 101, 114, 114, 111, 114, 0, 0} + wg := sync.WaitGroup{} + wg.Add(size) + for i := 0; i < size; i++ { + go func() { + defer wg.Done() + var res struct{ LastError error } + _ = Unmarshal(data, &res) + }() + } + wg.Wait() +} From c0852202b3b6a0f6bdc48f35d95bce02020c5ce2 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Wed, 29 Nov 2023 20:06:47 -0600 Subject: [PATCH 2/5] GODRIVER-2603 [master] (Contd.) Revised error handling using Go 1.13 error APIs (#1484) Co-authored-by: Lokesh Kumar --- bson/bsoncodec/default_value_decoders.go | 2 +- bson/bsoncodec/default_value_encoders.go | 6 +++--- bson/bsoncodec/map_codec.go | 5 +++-- bson/bsoncodec/registry_test.go | 7 +++++-- bson/bsonrw/copier.go | 5 +++-- bson/bsonrw/extjson_parser.go | 2 +- bson/bsonrw/extjson_parser_test.go | 3 ++- bson/bsonrw/extjson_reader.go | 5 +++-- bson/bsonrw/json_scanner.go | 12 ++++++------ bson/bsonrw/value_reader_test.go | 7 ++++--- bson/decoder_test.go | 2 +- bson/primitive_codecs_test.go | 4 ++-- bson/raw_test.go | 7 ++++--- examples/documentation_examples/examples.go | 7 +++++-- internal/logger/logger.go | 2 +- mongo/bulk_write.go | 13 +++++++------ mongo/change_stream.go | 4 ++-- mongo/client.go | 2 +- mongo/client_encryption.go | 2 +- mongo/collection.go | 10 +++++----- mongo/integration/mtest/proxy_dialer.go | 6 +++--- mongo/integration/mtest/received_message.go | 4 ++-- mongo/integration/mtest/sent_message.go | 6 +++--- mongo/integration/mtest/setup.go | 12 ++++++------ x/bsonx/bsoncore/array_test.go | 2 +- x/bsonx/bsoncore/document_sequence_test.go | 7 ++++--- x/bsonx/bsoncore/document_test.go | 7 ++++--- x/mongo/driver/batch_cursor.go | 3 ++- x/mongo/driver/ocsp/cache_test.go | 4 ++-- x/mongo/driver/ocsp/config.go | 2 +- x/mongo/driver/ocsp/ocsp.go | 6 +++--- x/mongo/driver/operation.go | 5 +++-- x/mongo/driver/topology/errors.go | 7 ++++--- 33 files changed, 98 insertions(+), 80 deletions(-) diff --git a/bson/bsoncodec/default_value_decoders.go b/bson/bsoncodec/default_value_decoders.go index 4ba1b61019..7e08aab35e 100644 --- a/bson/bsoncodec/default_value_decoders.go +++ b/bson/bsoncodec/default_value_decoders.go @@ -1787,7 +1787,7 @@ func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr b elems := make([]reflect.Value, 0) for { key, vr, err := dr.ReadElement() - if err == bsonrw.ErrEOD { + if errors.Is(err, bsonrw.ErrEOD) { break } if err != nil { diff --git a/bson/bsoncodec/default_value_encoders.go b/bson/bsoncodec/default_value_encoders.go index 91a48c3a5b..4751ae995e 100644 --- a/bson/bsoncodec/default_value_encoders.go +++ b/bson/bsoncodec/default_value_encoders.go @@ -352,7 +352,7 @@ func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.Docum return err } - if lookupErr == errInvalidValue { + if errors.Is(lookupErr, errInvalidValue) { err = vw.WriteNull() if err != nil { return err @@ -427,7 +427,7 @@ func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.Val return err } - if lookupErr == errInvalidValue { + if errors.Is(lookupErr, errInvalidValue) { err = vw.WriteNull() if err != nil { return err @@ -496,7 +496,7 @@ func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.Val return err } - if lookupErr == errInvalidValue { + if errors.Is(lookupErr, errInvalidValue) { err = vw.WriteNull() if err != nil { return err diff --git a/bson/bsoncodec/map_codec.go b/bson/bsoncodec/map_codec.go index 6a5292f2c0..868e39ccc0 100644 --- a/bson/bsoncodec/map_codec.go +++ b/bson/bsoncodec/map_codec.go @@ -8,6 +8,7 @@ package bsoncodec import ( "encoding" + "errors" "fmt" "reflect" "strconv" @@ -137,7 +138,7 @@ func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, v return err } - if lookupErr == errInvalidValue { + if errors.Is(lookupErr, errInvalidValue) { err = vw.WriteNull() if err != nil { return err @@ -200,7 +201,7 @@ func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val ref for { key, vr, err := dr.ReadElement() - if err == bsonrw.ErrEOD { + if errors.Is(err, bsonrw.ErrEOD) { break } if err != nil { diff --git a/bson/bsoncodec/registry_test.go b/bson/bsoncodec/registry_test.go index 131981f1d8..2a7d50a719 100644 --- a/bson/bsoncodec/registry_test.go +++ b/bson/bsoncodec/registry_test.go @@ -7,6 +7,7 @@ package bsoncodec import ( + "errors" "reflect" "testing" @@ -351,7 +352,8 @@ func TestRegistryBuilder(t *testing.T) { }) t.Run("Decoder", func(t *testing.T) { wanterr := tc.wanterr - if ene, ok := tc.wanterr.(ErrNoEncoder); ok { + var ene ErrNoEncoder + if errors.As(tc.wanterr, &ene) { wanterr = ErrNoDecoder(ene) } @@ -775,7 +777,8 @@ func TestRegistry(t *testing.T) { t.Parallel() wanterr := tc.wanterr - if ene, ok := tc.wanterr.(ErrNoEncoder); ok { + var ene ErrNoEncoder + if errors.As(tc.wanterr, &ene) { wanterr = ErrNoDecoder(ene) } diff --git a/bson/bsonrw/copier.go b/bson/bsonrw/copier.go index 4d279b7fee..1e25570b85 100644 --- a/bson/bsonrw/copier.go +++ b/bson/bsonrw/copier.go @@ -7,6 +7,7 @@ package bsonrw import ( + "errors" "fmt" "io" @@ -442,7 +443,7 @@ func (c Copier) copyArray(dst ValueWriter, src ValueReader) error { for { vr, err := ar.ReadValue() - if err == ErrEOA { + if errors.Is(err, ErrEOA) { break } if err != nil { @@ -466,7 +467,7 @@ func (c Copier) copyArray(dst ValueWriter, src ValueReader) error { func (c Copier) copyDocumentCore(dw DocumentWriter, dr DocumentReader) error { for { key, vr, err := dr.ReadElement() - if err == ErrEOD { + if errors.Is(err, ErrEOD) { break } if err != nil { diff --git a/bson/bsonrw/extjson_parser.go b/bson/bsonrw/extjson_parser.go index 54c76bf746..bb52a0ec3d 100644 --- a/bson/bsonrw/extjson_parser.go +++ b/bson/bsonrw/extjson_parser.go @@ -313,7 +313,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { // convert hex to bytes bytes, err := hex.DecodeString(uuidNoHyphens) if err != nil { - return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding hex bytes: %v", err) + return nil, fmt.Errorf("$uuid value does not follow RFC 4122 format regarding hex bytes: %w", err) } ejp.advanceState() diff --git a/bson/bsonrw/extjson_parser_test.go b/bson/bsonrw/extjson_parser_test.go index 6808b14174..5da5326688 100644 --- a/bson/bsonrw/extjson_parser_test.go +++ b/bson/bsonrw/extjson_parser_test.go @@ -7,6 +7,7 @@ package bsonrw import ( + "errors" "io" "strings" "testing" @@ -47,7 +48,7 @@ type readKeyValueTestCase struct { func expectSpecificError(expected error) expectedErrorFunc { return func(t *testing.T, err error, desc string) { - if err != expected { + if !errors.Is(err, expected) { t.Helper() t.Errorf("%s: Expected %v but got: %v", desc, expected, err) t.FailNow() diff --git a/bson/bsonrw/extjson_reader.go b/bson/bsonrw/extjson_reader.go index 2aca37a91f..59ddfc4485 100644 --- a/bson/bsonrw/extjson_reader.go +++ b/bson/bsonrw/extjson_reader.go @@ -7,6 +7,7 @@ package bsonrw import ( + "errors" "fmt" "io" "sync" @@ -613,7 +614,7 @@ func (ejvr *extJSONValueReader) ReadElement() (string, ValueReader, error) { name, t, err := ejvr.p.readKey() if err != nil { - if err == ErrEOD { + if errors.Is(err, ErrEOD) { if ejvr.stack[ejvr.frame].mode == mCodeWithScope { _, err := ejvr.p.peekType() if err != nil { @@ -640,7 +641,7 @@ func (ejvr *extJSONValueReader) ReadValue() (ValueReader, error) { t, err := ejvr.p.peekType() if err != nil { - if err == ErrEOA { + if errors.Is(err, ErrEOA) { ejvr.pop() } diff --git a/bson/bsonrw/json_scanner.go b/bson/bsonrw/json_scanner.go index cd4843a3a4..65a812ac18 100644 --- a/bson/bsonrw/json_scanner.go +++ b/bson/bsonrw/json_scanner.go @@ -58,7 +58,7 @@ func (js *jsonScanner) nextToken() (*jsonToken, error) { c, err = js.readNextByte() } - if err == io.EOF { + if errors.Is(err, io.EOF) { return &jsonToken{t: jttEOF}, nil } else if err != nil { return nil, err @@ -198,7 +198,7 @@ func (js *jsonScanner) scanString() (*jsonToken, error) { for { c, err = js.readNextByte() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil, errors.New("end of input in JSON string") } return nil, err @@ -209,7 +209,7 @@ func (js *jsonScanner) scanString() (*jsonToken, error) { case '\\': c, err = js.readNextByte() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil, errors.New("end of input in JSON string") } return nil, err @@ -248,7 +248,7 @@ func (js *jsonScanner) scanString() (*jsonToken, error) { if utf16.IsSurrogate(rn) { c, err = js.readNextByte() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil, errors.New("end of input in JSON string") } return nil, err @@ -264,7 +264,7 @@ func (js *jsonScanner) scanString() (*jsonToken, error) { c, err = js.readNextByte() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil, errors.New("end of input in JSON string") } return nil, err @@ -384,7 +384,7 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { for { c, err = js.readNextByte() - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return nil, err } diff --git a/bson/bsonrw/value_reader_test.go b/bson/bsonrw/value_reader_test.go index 1716eb54c4..11b257277e 100644 --- a/bson/bsonrw/value_reader_test.go +++ b/bson/bsonrw/value_reader_test.go @@ -8,6 +8,7 @@ package bsonrw import ( "bytes" + "errors" "fmt" "io" "math" @@ -185,7 +186,7 @@ func TestValueReader(t *testing.T) { // invalid length vr.d = []byte{0x00, 0x00} _, err := vr.ReadDocument() - if err != io.EOF { + if !errors.Is(err, io.EOF) { t.Errorf("Expected io.EOF with document length too small. got %v; want %v", err, io.EOF) } @@ -239,7 +240,7 @@ func TestValueReader(t *testing.T) { vr.frame-- _, err = vr.ReadDocument() - if err != io.EOF { + if !errors.Is(err, io.EOF) { t.Errorf("Should return error when attempting to read length with not enough bytes. got %v; want %v", err, io.EOF) } }) @@ -1482,7 +1483,7 @@ func TestValueReader(t *testing.T) { frame: 0, } gotType, got, gotErr := vr.ReadValueBytes(nil) - if gotErr != tc.wantErr { + if !errors.Is(gotErr, tc.wantErr) { t.Errorf("Did not receive expected error. got %v; want %v", gotErr, tc.wantErr) } if tc.wantErr == nil && gotType != tc.wantType { diff --git a/bson/decoder_test.go b/bson/decoder_test.go index c91f4e0491..c4476dddab 100644 --- a/bson/decoder_test.go +++ b/bson/decoder_test.go @@ -279,7 +279,7 @@ func TestDecoderv2(t *testing.T) { var got *D err = dec.Decode(got) - if err != ErrDecodeToNil { + if !errors.Is(err, ErrDecodeToNil) { t.Fatalf("Decode error mismatch; expected %v, got %v", ErrDecodeToNil, err) } }) diff --git a/bson/primitive_codecs_test.go b/bson/primitive_codecs_test.go index 466f135e83..35e7ba9a91 100644 --- a/bson/primitive_codecs_test.go +++ b/bson/primitive_codecs_test.go @@ -28,7 +28,7 @@ import ( func bytesFromDoc(doc interface{}) []byte { b, err := Marshal(doc) if err != nil { - panic(fmt.Errorf("Couldn't marshal BSON document: %v", err)) + panic(fmt.Errorf("Couldn't marshal BSON document: %w", err)) } return b } @@ -471,7 +471,7 @@ func TestDefaultValueEncoders(t *testing.T) { enc, err := NewEncoder(vw) noerr(t, err) err = enc.Encode(tc.value) - if err != tc.err { + if !errors.Is(err, tc.err) { t.Errorf("Did not receive expected error. got %v; want %v", err, tc.err) } if diff := cmp.Diff([]byte(b), tc.b); diff != "" { diff --git a/bson/raw_test.go b/bson/raw_test.go index 02c9f63136..644a2eea16 100644 --- a/bson/raw_test.go +++ b/bson/raw_test.go @@ -9,6 +9,7 @@ package bson import ( "bytes" "encoding/binary" + "errors" "fmt" "io" "strings" @@ -52,7 +53,7 @@ func TestRaw(t *testing.T) { r := make(Raw, 5) binary.LittleEndian.PutUint32(r[0:4], 200) got := r.Validate() - if got != want { + if !errors.Is(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -62,7 +63,7 @@ func TestRaw(t *testing.T) { binary.LittleEndian.PutUint32(r[0:4], 8) r[4], r[5], r[6], r[7] = '\x02', 'f', 'o', 'o' got := r.Validate() - if got != want { + if !errors.Is(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) @@ -72,7 +73,7 @@ func TestRaw(t *testing.T) { binary.LittleEndian.PutUint32(r[0:4], 9) r[4], r[5], r[6], r[7], r[8] = '\x0A', 'f', 'o', 'o', '\x00' got := r.Validate() - if got != want { + if !errors.Is(got, want) { t.Errorf("Did not get expected error. got %v; want %v", got, want) } }) diff --git a/examples/documentation_examples/examples.go b/examples/documentation_examples/examples.go index c8248b3d19..8da21a6209 100644 --- a/examples/documentation_examples/examples.go +++ b/examples/documentation_examples/examples.go @@ -8,6 +8,7 @@ package documentation_examples import ( "context" + "errors" "fmt" "io/ioutil" logger "log" @@ -1816,7 +1817,8 @@ func RunTransactionWithRetry(sctx mongo.SessionContext, txnFn func(mongo.Session log.Println("Transaction aborted. Caught exception during transaction.") // If transient error, retry the whole transaction - if cmdErr, ok := err.(mongo.CommandError); ok && cmdErr.HasErrorLabel("TransientTransactionError") { + var cmdErr mongo.CommandError + if errors.As(err, &cmdErr) && cmdErr.HasErrorLabel("TransientTransactionError") { log.Println("TransientTransactionError, retrying transaction...") continue } @@ -1883,7 +1885,8 @@ func TransactionsExamples(ctx context.Context, client *mongo.Client) error { log.Println("Transaction aborted. Caught exception during transaction.") // If transient error, retry the whole transaction - if cmdErr, ok := err.(mongo.CommandError); ok && cmdErr.HasErrorLabel("TransientTransactionError") { + var cmdErr mongo.CommandError + if errors.As(err, &cmdErr) && cmdErr.HasErrorLabel("TransientTransactionError") { log.Println("TransientTransactionError, retrying transaction...") continue } diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 03d42814f4..2250286e4a 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -183,7 +183,7 @@ func selectLogSink(sink LogSink) (LogSink, *os.File, error) { if path != "" { logFile, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666) if err != nil { - return nil, nil, fmt.Errorf("unable to open log file: %v", err) + return nil, nil, fmt.Errorf("unable to open log file: %w", err) } return NewIOSink(logFile), logFile, nil diff --git a/mongo/bulk_write.go b/mongo/bulk_write.go index 42d286ea7d..a7efd551e7 100644 --- a/mongo/bulk_write.go +++ b/mongo/bulk_write.go @@ -8,6 +8,7 @@ package mongo import ( "context" + "errors" "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/bson/primitive" @@ -108,8 +109,8 @@ func (bw *bulkWrite) runBatch(ctx context.Context, batch bulkWriteBatch) (BulkWr case *InsertOneModel: res, err := bw.runInsert(ctx, batch) if err != nil { - writeErr, ok := err.(driver.WriteCommandError) - if !ok { + var writeErr driver.WriteCommandError + if !errors.As(err, &writeErr) { return BulkWriteResult{}, batchErr, err } writeErrors = writeErr.WriteErrors @@ -120,8 +121,8 @@ func (bw *bulkWrite) runBatch(ctx context.Context, batch bulkWriteBatch) (BulkWr case *DeleteOneModel, *DeleteManyModel: res, err := bw.runDelete(ctx, batch) if err != nil { - writeErr, ok := err.(driver.WriteCommandError) - if !ok { + var writeErr driver.WriteCommandError + if !errors.As(err, &writeErr) { return BulkWriteResult{}, batchErr, err } writeErrors = writeErr.WriteErrors @@ -132,8 +133,8 @@ func (bw *bulkWrite) runBatch(ctx context.Context, batch bulkWriteBatch) (BulkWr case *ReplaceOneModel, *UpdateOneModel, *UpdateManyModel: res, err := bw.runUpdate(ctx, batch) if err != nil { - writeErr, ok := err.(driver.WriteCommandError) - if !ok { + var writeErr driver.WriteCommandError + if !errors.As(err, &writeErr) { return BulkWriteResult{}, batchErr, err } writeErrors = writeErr.WriteErrors diff --git a/mongo/change_stream.go b/mongo/change_stream.go index b7e16f99aa..ca0b5fa3b8 100644 --- a/mongo/change_stream.go +++ b/mongo/change_stream.go @@ -738,8 +738,8 @@ func (cs *ChangeStream) loopNext(ctx context.Context, nonBlocking bool) { } func (cs *ChangeStream) isResumableError() bool { - commandErr, ok := cs.err.(CommandError) - if !ok || commandErr.HasErrorLabel(networkErrorLabel) { + var commandErr CommandError + if !errors.As(cs.err, &commandErr) || commandErr.HasErrorLabel(networkErrorLabel) { // All non-server errors or network errors are resumable. return true } diff --git a/mongo/client.go b/mongo/client.go index 56641179d0..0afbec29d8 100644 --- a/mongo/client.go +++ b/mongo/client.go @@ -576,7 +576,7 @@ func (c *Client) newMongoCrypt(opts *options.AutoEncryptionOptions) (*mongocrypt kmsProviders, err := marshal(opts.KmsProviders, c.bsonOpts, c.registry) if err != nil { - return nil, fmt.Errorf("error creating KMS providers document: %v", err) + return nil, fmt.Errorf("error creating KMS providers document: %w", err) } // Set the crypt_shared library override path from the "cryptSharedLibPath" extra option if one diff --git a/mongo/client_encryption.go b/mongo/client_encryption.go index c03afc8e67..9d291e8728 100644 --- a/mongo/client_encryption.go +++ b/mongo/client_encryption.go @@ -64,7 +64,7 @@ func NewClientEncryption(keyVaultClient *Client, opts ...*options.ClientEncrypti kmsProviders, err := marshal(ceo.KmsProviders, nil, nil) if err != nil { - return nil, fmt.Errorf("error creating KMS providers map: %v", err) + return nil, fmt.Errorf("error creating KMS providers map: %w", err) } mc, err := mongocrypt.NewMongoCrypt(mcopts.MongoCrypt(). diff --git a/mongo/collection.go b/mongo/collection.go index 55db6692df..8d7fd288cc 100644 --- a/mongo/collection.go +++ b/mongo/collection.go @@ -370,8 +370,8 @@ func (coll *Collection) insert(ctx context.Context, documents []interface{}, op = op.Retry(retry) err = op.Execute(ctx) - wce, ok := err.(driver.WriteCommandError) - if !ok { + var wce driver.WriteCommandError + if !errors.As(err, &wce) { return result, err } @@ -465,8 +465,8 @@ func (coll *Collection) InsertMany(ctx context.Context, documents interface{}, } imResult := &InsertManyResult{InsertedIDs: result} - writeException, ok := err.(WriteException) - if !ok { + var writeException WriteException + if !errors.As(err, &writeException) { return imResult, err } @@ -2200,7 +2200,7 @@ func (coll *Collection) Drop(ctx context.Context, opts ...*options.DropCollectio func (coll *Collection) dropEncryptedCollection(ctx context.Context, ef interface{}) error { efBSON, err := marshal(ef, coll.bsonOpts, coll.registry) if err != nil { - return fmt.Errorf("error transforming document: %v", err) + return fmt.Errorf("error transforming document: %w", err) } // Drop the two encryption-related, associated collections: `escCollection` and `ecocCollection`. diff --git a/mongo/integration/mtest/proxy_dialer.go b/mongo/integration/mtest/proxy_dialer.go index b50f37488a..c8e9e6d456 100644 --- a/mongo/integration/mtest/proxy_dialer.go +++ b/mongo/integration/mtest/proxy_dialer.go @@ -51,7 +51,7 @@ func newProxyDialer() *proxyDialer { } func newProxyErrorWithWireMsg(wm []byte, err error) error { - return fmt.Errorf("proxy error for wiremessage %v: %v", wm, err) + return fmt.Errorf("proxy error for wiremessage %v: %w", wm, err) } // DialContext creates a new proxyConnection. @@ -149,7 +149,7 @@ type proxyConn struct { // server. func (pc *proxyConn) Write(wm []byte) (n int, err error) { if err := pc.dialer.storeSentMessage(wm); err != nil { - wrapped := fmt.Errorf("error storing sent message: %v", err) + wrapped := fmt.Errorf("error storing sent message: %w", err) return 0, newProxyErrorWithWireMsg(wm, wrapped) } @@ -178,7 +178,7 @@ func (pc *proxyConn) Read(buffer []byte) (int, error) { wm = bsoncore.UpdateLength(wm, idx, int32(len(wm[idx:]))) if err := pc.dialer.storeReceivedMessage(wm, pc.RemoteAddr().String()); err != nil { - wrapped := fmt.Errorf("error storing received message: %v", err) + wrapped := fmt.Errorf("error storing received message: %w", err) return 0, newProxyErrorWithWireMsg(wm, wrapped) } diff --git a/mongo/integration/mtest/received_message.go b/mongo/integration/mtest/received_message.go index 3df507e5a5..2e2f952242 100644 --- a/mongo/integration/mtest/received_message.go +++ b/mongo/integration/mtest/received_message.go @@ -49,7 +49,7 @@ func parseReceivedMessage(wm []byte) (*ReceivedMessage, error) { } received, err := parseFn(remaining) if err != nil { - return nil, fmt.Errorf("error parsing wiremessage with opcode %s: %v", opcode, err) + return nil, fmt.Errorf("error parsing wiremessage with opcode %s: %w", opcode, err) } received.ResponseTo = responseTo @@ -97,7 +97,7 @@ func parseReceivedOpMsg(wm []byte) (*ReceivedMessage, error) { } if wm, err = assertMsgSectionType(wm, wiremessage.SingleDocument); err != nil { - return nil, fmt.Errorf("error verifying section type for response document: %v", err) + return nil, fmt.Errorf("error verifying section type for response document: %w", err) } response, wm, ok := wiremessage.ReadMsgSectionSingleDocument(wm) diff --git a/mongo/integration/mtest/sent_message.go b/mongo/integration/mtest/sent_message.go index 6b96e061bc..94eed12257 100644 --- a/mongo/integration/mtest/sent_message.go +++ b/mongo/integration/mtest/sent_message.go @@ -124,7 +124,7 @@ func parseSentMessage(wm []byte) (*SentMessage, error) { } sent, err := parseFn(remaining) if err != nil { - return nil, fmt.Errorf("error parsing wiremessage with opcode %s: %v", opcode, err) + return nil, fmt.Errorf("error parsing wiremessage with opcode %s: %w", opcode, err) } sent.RequestID = requestID @@ -142,7 +142,7 @@ func parseSentOpMsg(wm []byte) (*SentMessage, error) { } if wm, err = assertMsgSectionType(wm, wiremessage.SingleDocument); err != nil { - return nil, fmt.Errorf("error verifying section type for command document: %v", err) + return nil, fmt.Errorf("error verifying section type for command document: %w", err) } var commandDoc bsoncore.Document @@ -160,7 +160,7 @@ func parseSentOpMsg(wm []byte) (*SentMessage, error) { if len(wm) != 0 { // If there are bytes remaining in the wire message, they must correspond to a DocumentSequence section. if wm, err = assertMsgSectionType(wm, wiremessage.DocumentSequence); err != nil { - return nil, fmt.Errorf("error verifying section type for document sequence: %v", err) + return nil, fmt.Errorf("error verifying section type for document sequence: %w", err) } var data []byte diff --git a/mongo/integration/mtest/setup.go b/mongo/integration/mtest/setup.go index de5525f2dc..0c0ab21dbe 100644 --- a/mongo/integration/mtest/setup.go +++ b/mongo/integration/mtest/setup.go @@ -91,13 +91,13 @@ func Setup(setupOpts ...*SetupOptions) error { var err error uri, err = integtest.MongoDBURI() if err != nil { - return fmt.Errorf("error getting uri: %v", err) + return fmt.Errorf("error getting uri: %w", err) } } testContext.connString, err = connstring.ParseAndValidate(uri) if err != nil { - return fmt.Errorf("error parsing and validating connstring: %v", err) + return fmt.Errorf("error parsing and validating connstring: %w", err) } testContext.dataLake = os.Getenv("ATLAS_DATA_LAKE_INTEGRATION_TEST") == "true" @@ -108,20 +108,20 @@ func Setup(setupOpts ...*SetupOptions) error { cfg, err := topology.NewConfig(clientOpts, nil) if err != nil { - return fmt.Errorf("error constructing topology config: %v", err) + return fmt.Errorf("error constructing topology config: %w", err) } testContext.topo, err = topology.New(cfg) if err != nil { - return fmt.Errorf("error creating topology: %v", err) + return fmt.Errorf("error creating topology: %w", err) } if err = testContext.topo.Connect(); err != nil { - return fmt.Errorf("error connecting topology: %v", err) + return fmt.Errorf("error connecting topology: %w", err) } testContext.client, err = setupClient(options.Client().ApplyURI(uri)) if err != nil { - return fmt.Errorf("error connecting test client: %v", err) + return fmt.Errorf("error connecting test client: %w", err) } pingCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) diff --git a/x/bsonx/bsoncore/array_test.go b/x/bsonx/bsoncore/array_test.go index 8249d82808..4171adade7 100644 --- a/x/bsonx/bsoncore/array_test.go +++ b/x/bsonx/bsoncore/array_test.go @@ -115,7 +115,7 @@ func TestArray(t *testing.T) { t.Run("Out of bounds", func(t *testing.T) { rdr := Array{0xe, 0x0, 0x0, 0x0, 0xa, '0', 0x0, 0xa, '1', 0x0, 0xa, 0x7a, 0x0, 0x0} _, err := rdr.IndexErr(3) - if err != ErrOutOfBounds { + if !errors.Is(err, ErrOutOfBounds) { t.Errorf("Out of bounds should be returned when accessing element beyond end of Array. got %v; want %v", err, ErrOutOfBounds) } }) diff --git a/x/bsonx/bsoncore/document_sequence_test.go b/x/bsonx/bsoncore/document_sequence_test.go index c9a395d4f2..bf40fa878d 100644 --- a/x/bsonx/bsoncore/document_sequence_test.go +++ b/x/bsonx/bsoncore/document_sequence_test.go @@ -8,6 +8,7 @@ package bsoncore import ( "bytes" + "errors" "io" "strconv" "testing" @@ -113,7 +114,7 @@ func TestDocumentSequence(t *testing.T) { if !cmp.Equal(documents, tc.documents) { t.Errorf("Documents do not match. got %v; want %v", documents, tc.documents) } - if err != tc.err { + if !errors.Is(err, tc.err) { t.Errorf("Errors do not match. got %v; want %v", err, tc.err) } }) @@ -224,7 +225,7 @@ func TestDocumentSequence(t *testing.T) { if !bytes.Equal(document, tc.document) { t.Errorf("Documents do not match. got %v; want %v", document, tc.document) } - if err != tc.err { + if !errors.Is(err, tc.err) { t.Errorf("Errors do not match. got %v; want %v", err, tc.err) } }) @@ -275,7 +276,7 @@ func TestDocumentSequence(t *testing.T) { var docs []Document for { doc, err := ds.Next() - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if err != nil { diff --git a/x/bsonx/bsoncore/document_test.go b/x/bsonx/bsoncore/document_test.go index 0d77b79d30..a5609e689e 100644 --- a/x/bsonx/bsoncore/document_test.go +++ b/x/bsonx/bsoncore/document_test.go @@ -9,6 +9,7 @@ package bsoncore import ( "bytes" "encoding/binary" + "errors" "fmt" "io" "testing" @@ -113,7 +114,7 @@ func TestDocument(t *testing.T) { t.Run("empty-key", func(t *testing.T) { rdr := Document{'\x05', '\x00', '\x00', '\x00', '\x00'} _, err := rdr.LookupErr() - if err != ErrEmptyKey { + if !errors.Is(err, ErrEmptyKey) { t.Errorf("Empty key lookup did not return expected result. got %v; want %v", err, ErrEmptyKey) } }) @@ -206,7 +207,7 @@ func TestDocument(t *testing.T) { }) t.Run("LookupErr", func(t *testing.T) { got, err := tc.r.LookupErr(tc.key...) - if err != tc.err { + if !errors.Is(err, tc.err) { t.Errorf("Returned error does not match. got %v; want %v", err, tc.err) } if !cmp.Equal(got, tc.want) { @@ -220,7 +221,7 @@ func TestDocument(t *testing.T) { t.Run("Out of bounds", func(t *testing.T) { rdr := Document{0xe, 0x0, 0x0, 0x0, 0xa, 0x78, 0x0, 0xa, 0x79, 0x0, 0xa, 0x7a, 0x0, 0x0} _, err := rdr.IndexErr(3) - if err != ErrOutOfBounds { + if !errors.Is(err, ErrOutOfBounds) { t.Errorf("Out of bounds should be returned when accessing element beyond end of document. got %v; want %v", err, ErrOutOfBounds) } }) diff --git a/x/mongo/driver/batch_cursor.go b/x/mongo/driver/batch_cursor.go index 7d3703f7be..827e536137 100644 --- a/x/mongo/driver/batch_cursor.go +++ b/x/mongo/driver/batch_cursor.go @@ -451,7 +451,8 @@ func (bc *BatchCursor) getMore(ctx context.Context) { // If we're in load balanced mode and the pinned connection encounters a network error, we should not use it for // future commands. Per the spec, the connection will not be unpinned until the cursor is actually closed, but // we set the cursor ID to 0 to ensure the Close() call will not execute a killCursors command. - if driverErr, ok := bc.err.(Error); ok && driverErr.NetworkError() && bc.connection != nil { + var driverErr Error + if errors.As(bc.err, &driverErr) && driverErr.NetworkError() && bc.connection != nil { bc.id = 0 } diff --git a/x/mongo/driver/ocsp/cache_test.go b/x/mongo/driver/ocsp/cache_test.go index 8558191f15..047b749969 100644 --- a/x/mongo/driver/ocsp/cache_test.go +++ b/x/mongo/driver/ocsp/cache_test.go @@ -34,8 +34,8 @@ func TestCache(t *testing.T) { err := Verify(ctx, tls.ConnectionState{}, &VerifyOptions{}) assert.NotNil(t, err, "expected error, got nil") - ocspErr, ok := err.(*Error) - assert.True(t, ok, "expected error of type %T, got %v of type %T", &Error{}, err, err) + var ocspErr *Error + assert.True(t, errors.As(err, &ocspErr), "expected error of type %T, got %v of type %T", &Error{}, err, err) expected := &Error{ wrapped: errors.New("no OCSP cache provided"), } diff --git a/x/mongo/driver/ocsp/config.go b/x/mongo/driver/ocsp/config.go index 94a5dd775f..5b720cd590 100644 --- a/x/mongo/driver/ocsp/config.go +++ b/x/mongo/driver/ocsp/config.go @@ -61,7 +61,7 @@ func newConfig(certChain []*x509.Certificate, opts *VerifyOptions) (config, erro } cfg.ocspRequest, err = ocsp.ParseRequest(cfg.ocspRequestBytes) if err != nil { - return cfg, fmt.Errorf("error parsing OCSP request bytes: %v", err) + return cfg, fmt.Errorf("error parsing OCSP request bytes: %w", err) } return cfg, nil diff --git a/x/mongo/driver/ocsp/ocsp.go b/x/mongo/driver/ocsp/ocsp.go index 849530fde9..8700728729 100644 --- a/x/mongo/driver/ocsp/ocsp.go +++ b/x/mongo/driver/ocsp/ocsp.go @@ -161,10 +161,10 @@ func processStaple(cfg config, staple []byte) (*ResponseDetails, error) { // If the stapled response could not be parsed correctly, error. This can happen if the response is malformed, // the response does not cover the certificate presented by the server, or if the response contains an error // status. - return nil, fmt.Errorf("error parsing stapled response: %v", err) + return nil, fmt.Errorf("error parsing stapled response: %w", err) } if err = verifyResponse(cfg, parsedResponse); err != nil { - return nil, fmt.Errorf("error validating stapled response: %v", err) + return nil, fmt.Errorf("error validating stapled response: %w", err) } return extractResponseDetails(parsedResponse), nil @@ -192,7 +192,7 @@ func isMustStapleCertificate(cert *x509.Certificate) (bool, error) { // Use []*big.Int to ensure that all values in the sequence can be successfully unmarshalled. var featureValues []*big.Int if _, err := asn1.Unmarshal(featureExtension.Value, &featureValues); err != nil { - return false, fmt.Errorf("error unmarshalling TLS feature extension values: %v", err) + return false, fmt.Errorf("error unmarshalling TLS feature extension values: %w", err) } for _, value := range featureValues { diff --git a/x/mongo/driver/operation.go b/x/mongo/driver/operation.go index 63745ecefe..b1f0bce873 100644 --- a/x/mongo/driver/operation.go +++ b/x/mongo/driver/operation.go @@ -125,7 +125,8 @@ type finishedInformation struct { // write errors are included since the actual command did succeed, only writes // failed. func (info finishedInformation) success() bool { - if _, ok := info.cmdErr.(WriteCommandError); ok { + var writeCmdErr WriteCommandError + if errors.As(info.cmdErr, &writeCmdErr) { return true } @@ -1475,7 +1476,7 @@ func (op Operation) addWriteConcern(dst []byte, desc description.SelectedServer) } t, data, err := wc.MarshalBSONValue() - if err == writeconcern.ErrEmptyWriteConcern { + if errors.Is(err, writeconcern.ErrEmptyWriteConcern) { return dst, nil } if err != nil { diff --git a/x/mongo/driver/topology/errors.go b/x/mongo/driver/topology/errors.go index 7ce41864e6..a6630aae76 100644 --- a/x/mongo/driver/topology/errors.go +++ b/x/mongo/driver/topology/errors.go @@ -8,6 +8,7 @@ package topology import ( "context" + "errors" "fmt" "time" @@ -86,9 +87,9 @@ type pinnedConnections struct { // Error implements the error interface. func (w WaitQueueTimeoutError) Error() string { errorMsg := "timed out while checking out a connection from connection pool" - switch w.Wrapped { - case nil: - case context.Canceled: + switch { + case w.Wrapped == nil: + case errors.Is(w.Wrapped, context.Canceled): errorMsg = fmt.Sprintf( "%s: %s", "canceled while checking out a connection from connection pool", From 9380bef48cb28e96b00adb8e7aa8d7284937603a Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Fri, 1 Dec 2023 07:25:25 -0600 Subject: [PATCH 3/5] GODRIVER-2960 [master] Improve Evergreen Runtime and Usability (#1481) --- .evergreen/config.yml | 151 ++++++++++++++++------------- .evergreen/run-mongodb-aws-test.sh | 2 +- Makefile | 2 +- etc/run-atlas-test.sh | 2 +- 4 files changed, 89 insertions(+), 68 deletions(-) diff --git a/.evergreen/config.yml b/.evergreen/config.yml index 253d31a095..2bdb6ce8ac 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -166,7 +166,7 @@ functions: . ${DRIVERS_TOOLS}/.evergreen/venv-utils.sh . ${DRIVERS_TOOLS}/.evergreen/find-python3.sh - export PYTHON3_BINARY="$(find_python3)" + export PYTHON3_BINARY="$(find_python3 2>/dev/null)" venvcreate "$PYTHON3_BINARY" venv echo "PYTHON3_BINARY: $PYTHON3_BINARY" >>expansion.yml @@ -175,7 +175,11 @@ functions: params: file: src/go.mongodb.org/mongo-driver/expansion.yml - upload-mo-artifacts: + handle-test-artifacts: + - command: gotest.parse_files + params: + files: + - "src/go.mongodb.org/mongo-driver/*.suite" - command: shell.exec params: shell: "bash" @@ -196,12 +200,31 @@ functions: params: aws_key: ${aws_key} aws_secret: ${aws_secret} + optional: true local_file: ${PROJECT_DIRECTORY}/fuzz.tgz remote_file: ${UPLOAD_BUCKET}/${build_variant}/${revision}/${version_id}/${build_id}/${task_id}-${execution}-fuzz.tgz bucket: mciuploads permissions: public-read content_type: application/x-gzip display_name: "fuzz.tgz" + - command: shell.exec + params: + shell: "bash" + working_dir: src/go.mongodb.org/mongo-driver + script: | + ${PREPARE_SHELL} + find . -name \*.suite | xargs tar czf test_suite.tgz + - command: s3.put + params: + aws_key: ${aws_key} + aws_secret: ${aws_secret} + local_file: src/go.mongodb.org/mongo-driver/test_suite.tgz + optional: true + remote_file: ${UPLOAD_BUCKET}/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-test_suite.tgz + bucket: mciuploads + permissions: public-read + content_type: ${content_type|text/plain} + display_name: "test_suite.tgz" bootstrap-mongohoused: - command: shell.exec @@ -263,15 +286,26 @@ functions: params: shell: "bash" script: | - ${PREPARE_SHELL} - cd "$MONGO_ORCHESTRATION_HOME" - # source the mongo-orchestration virtualenv if it exists - if [ -f venv/bin/activate ]; then - . venv/bin/activate - elif [ -f venv/Scripts/activate ]; then - . venv/Scripts/activate + # Ensure the instance profile is reassigned for aws tests. + cd "${DRIVERS_TOOLS}/.evergreen/auth_aws" + if [ -f "./aws_e2e_setup.json" ]; then + . ./activate-authawsvenv.sh + python ./lib/aws_assign_instance_profile.py fi - mongo-orchestration stop + - command: shell.exec + params: + shell: "bash" + script: | + # Attempt to shut down a running load balancer. Ignore any errors that happen if the load + # balancer is not running. + DRIVERS_TOOLS=${DRIVERS_TOOLS} MONGODB_URI=${MONGODB_URI} bash ${DRIVERS_TOOLS}/.evergreen/run-load-balancer.sh stop || echo "Ignoring load balancer stop error" + - command: shell.exec + params: + shell: "bash" + script: | + ${PREPARE_SHELL} + # Stop orchestration and remove drivers tools. + bash ${DRIVERS_TOOLS}/.evergreen/stop-orchestration.sh cd - rm -rf $DRIVERS_TOOLS || true @@ -701,26 +735,6 @@ functions: TEST_INDEX_URI="${TEST_INDEX_URI}" \ make evg-test-search-index - stop-load-balancer: - - command: shell.exec - params: - shell: "bash" - script: | - # Attempt to shut down a running load balancer. Ignore any errors that happen if the load - # balancer is not running. - DRIVERS_TOOLS=${DRIVERS_TOOLS} MONGODB_URI=${MONGODB_URI} bash ${DRIVERS_TOOLS}/.evergreen/run-load-balancer.sh stop || echo "Ignoring load balancer stop error" - - teardown-aws: - - command: shell.exec - params: - shell: "bash" - script: | - cd "${DRIVERS_TOOLS}/.evergreen/auth_aws" - if [ -f "./aws_e2e_setup.json" ]; then - . ./activate-authawsvenv.sh - python ./lib/aws_assign_instance_profile.py - fi - add-aws-auth-variables-to-file: - command: ec2.assume_role params: @@ -901,17 +915,11 @@ functions: background: true script: | cd ${DRIVERS_TOOLS}/.evergreen/csfle - if [ "Windows_NT" = "$OS" ]; then - kmstlsvenv/Scripts/python.exe -u kms_kmip_server.py \ - --port 5698 \ - --ca_file "${PROJECT_DIRECTORY}/testdata/kmip-certs/ca-ec.pem" \ - --cert_file "${PROJECT_DIRECTORY}/testdata/kmip-certs/server-ec.pem" - else - ./kmstlsvenv/bin/python3 -u kms_kmip_server.py \ + . ./activate-kmstlsvenv.sh + python -u kms_kmip_server.py \ --port 5698 \ --ca_file "${PROJECT_DIRECTORY}/testdata/kmip-certs/ca-ec.pem" \ --cert_file "${PROJECT_DIRECTORY}/testdata/kmip-certs/server-ec.pem" - fi - command: shell.exec params: @@ -919,11 +927,8 @@ functions: background: true script: | cd ${DRIVERS_TOOLS}/.evergreen/csfle - if [ "Windows_NT" = "$OS" ]; then - kmstlsvenv/Scripts/python.exe bottle.py fake_azure:imds - else - ./kmstlsvenv/bin/python3 bottle.py fake_azure:imds - fi + . ./activate-kmstlsvenv.sh + python bottle.py fake_azure:imds - command: shell.exec params: @@ -1018,16 +1023,9 @@ pre: - func: windows-fix - func: fix-absolute-paths - func: make-files-executable - - func: start-cse-servers post: - - command: gotest.parse_files - params: - files: - - "src/go.mongodb.org/mongo-driver/*.suite" - - func: upload-mo-artifacts - - func: stop-load-balancer - - func: teardown-aws + - func: handle-test-artifacts - func: cleanup tasks: @@ -1061,6 +1059,7 @@ tasks: TOPOLOGY: "server" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1075,6 +1074,7 @@ tasks: TOPOLOGY: "server" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1090,6 +1090,7 @@ tasks: TOPOLOGY: "server" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1105,6 +1106,7 @@ tasks: TOPOLOGY: "server" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1120,6 +1122,7 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1134,6 +1137,7 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1148,6 +1152,7 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1163,6 +1168,7 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1178,6 +1184,7 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "server" @@ -1557,6 +1564,7 @@ tasks: TOPOLOGY: "replica_set" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1572,6 +1580,7 @@ tasks: TOPOLOGY: "replica_set" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1586,6 +1595,7 @@ tasks: TOPOLOGY: "replica_set" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1600,6 +1610,7 @@ tasks: TOPOLOGY: "replica_set" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1617,6 +1628,7 @@ tasks: TOPOLOGY: "replica_set" AUTH: "auth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1631,6 +1643,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1645,6 +1658,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1660,6 +1674,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1675,6 +1690,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "noauth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1690,6 +1706,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1704,6 +1721,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1719,6 +1737,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1734,6 +1753,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "auth" SSL: "ssl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1749,6 +1769,7 @@ tasks: TOPOLOGY: "sharded_cluster" AUTH: "auth" SSL: "nossl" + - func: start-cse-servers - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1820,6 +1841,7 @@ tasks: AUTH: "auth" SSL: "nossl" REQUIRE_API_VERSION: true + - func: start-cse-servers - func: run-versioned-api-test vars: TOPOLOGY: "server" @@ -1836,6 +1858,7 @@ tasks: AUTH: "noauth" SSL: "nossl" ORCHESTRATION_FILE: "versioned-api-testing.json" + - func: start-cse-servers - func: run-versioned-api-test vars: TOPOLOGY: "server" @@ -1909,6 +1932,7 @@ tasks: - name: "test-serverless" tags: ["serverless"] commands: + - func: start-cse-servers - func: "run-serverless-tests" vars: MONGO_GO_DRIVER_COMPRESSOR: "snappy" @@ -2345,20 +2369,8 @@ task_groups: SERVERLESS_API_PRIVATE_KEY=${SERVERLESS_API_PRIVATE_KEY} \ SERVERLESS_INSTANCE_NAME=${SERVERLESS_INSTANCE_NAME} \ bash ${DRIVERS_TOOLS}/.evergreen/serverless/delete-instance.sh - - command: gotest.parse_files - params: - files: - - "src/go.mongodb.org/mongo-driver/*.suite" - - command: s3.put - params: - aws_key: ${aws_key} - aws_secret: ${aws_secret} - local_file: mongodb-logs.tar.gz - remote_file: ${UPLOAD_BUCKET}/${build_variant}/${revision}/${version_id}/${build_id}/logs/${task_id}-${execution}-mongodb-logs.tar.gz - bucket: mciuploads - permissions: public-read - content_type: ${content_type|application/x-gzip} - display_name: "mongodb-logs.tar.gz" + - func: handle-test-artifacts + - func: cleanup tasks: - ".serverless" @@ -2395,8 +2407,11 @@ task_groups: export GCPKMS_ZONE=${GCPKMS_ZONE} export GCPKMS_INSTANCENAME=${GCPKMS_INSTANCENAME} $DRIVERS_TOOLS/.evergreen/csfle/gcpkms/delete-instance.sh + - func: handle-test-artifacts + - func: cleanup tasks: - testgcpkms-task + - name: testazurekms_task_group setup_group_can_fail_task: true teardown_group_can_fail_task: true @@ -2433,6 +2448,8 @@ task_groups: export AZUREKMS_SCOPE=${AZUREKMS_SCOPE} export AZUREKMS_RESOURCEGROUP=${AZUREKMS_RESOURCEGROUP} $DRIVERS_TOOLS/.evergreen/csfle/azurekms/delete-vm.sh + - func: handle-test-artifacts + - func: cleanup tasks: - testazurekms-task @@ -2464,6 +2481,8 @@ task_groups: AWS_REGION: us-east-1 args: - ${DRIVERS_TOOLS}/.evergreen/atlas/teardown-atlas-cluster.sh + - func: handle-test-artifacts + - func: cleanup setup_group_can_fail_task: true setup_group_timeout_secs: 1800 tasks: @@ -2502,6 +2521,8 @@ task_groups: add_expansions_to_env: true args: - ${DRIVERS_TOOLS}/.evergreen/atlas/teardown-atlas-cluster.sh + - func: handle-test-artifacts + - func: cleanup setup_group_can_fail_task: true setup_group_timeout_secs: 1800 tasks: diff --git a/.evergreen/run-mongodb-aws-test.sh b/.evergreen/run-mongodb-aws-test.sh index 3b213b249c..9d5c71376d 100644 --- a/.evergreen/run-mongodb-aws-test.sh +++ b/.evergreen/run-mongodb-aws-test.sh @@ -21,4 +21,4 @@ set -x # For Go 1.16+, Go builds requires a go.mod file in the current working directory or a parent # directory. Spawn a new subshell, "cd" to the project directory, then run "go run". -(cd ${PROJECT_DIRECTORY} && go run "./cmd/testaws/main.go") +(cd ${PROJECT_DIRECTORY} && go run "./cmd/testaws/main.go" | tee test.suite) diff --git a/Makefile b/Makefile index 3e818df3cb..3df4d42c73 100644 --- a/Makefile +++ b/Makefile @@ -196,7 +196,7 @@ build-kms-test: ### Benchmark specific targets and support. ### .PHONY: benchmark benchmark:perf - go test $(BUILD_TAGS) -benchmem -bench=. ./benchmark + go test $(BUILD_TAGS) -benchmem -bench=. ./benchmark | test benchmark.suite .PHONY: driver-benchmark driver-benchmark:perf diff --git a/etc/run-atlas-test.sh b/etc/run-atlas-test.sh index aa89b2dd4b..9a1839993f 100644 --- a/etc/run-atlas-test.sh +++ b/etc/run-atlas-test.sh @@ -8,4 +8,4 @@ set +x . etc/get_aws_secrets.sh drivers/atlas_connect echo "Running cmd/testatlas/main.go" -go run ./cmd/testatlas/main.go "$ATLAS_REPL" "$ATLAS_SHRD" "$ATLAS_FREE" "$ATLAS_TLS11" "$ATLAS_TLS12" "$ATLAS_SERVERLESS" "$ATLAS_SRV_REPL" "$ATLAS_SRV_SHRD" "$ATLAS_SRV_FREE" "$ATLAS_SRV_TLS11" "$ATLAS_SRV_TLS12" "$ATLAS_SRV_SERVERLESS" +go run ./cmd/testatlas/main.go "$ATLAS_REPL" "$ATLAS_SHRD" "$ATLAS_FREE" "$ATLAS_TLS11" "$ATLAS_TLS12" "$ATLAS_SERVERLESS" "$ATLAS_SRV_REPL" "$ATLAS_SRV_SHRD" "$ATLAS_SRV_FREE" "$ATLAS_SRV_TLS11" "$ATLAS_SRV_TLS12" "$ATLAS_SRV_SERVERLESS" | tee test.suite From ec2153b31e833a8ab8d207068da785a0e93396dd Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Mon, 4 Dec 2023 14:02:03 -0600 Subject: [PATCH 4/5] GODRIVER-3054 [master] Handshake connection should not use legacy for LB (#1487) Co-authored-by: Preston Vasquez --- Makefile | 1 + mongo/integration/client_test.go | 21 -------- mongo/integration/handshake_test.go | 51 +++++++++++++++++++ .../load-balancers/sdam-error-handling.json | 3 +- .../load-balancers/sdam-error-handling.yml | 2 +- x/mongo/driver/operation/hello.go | 10 ++-- 6 files changed, 60 insertions(+), 28 deletions(-) diff --git a/Makefile b/Makefile index 3df4d42c73..77df091002 100644 --- a/Makefile +++ b/Makefile @@ -148,6 +148,7 @@ evg-test-load-balancers: go test $(BUILD_TAGS) ./mongo/integration -run TestChangeStreamSpec -v -timeout $(TEST_TIMEOUT)s >> test.suite go test $(BUILD_TAGS) ./mongo/integration -run TestInitialDNSSeedlistDiscoverySpec/load_balanced -v -timeout $(TEST_TIMEOUT)s >> test.suite go test $(BUILD_TAGS) ./mongo/integration -run TestLoadBalancerSupport -v -timeout $(TEST_TIMEOUT)s >> test.suite + go test $(BUILD_TAGS) ./mongo/integration -run TestLoadBalancedConnectionHandshake -v -timeout $(TEST_TIMEOUT)s >> test.suite go test $(BUILD_TAGS) ./mongo/integration/unified -run TestUnifiedSpec -v -timeout $(TEST_TIMEOUT)s >> test.suite .PHONY: evg-test-search-index diff --git a/mongo/integration/client_test.go b/mongo/integration/client_test.go index af90b6b45e..dafea690d0 100644 --- a/mongo/integration/client_test.go +++ b/mongo/integration/client_test.go @@ -760,27 +760,6 @@ func TestClient(t *testing.T) { "expected 'OP_MSG' OpCode in wire message, got %q", pair.Sent.OpCode.String()) } }) - - // Test that OP_MSG is used for handshakes when loadBalanced is true. - opMsgLBOpts := mtest.NewOptions().ClientType(mtest.Proxy).MinServerVersion("5.0").Topologies(mtest.LoadBalanced) - mt.RunOpts("OP_MSG used for handshakes when loadBalanced is true", opMsgLBOpts, func(mt *mtest.T) { - err := mt.Client.Ping(context.Background(), mtest.PrimaryRp) - assert.Nil(mt, err, "Ping error: %v", err) - - msgPairs := mt.GetProxiedMessages() - assert.True(mt, len(msgPairs) >= 3, "expected at least 3 events, got %v", len(msgPairs)) - - // First three messages should be connection handshakes: one for the heartbeat connection, another for the - // application connection, and a final one for the RTT monitor connection. - for idx, pair := range msgPairs[:3] { - assert.Equal(mt, "hello", pair.CommandName, "expected command name 'hello' at index %d, got %s", idx, - pair.CommandName) - - // Assert that appended OpCode is OP_MSG when loadBalanced is true. - assert.Equal(mt, wiremessage.OpMsg, pair.Sent.OpCode, - "expected 'OP_MSG' OpCode in wire message, got %q", pair.Sent.OpCode.String()) - } - }) } func TestClient_BSONOptions(t *testing.T) { diff --git a/mongo/integration/handshake_test.go b/mongo/integration/handshake_test.go index fc1d25eba9..95de8536ab 100644 --- a/mongo/integration/handshake_test.go +++ b/mongo/integration/handshake_test.go @@ -20,6 +20,7 @@ import ( "go.mongodb.org/mongo-driver/mongo/integration/mtest" "go.mongodb.org/mongo-driver/version" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/wiremessage" ) func TestHandshakeProse(t *testing.T) { @@ -199,3 +200,53 @@ func TestHandshakeProse(t *testing.T) { }) } } + +func TestLoadBalancedConnectionHandshake(t *testing.T) { + mt := mtest.New(t) + + lbopts := mtest.NewOptions().ClientType(mtest.Proxy).Topologies( + mtest.LoadBalanced) + + mt.RunOpts("LB connection handshake uses OP_MSG", lbopts, func(mt *mtest.T) { + // Ping the server to ensure the handshake has completed. + err := mt.Client.Ping(context.Background(), nil) + require.NoError(mt, err, "Ping error: %v", err) + + messages := mt.GetProxiedMessages() + handshakeMessage := messages[:1][0] + + // Per the specifications, if loadBalanced=true, drivers MUST use the hello + // command for the initial handshake and use the OP_MSG protocol. + assert.Equal(mt, "hello", handshakeMessage.CommandName) + assert.Equal(mt, wiremessage.OpMsg, handshakeMessage.Sent.OpCode) + }) + + opts := mtest.NewOptions().ClientType(mtest.Proxy).Topologies( + mtest.ReplicaSet, + mtest.Sharded, + mtest.Single, + mtest.ShardedReplicaSet) + + mt.RunOpts("non-LB connection handshake uses OP_QUERY", opts, func(mt *mtest.T) { + // Ping the server to ensure the handshake has completed. + err := mt.Client.Ping(context.Background(), nil) + require.NoError(mt, err, "Ping error: %v", err) + + messages := mt.GetProxiedMessages() + handshakeMessage := messages[:1][0] + + want := wiremessage.OpQuery + + hello := handshake.LegacyHello + if os.Getenv("REQUIRE_API_VERSION") == "true" { + hello = "hello" + + // If the server API version is requested, then we should use OP_MSG + // regardless of the topology + want = wiremessage.OpMsg + } + + assert.Equal(mt, hello, handshakeMessage.CommandName) + assert.Equal(mt, want, handshakeMessage.Sent.OpCode) + }) +} diff --git a/testdata/load-balancers/sdam-error-handling.json b/testdata/load-balancers/sdam-error-handling.json index c0f114cdfb..b9a11f2527 100644 --- a/testdata/load-balancers/sdam-error-handling.json +++ b/testdata/load-balancers/sdam-error-handling.json @@ -279,7 +279,8 @@ }, "data": { "failCommands": [ - "isMaster" + "isMaster", + "hello" ], "closeConnection": true, "appName": "lbSDAMErrorTestClient" diff --git a/testdata/load-balancers/sdam-error-handling.yml b/testdata/load-balancers/sdam-error-handling.yml index 0e6c8993af..0f93b8a249 100644 --- a/testdata/load-balancers/sdam-error-handling.yml +++ b/testdata/load-balancers/sdam-error-handling.yml @@ -153,7 +153,7 @@ tests: configureFailPoint: failCommand mode: { times: 1 } data: - failCommands: [isMaster] + failCommands: [isMaster, hello] closeConnection: true appName: *singleClientAppName - name: insertOne diff --git a/x/mongo/driver/operation/hello.go b/x/mongo/driver/operation/hello.go index 6e750fd034..16f2ebf6c0 100644 --- a/x/mongo/driver/operation/hello.go +++ b/x/mongo/driver/operation/hello.go @@ -530,7 +530,7 @@ func (h *Hello) handshakeCommand(dst []byte, desc description.SelectedServer) ([ func (h *Hello) command(dst []byte, desc description.SelectedServer) ([]byte, error) { // Use "hello" if topology is LoadBalanced, API version is declared or server // has responded with "helloOk". Otherwise, use legacy hello. - if desc.Kind == description.LoadBalanced || h.serverAPI != nil || desc.Server.HelloOK { + if h.loadBalanced || h.serverAPI != nil || desc.Server.HelloOK { dst = bsoncore.AppendInt32Element(dst, "hello", 1) } else { dst = bsoncore.AppendInt32Element(dst, handshake.LegacyHello, 1) @@ -575,8 +575,8 @@ func (h *Hello) StreamResponse(ctx context.Context, conn driver.StreamerConnecti // loadBalanced is False. If this is the case, then the drivers MUST use legacy // hello for the first message of the initial handshake with the OP_QUERY // protocol -func isLegacyHandshake(srvAPI *driver.ServerAPIOptions, deployment driver.Deployment) bool { - return srvAPI == nil && deployment.Kind() != description.LoadBalanced +func isLegacyHandshake(srvAPI *driver.ServerAPIOptions, loadbalanced bool) bool { + return srvAPI == nil && !loadbalanced } func (h *Hello) createOperation() driver.Operation { @@ -592,7 +592,7 @@ func (h *Hello) createOperation() driver.Operation { ServerAPI: h.serverAPI, } - if isLegacyHandshake(h.serverAPI, h.d) { + if isLegacyHandshake(h.serverAPI, h.loadBalanced) { op.Legacy = driver.LegacyHandshake } @@ -616,7 +616,7 @@ func (h *Hello) GetHandshakeInformation(ctx context.Context, _ address.Address, ServerAPI: h.serverAPI, } - if isLegacyHandshake(h.serverAPI, deployment) { + if isLegacyHandshake(h.serverAPI, h.loadBalanced) { op.Legacy = driver.LegacyHandshake } From 5b711e821541d0f024c1d2c1033a08f2dd873714 Mon Sep 17 00:00:00 2001 From: Preston Vasquez Date: Tue, 5 Dec 2023 17:20:51 -0700 Subject: [PATCH 5/5] GODRIVER-979 Remove context parameter from Connect (#1464) --- README.md | 6 ++-- benchmark/multi.go | 4 +-- benchmark/operation_test.go | 6 ++-- benchmark/single.go | 10 +++--- cmd/testatlas/main.go | 2 +- cmd/testaws/main.go | 2 +- cmd/testentauth/main.go | 1 - cmd/testkms/main.go | 2 +- event/doc.go | 6 ++-- event/examples_test.go | 2 +- examples/_logger/logrus/main.go | 2 +- examples/_logger/zap/main.go | 2 +- examples/_logger/zerolog/main.go | 2 +- examples/documentation_examples/examples.go | 12 +++---- .../documentation_examples/examples_test.go | 2 +- internal/test/compilecheck/main.go | 3 +- mongo/client.go | 14 ++++----- mongo/client_examples_test.go | 31 +++++++------------ mongo/client_side_encryption_examples_test.go | 15 ++++----- mongo/client_test.go | 2 +- mongo/crud_examples_test.go | 4 +-- mongo/database_test.go | 2 +- mongo/doc.go | 2 +- mongo/gridfs/bucket_test.go | 2 +- mongo/gridfs/gridfs_test.go | 2 +- mongo/integration/clam_prose_test.go | 4 +-- mongo/integration/client_options_test.go | 2 +- .../client_side_encryption_prose_test.go | 28 ++++++++--------- .../client_side_encryption_test.go | 14 ++++----- mongo/integration/client_test.go | 4 +-- mongo/integration/crud_helpers_test.go | 6 ++-- mongo/integration/csot_cse_prose_test.go | 4 +-- mongo/integration/csot_prose_test.go | 2 +- mongo/integration/errors_test.go | 2 +- .../initial_dns_seedlist_discovery_test.go | 2 +- mongo/integration/mtest/mongotest.go | 6 ++-- mongo/integration/mtest/setup.go | 2 +- .../sessions_mongocryptd_prose_test.go | 4 +-- mongo/integration/unified/admin_helpers.go | 2 +- mongo/integration/unified/client_entity.go | 2 +- mongo/integration/unified_spec_test.go | 2 +- mongo/mongocryptd.go | 4 +-- mongo/ocsp_test.go | 4 +-- mongo/options/example_test.go | 2 +- mongo/readpref/options_example_test.go | 6 ++-- mongo/with_transactions_test.go | 4 +-- .../writeconcern/writeconcern_example_test.go | 6 ++-- 47 files changed, 115 insertions(+), 135 deletions(-) diff --git a/README.md b/README.md index 8e932cd7f7..e42143c96e 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ import ( ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() -client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) +client, err := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017")) ``` Make sure to defer a call to `Disconnect` after instantiating your client: @@ -166,12 +166,12 @@ Compression can be enabled using the `compressors` parameter on the connection s ```go opts := options.Client().ApplyURI("mongodb://localhost:27017/?compressors=snappy,zlib,zstd") -client, _ := mongo.Connect(context.TODO(), opts) +client, _ := mongo.Connect(opts) ``` ```go opts := options.Client().SetCompressors([]string{"snappy", "zlib", "zstd"}) -client, _ := mongo.Connect(context.TODO(), opts) +client, _ := mongo.Connect(opts) ``` If compressors are set, the Go Driver negotiates with the server to select the first common compressor. For server configuration and defaults, refer to [`networkMessageCompressors`](https://www.mongodb.com/docs/manual/reference/program/mongod/#std-option-mongod.--networkMessageCompressors). diff --git a/benchmark/multi.go b/benchmark/multi.go index e003420718..103522ee6d 100644 --- a/benchmark/multi.go +++ b/benchmark/multi.go @@ -17,7 +17,7 @@ func MultiFindMany(ctx context.Context, tm TimerManager, iters int) error { ctx, cancel := context.WithCancel(ctx) defer cancel() - db, err := getClientDB(ctx) + db, err := getClientDB() if err != nil { return err } @@ -83,7 +83,7 @@ func multiInsertCase(ctx context.Context, tm TimerManager, iters int, data strin ctx, cancel := context.WithCancel(ctx) defer cancel() - db, err := getClientDB(ctx) + db, err := getClientDB() if err != nil { return err } diff --git a/benchmark/operation_test.go b/benchmark/operation_test.go index d53f75c994..3e555500e2 100644 --- a/benchmark/operation_test.go +++ b/benchmark/operation_test.go @@ -32,7 +32,7 @@ func BenchmarkClientWrite(b *testing.B) { } for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { - client, err := mongo.Connect(context.Background(), bm.opt) + client, err := mongo.Connect(bm.opt) if err != nil { b.Fatalf("error creating client: %v", err) } @@ -71,7 +71,7 @@ func BenchmarkClientBulkWrite(b *testing.B) { } for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { - client, err := mongo.Connect(context.Background(), bm.opt) + client, err := mongo.Connect(bm.opt) if err != nil { b.Fatalf("error creating client: %v", err) } @@ -115,7 +115,7 @@ func BenchmarkClientRead(b *testing.B) { } for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { - client, err := mongo.Connect(context.Background(), bm.opt) + client, err := mongo.Connect(bm.opt) if err != nil { b.Fatalf("error creating client: %v", err) } diff --git a/benchmark/single.go b/benchmark/single.go index d8366e34f6..2cd00bd0ae 100644 --- a/benchmark/single.go +++ b/benchmark/single.go @@ -24,12 +24,12 @@ const ( largeData = "large_doc.json" ) -func getClientDB(ctx context.Context) (*mongo.Database, error) { +func getClientDB() (*mongo.Database, error) { cs, err := integtest.GetConnString() if err != nil { return nil, err } - client, err := mongo.Connect(ctx, options.Client().ApplyURI(cs.String())) + client, err := mongo.Connect(options.Client().ApplyURI(cs.String())) if err != nil { return nil, err } @@ -42,7 +42,7 @@ func SingleRunCommand(ctx context.Context, tm TimerManager, iters int) error { ctx, cancel := context.WithCancel(ctx) defer cancel() - db, err := getClientDB(ctx) + db, err := getClientDB() if err != nil { return err } @@ -75,7 +75,7 @@ func SingleFindOneByID(ctx context.Context, tm TimerManager, iters int) error { ctx, cancel := context.WithCancel(ctx) defer cancel() - db, err := getClientDB(ctx) + db, err := getClientDB() if err != nil { return err } @@ -123,7 +123,7 @@ func singleInsertCase(ctx context.Context, tm TimerManager, iters int, data stri ctx, cancel := context.WithCancel(ctx) defer cancel() - db, err := getClientDB(ctx) + db, err := getClientDB() if err != nil { return err } diff --git a/cmd/testatlas/main.go b/cmd/testatlas/main.go index ae1b15fcbc..1bf2f8faff 100644 --- a/cmd/testatlas/main.go +++ b/cmd/testatlas/main.go @@ -51,7 +51,7 @@ func main() { } func runTest(ctx context.Context, clientOpts *options.ClientOptions) error { - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { return fmt.Errorf("Connect error: %w", err) } diff --git a/cmd/testaws/main.go b/cmd/testaws/main.go index ec4a1c91c3..4bdf50c340 100644 --- a/cmd/testaws/main.go +++ b/cmd/testaws/main.go @@ -21,7 +21,7 @@ func main() { uri := os.Getenv("MONGODB_URI") ctx := context.Background() - client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) + client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(fmt.Sprintf("Connect error: %v", err)) } diff --git a/cmd/testentauth/main.go b/cmd/testentauth/main.go index 9bcea33294..bcb2e6a427 100644 --- a/cmd/testentauth/main.go +++ b/cmd/testentauth/main.go @@ -22,7 +22,6 @@ func main() { compressor := os.Getenv("MONGO_GO_DRIVER_COMPRESSOR") client, err := mongo.Connect( - context.Background(), options.Client().ApplyURI(uri).SetCompressors([]string{compressor})) if err != nil { log.Fatalf("Error connecting client: %v", err) diff --git a/cmd/testkms/main.go b/cmd/testkms/main.go index bc8f6b6dfe..2151201d33 100644 --- a/cmd/testkms/main.go +++ b/cmd/testkms/main.go @@ -83,7 +83,7 @@ func main() { } cOpts := options.Client().ApplyURI(uri) - keyVaultClient, err := mongo.Connect(context.Background(), cOpts) + keyVaultClient, err := mongo.Connect(cOpts) if err != nil { panic(fmt.Sprintf("Connect error: %v", err)) } diff --git a/event/doc.go b/event/doc.go index 239340130f..9bade98cf7 100644 --- a/event/doc.go +++ b/event/doc.go @@ -21,7 +21,7 @@ // }, // } // clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetMonitor(cmdMonitor) -// client, err := mongo.Connect(context.Background(), clientOpts) +// client, err := mongo.Connect( clientOpts) // // Monitoring the connection pool requires specifying a PoolMonitor when constructing // a mongo.Client. The following code tracks the number of checked out connections: @@ -38,7 +38,7 @@ // }, // } // clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetPoolMonitor(poolMonitor) -// client, err := mongo.Connect(context.Background(), clientOpts) +// client, err := mongo.Connect( clientOpts) // // Monitoring server changes specifying a ServerMonitor object when constructing // a mongo.Client. Different functions can be set on the ServerMonitor to @@ -52,5 +52,5 @@ // } // } // clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetServerMonitor(svrMonitor) -// client, err := mongo.Connect(context.Background(), clientOpts) +// client, err := mongo.Connect( clientOpts) package event diff --git a/event/examples_test.go b/event/examples_test.go index 5041006568..7c151d2a9e 100644 --- a/event/examples_test.go +++ b/event/examples_test.go @@ -47,7 +47,7 @@ func ExampleCommandMonitor() { }, } clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetMonitor(cmdMonitor) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } diff --git a/examples/_logger/logrus/main.go b/examples/_logger/logrus/main.go index c75d72ccc2..7ef12c124c 100644 --- a/examples/_logger/logrus/main.go +++ b/examples/_logger/logrus/main.go @@ -39,7 +39,7 @@ func main() { ApplyURI("mongodb://localhost:27017"). SetLoggerOptions(loggerOptions) - client, err := mongo.Connect(context.TODO(), clientOptions) + client, err := mongo.Connect(clientOptions) if err != nil { log.Fatalf("error connecting to MongoDB: %v", err) } diff --git a/examples/_logger/zap/main.go b/examples/_logger/zap/main.go index ff061413f4..d7424e2e15 100644 --- a/examples/_logger/zap/main.go +++ b/examples/_logger/zap/main.go @@ -39,7 +39,7 @@ func main() { ApplyURI("mongodb://localhost:27017"). SetLoggerOptions(loggerOptions) - client, err := mongo.Connect(context.TODO(), clientOptions) + client, err := mongo.Connect(clientOptions) if err != nil { log.Fatalf("error connecting to MongoDB: %v", err) } diff --git a/examples/_logger/zerolog/main.go b/examples/_logger/zerolog/main.go index 58efe415b1..1e01f49437 100644 --- a/examples/_logger/zerolog/main.go +++ b/examples/_logger/zerolog/main.go @@ -36,7 +36,7 @@ func main() { ApplyURI("mongodb://localhost:27017"). SetLoggerOptions(loggerOptions) - client, err := mongo.Connect(context.TODO(), clientOptions) + client, err := mongo.Connect(clientOptions) if err != nil { log.Fatalf("error connecting to MongoDB: %v", err) } diff --git a/examples/documentation_examples/examples.go b/examples/documentation_examples/examples.go index 8da21a6209..eb0c4de066 100644 --- a/examples/documentation_examples/examples.go +++ b/examples/documentation_examples/examples.go @@ -1966,7 +1966,7 @@ func WithTransactionExample(ctx context.Context) error { uri := mtest.ClusterURI() clientOpts := options.Client().ApplyURI(uri) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { return err } @@ -2781,7 +2781,7 @@ func StableAPIExample() { serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1) clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { panic(err) } @@ -2803,7 +2803,7 @@ func StableAPIStrictExample() { serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetStrict(true) clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { panic(err) } @@ -2825,7 +2825,7 @@ func StableAPINonStrictExample() { serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetStrict(false) clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { panic(err) } @@ -2848,7 +2848,7 @@ func StableAPIDeprecationErrorsExample() { serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetDeprecationErrors(true) clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { panic(err) } @@ -2869,7 +2869,7 @@ func StableAPIStrictCountExample(t *testing.T) { serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetStrict(true) clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions) - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(t, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(context.TODO()) }() diff --git a/examples/documentation_examples/examples_test.go b/examples/documentation_examples/examples_test.go index 141056f6da..429a9db58e 100644 --- a/examples/documentation_examples/examples_test.go +++ b/examples/documentation_examples/examples_test.go @@ -44,7 +44,7 @@ func TestDocumentationExamples(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(mtest.ClusterURI())) + client, err := mongo.Connect(options.Client().ApplyURI(mtest.ClusterURI())) assert.NoError(t, err) defer client.Disconnect(ctx) diff --git a/internal/test/compilecheck/main.go b/internal/test/compilecheck/main.go index 1678e64cde..cb35d6133d 100644 --- a/internal/test/compilecheck/main.go +++ b/internal/test/compilecheck/main.go @@ -7,7 +7,6 @@ package main import ( - "context" "fmt" "go.mongodb.org/mongo-driver/bson" @@ -16,6 +15,6 @@ import ( ) func main() { - _, _ = mongo.Connect(context.Background(), options.Client()) + _, _ = mongo.Connect(options.Client()) fmt.Println(bson.D{{Key: "key", Value: "value"}}) } diff --git a/mongo/client.go b/mongo/client.go index 0afbec29d8..fe6071cd75 100644 --- a/mongo/client.go +++ b/mongo/client.go @@ -102,12 +102,12 @@ type Client struct { // // The Client.Ping method can be used to verify that the deployment is successfully connected and the // Client was correctly configured. -func Connect(ctx context.Context, opts ...*options.ClientOptions) (*Client, error) { +func Connect(opts ...*options.ClientOptions) (*Client, error) { c, err := newClient(opts...) if err != nil { return nil, err } - err = c.connect(ctx) + err = c.connect() if err != nil { return nil, err } @@ -237,7 +237,7 @@ func newClient(opts ...*options.ClientOptions) (*Client, error) { // // Connect starts background goroutines to monitor the state of the deployment and does not do any I/O in the main // goroutine. The Client.Ping method can be used to verify that the connection was created successfully. -func (c *Client) connect(ctx context.Context) error { +func (c *Client) connect() error { if connector, ok := c.deployment.(driver.Connector); ok { err := connector.Connect() if err != nil { @@ -246,25 +246,25 @@ func (c *Client) connect(ctx context.Context) error { } if c.mongocryptdFLE != nil { - if err := c.mongocryptdFLE.connect(ctx); err != nil { + if err := c.mongocryptdFLE.connect(); err != nil { return err } } if c.internalClientFLE != nil { - if err := c.internalClientFLE.connect(ctx); err != nil { + if err := c.internalClientFLE.connect(); err != nil { return err } } if c.keyVaultClientFLE != nil && c.keyVaultClientFLE != c.internalClientFLE && c.keyVaultClientFLE != c { - if err := c.keyVaultClientFLE.connect(ctx); err != nil { + if err := c.keyVaultClientFLE.connect(); err != nil { return err } } if c.metadataClientFLE != nil && c.metadataClientFLE != c.internalClientFLE && c.metadataClientFLE != c { - if err := c.metadataClientFLE.connect(ctx); err != nil { + if err := c.metadataClientFLE.connect(); err != nil { return err } } diff --git a/mongo/client_examples_test.go b/mongo/client_examples_test.go index 4123e8e0e4..e6654ba84d 100644 --- a/mongo/client_examples_test.go +++ b/mongo/client_examples_test.go @@ -21,7 +21,6 @@ func ExampleClient() { // Create a Client and execute a ListDatabases operation. client, err := mongo.Connect( - context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { log.Fatal(err) @@ -45,7 +44,7 @@ func ExampleConnect_ping() { // server is running. clientOpts := options.Client().ApplyURI("mongodb://localhost:27017") - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -74,7 +73,7 @@ func ExampleConnect_replicaSet() { clientOpts := options.Client().ApplyURI( "mongodb://localhost:27017,localhost:27018/?replicaSet=replset") - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -88,7 +87,7 @@ func ExampleConnect_sharded() { clientOpts := options.Client().ApplyURI( "mongodb://localhost:27017,localhost:27018") - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -106,7 +105,7 @@ func ExampleConnect_sRV() { // requires driver version 1.1.0 or higher. clientOpts := options.Client().ApplyURI("mongodb+srv://mongodb.example.com") - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -120,7 +119,7 @@ func ExampleConnect_direct() { clientOpts := options.Client().ApplyURI( "mongodb://localhost:27017/?connect=direct") - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -143,7 +142,7 @@ func ExampleConnect_sCRAM() { } clientOpts := options.Client().ApplyURI("mongodb://localhost:27017"). SetAuth(credential) - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -179,7 +178,7 @@ func ExampleConnect_x509() { } clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -204,7 +203,7 @@ func ExampleConnect_pLAIN() { clientOpts := options.Client().ApplyURI("mongodb://localhost:27017"). SetAuth(credential) - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -239,7 +238,7 @@ func ExampleConnect_kerberos() { uri := "mongo-server.example.com:27017" clientOpts := options.Client().ApplyURI(uri).SetAuth(credential) - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { log.Fatal(err) } @@ -289,7 +288,6 @@ func ExampleConnect_aWS() { Password: secretAccessKey, } awsIAMClient, err := mongo.Connect( - context.TODO(), options.Client().SetAuth(awsCredential)) if err != nil { panic(err) @@ -311,7 +309,6 @@ func ExampleConnect_aWS() { }, } assumeRoleClient, err := mongo.Connect( - context.TODO(), options.Client().SetAuth(assumeRoleCredential)) if err != nil { panic(err) @@ -333,7 +330,6 @@ func ExampleConnect_aWS() { AuthMechanism: "MONGODB-AWS", } envVariablesClient, err := mongo.Connect( - context.TODO(), options.Client().SetAuth(envVariablesCredential)) if err != nil { panic(err) @@ -350,9 +346,7 @@ func ExampleConnect_aWS() { ecCredential := options.Credential{ AuthMechanism: "MONGODB-AWS", } - ecClient, err := mongo.Connect( - context.TODO(), - options.Client().SetAuth(ecCredential)) + ecClient, err := mongo.Connect(options.Client().SetAuth(ecCredential)) if err != nil { panic(err) } @@ -382,7 +376,6 @@ func ExampleConnect_stableAPI() { // is a constant equal to "1". serverAPI := options.ServerAPI(options.ServerAPIVersion1) serverAPIClient, err := mongo.Connect( - context.TODO(), options.Client().SetServerAPIOptions(serverAPI)) if err != nil { panic(err) @@ -397,7 +390,6 @@ func ExampleConnect_stableAPI() { serverAPIStrict := options.ServerAPI(options.ServerAPIVersion1). SetStrict(true) serverAPIStrictClient, err := mongo.Connect( - context.TODO(), options.Client().SetServerAPIOptions(serverAPIStrict)) if err != nil { panic(err) @@ -416,7 +408,6 @@ func ExampleConnect_stableAPI() { serverAPIDeprecation := options.ServerAPI(options.ServerAPIVersion1). SetDeprecationErrors(true) serverAPIDeprecationClient, err := mongo.Connect( - context.TODO(), options.Client().SetServerAPIOptions(serverAPIDeprecation)) if err != nil { panic(err) @@ -442,7 +433,7 @@ func ExampleConnect_bSONOptions() { ApplyURI("mongodb://localhost:27017"). SetBSONOptions(bsonOpts) - client, err := mongo.Connect(context.TODO(), clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { panic(err) } diff --git a/mongo/client_side_encryption_examples_test.go b/mongo/client_side_encryption_examples_test.go index 70243c4cc9..d2e6449fe4 100644 --- a/mongo/client_side_encryption_examples_test.go +++ b/mongo/client_side_encryption_examples_test.go @@ -39,7 +39,7 @@ func Example_clientSideEncryption() { clientOpts := options.Client(). ApplyURI(uri). SetAutoEncryptionOptions(autoEncryptionOpts) - client, err := Connect(context.TODO(), clientOpts) + client, err := Connect(clientOpts) if err != nil { log.Fatalf("Connect error: %v", err) } @@ -78,9 +78,7 @@ func Example_clientSideEncryptionCreateKey() { clientEncryptionOpts := options.ClientEncryption(). SetKeyVaultNamespace(keyVaultNamespace). SetKmsProviders(kmsProviders) - keyVaultClient, err := Connect( - context.TODO(), - options.Client().ApplyURI(uri)) + keyVaultClient, err := Connect(options.Client().ApplyURI(uri)) if err != nil { log.Fatalf("Connect error for keyVaultClient: %v", err) } @@ -142,7 +140,7 @@ func Example_clientSideEncryptionCreateKey() { clientOptions := options.Client(). ApplyURI(uri). SetAutoEncryptionOptions(autoEncryptionOpts) - client, err := Connect(context.TODO(), clientOptions) + client, err := Connect(clientOptions) if err != nil { log.Fatalf("Connect error for encrypted client: %v", err) } @@ -169,9 +167,8 @@ func Example_explictEncryption() { keyVaultNamespace := keyVaultDBName + "." + keyVaultCollName // The Client used to read/write application data. - client, err := Connect( - context.TODO(), - options.Client().ApplyURI("mongodb://localhost:27017")) + opts := options.Client().ApplyURI("mongodb://localhost:27017") + client, err := Connect(opts) if err != nil { panic(err) } @@ -294,7 +291,7 @@ func Example_explictEncryptionWithAutomaticDecryption() { clientOpts := options.Client(). ApplyURI("mongodb://localhost:27017"). SetAutoEncryptionOptions(autoEncryptionOpts) - client, err := Connect(context.TODO(), clientOpts) + client, err := Connect(clientOpts) if err != nil { panic(err) } diff --git a/mongo/client_test.go b/mongo/client_test.go index e90215108c..6046b5abc2 100644 --- a/mongo/client_test.go +++ b/mongo/client_test.go @@ -357,7 +357,7 @@ func TestClient(t *testing.T) { clientOpts := options.Client().ApplyURI(cs.Original).SetReadPreference(readpref.Primary()). SetWriteConcern(writeconcern.Majority()).SetMonitor(cmdMonitor) integtest.AddTestServerAPIVersion(clientOpts) - client, err := Connect(bgCtx, clientOpts) + client, err := Connect(clientOpts) assert.Nil(t, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(bgCtx) diff --git a/mongo/crud_examples_test.go b/mongo/crud_examples_test.go index e76d279139..f4b64a98ad 100644 --- a/mongo/crud_examples_test.go +++ b/mongo/crud_examples_test.go @@ -1080,7 +1080,7 @@ func ExampleCollection_Find_primitiveRegex() { clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") // Connect to a mongodb server. - client, err := mongo.Connect(ctx, clientOptions) + client, err := mongo.Connect(clientOptions) if err != nil { panic(err) } @@ -1121,7 +1121,7 @@ func ExampleCollection_Find_regex() { clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") // Connect to a mongodb server. - client, err := mongo.Connect(ctx, clientOptions) + client, err := mongo.Connect(clientOptions) if err != nil { panic(err) } diff --git a/mongo/database_test.go b/mongo/database_test.go index 745f533b73..fa2c603d9d 100644 --- a/mongo/database_test.go +++ b/mongo/database_test.go @@ -97,7 +97,7 @@ func TestDatabase(t *testing.T) { }) t.Run("TransientTransactionError label", func(t *testing.T) { client := setupClient(options.Client().ApplyURI("mongodb://nonexistent").SetServerSelectionTimeout(3 * time.Second)) - err := client.connect(bgCtx) + err := client.connect() defer func() { _ = client.Disconnect(bgCtx) }() assert.Nil(t, err, "expected nil, got %v", err) diff --git a/mongo/doc.go b/mongo/doc.go index e0a5d66ac2..8a037c7ed6 100644 --- a/mongo/doc.go +++ b/mongo/doc.go @@ -13,7 +13,7 @@ // // ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) // defer cancel() -// client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://foo:bar@localhost:27017")) +// client, err := mongo.Connect( options.Client().ApplyURI("mongodb://foo:bar@localhost:27017")) // if err != nil { return err } // // This will create a new client and start monitoring the MongoDB server on localhost. diff --git a/mongo/gridfs/bucket_test.go b/mongo/gridfs/bucket_test.go index 0bff0ed871..b0a50520fa 100644 --- a/mongo/gridfs/bucket_test.go +++ b/mongo/gridfs/bucket_test.go @@ -38,7 +38,7 @@ func TestBucket_openDownloadStream(t *testing.T) { cs := integtest.ConnString(t) clientOpts := options.Client().ApplyURI(cs.Original) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(t, err, "Connect error: %v", err) db := client.Database("bucket") diff --git a/mongo/gridfs/gridfs_test.go b/mongo/gridfs/gridfs_test.go index ea9d39efe4..b3af58518c 100644 --- a/mongo/gridfs/gridfs_test.go +++ b/mongo/gridfs/gridfs_test.go @@ -49,7 +49,7 @@ func TestGridFS(t *testing.T) { // will discover the other hosts during SDAM checks. SetHosts(cs.Hosts[:1]) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(t, err, "Connect error: %v", err) db := client.Database("gridfs") defer func() { diff --git a/mongo/integration/clam_prose_test.go b/mongo/integration/clam_prose_test.go index 3b0ad2cde1..52b2b85f1d 100644 --- a/mongo/integration/clam_prose_test.go +++ b/mongo/integration/clam_prose_test.go @@ -321,7 +321,7 @@ func TestCommandLoggingAndMonitoringProse(t *testing.T) { integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error in setup: %v", err) coll := mt.CreateCollection(mtest.Collection{ @@ -379,7 +379,7 @@ func TestCommandLoggingAndMonitoringProse(t *testing.T) { integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error: %v", err) coll := mt.CreateCollection(mtest.Collection{ diff --git a/mongo/integration/client_options_test.go b/mongo/integration/client_options_test.go index 43703d5e33..4287842149 100644 --- a/mongo/integration/client_options_test.go +++ b/mongo/integration/client_options_test.go @@ -24,7 +24,7 @@ func TestClientOptions_CustomDialer(t *testing.T) { cs := integtest.ConnString(t) opts := options.Client().ApplyURI(cs.String()).SetDialer(td) integtest.AddTestServerAPIVersion(opts) - client, err := mongo.Connect(context.Background(), opts) + client, err := mongo.Connect(opts) require.NoError(t, err) _, err = client.ListDatabases(context.Background(), bson.D{}) require.NoError(t, err) diff --git a/mongo/integration/client_side_encryption_prose_test.go b/mongo/integration/client_side_encryption_prose_test.go index 22dde7c896..46fceaab2c 100644 --- a/mongo/integration/client_side_encryption_prose_test.go +++ b/mongo/integration/client_side_encryption_prose_test.go @@ -1153,7 +1153,7 @@ func TestClientSideEncryptionProse(t *testing.T) { mcryptOpts := options.Client().ApplyURI("mongodb://localhost:27021"). SetServerSelectionTimeout(1 * time.Second) integtest.AddTestServerAPIVersion(mcryptOpts) - mcryptClient, err := mongo.Connect(context.Background(), mcryptOpts) + mcryptClient, err := mongo.Connect(mcryptOpts) assert.Nil(mt, err, "mongocryptd Connect error: %v", err) err = mcryptClient.Database("admin").RunCommand(context.Background(), bson.D{{handshake.LegacyHelloLowercase, 1}}).Err() @@ -1364,7 +1364,7 @@ func TestClientSideEncryptionProse(t *testing.T) { SetAutoEncryptionOptions(aeOpts) integtest.AddTestServerAPIVersion(ceOpts) - clientEncrypted, err := mongo.Connect(context.Background(), ceOpts) + clientEncrypted, err := mongo.Connect(ceOpts) assert.Nil(mt, err, "Connect error: %v", err) defer clientEncrypted.Disconnect(context.Background()) @@ -1682,7 +1682,7 @@ func TestClientSideEncryptionProse(t *testing.T) { assert.Nil(mt, err, "error on CreateCollection: %v", err) err = mt.Client.Database("keyvault").Collection("datakeys").Drop(context.Background()) assert.Nil(mt, err, "error on Drop: %v", err) - keyVaultClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI(mtest.ClusterURI())) + keyVaultClient, err := mongo.Connect(options.Client().ApplyURI(mtest.ClusterURI())) assert.Nil(mt, err, "error on Connect: %v", err) datakeysColl := keyVaultClient.Database("keyvault").Collection("datakeys", options.Collection().SetWriteConcern(mtest.MajorityWc)) _, err = datakeysColl.InsertOne(context.Background(), key1Document) @@ -1700,7 +1700,7 @@ func TestClientSideEncryptionProse(t *testing.T) { SetKmsProviders(fullKmsProvidersMap). SetBypassQueryAnalysis(true) co := options.Client().SetAutoEncryptionOptions(aeo).ApplyURI(mtest.ClusterURI()) - encryptedClient, err := mongo.Connect(context.Background(), co) + encryptedClient, err := mongo.Connect(co) assert.Nil(mt, err, "error on Connect: %v", err) return encryptedClient, clientEncryption } @@ -2036,7 +2036,7 @@ func TestClientSideEncryptionProse(t *testing.T) { var keyVaultClient *mongo.Client { co := options.Client().ApplyURI(mtest.ClusterURI()) - keyVaultClient, err = mongo.Connect(context.Background(), co) + keyVaultClient, err = mongo.Connect(co) defer keyVaultClient.Disconnect(context.Background()) integtest.AddTestServerAPIVersion(co) assert.Nil(mt, err, "error on Connect: %v", err) @@ -2078,7 +2078,7 @@ func TestClientSideEncryptionProse(t *testing.T) { var keyVaultClient *mongo.Client { co := options.Client().ApplyURI(mtest.ClusterURI()) - keyVaultClient, err = mongo.Connect(context.Background(), co) + keyVaultClient, err = mongo.Connect(co) defer keyVaultClient.Disconnect(context.Background()) integtest.AddTestServerAPIVersion(co) assert.Nil(mt, err, "error on Connect: %v", err) @@ -2128,7 +2128,7 @@ func TestClientSideEncryptionProse(t *testing.T) { var keyVaultClient *mongo.Client { co := options.Client().ApplyURI(mtest.ClusterURI()) - keyVaultClient, err = mongo.Connect(context.Background(), co) + keyVaultClient, err = mongo.Connect(co) defer keyVaultClient.Disconnect(context.Background()) integtest.AddTestServerAPIVersion(co) assert.Nil(mt, err, "error on Connect: %v", err) @@ -2271,7 +2271,7 @@ func TestClientSideEncryptionProse(t *testing.T) { SetExtraOptions(mongocryptdSpawnArgs) cliOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetAutoEncryptionOptions(aeo) integtest.AddTestServerAPIVersion(cliOpts) - encClient, err := mongo.Connect(context.Background(), cliOpts) + encClient, err := mongo.Connect(cliOpts) assert.Nil(mt, err, "Connect error: %v", err) defer func() { err = encClient.Disconnect(context.Background()) @@ -2291,7 +2291,7 @@ func TestClientSideEncryptionProse(t *testing.T) { mt.RunOpts("21. automatic data encryption keys", qeRunOpts, func(mt *mtest.T) { setup := func() (*mongo.Client, *mongo.ClientEncryption, error) { opts := options.Client().ApplyURI(mtest.ClusterURI()) - client, err := mongo.Connect(context.Background(), opts) + client, err := mongo.Connect(opts) if err != nil { return nil, nil, err } @@ -2603,7 +2603,7 @@ func TestClientSideEncryptionProse(t *testing.T) { assert.Nil(mt, err, "error on CreateCollection: %v", err) err = mt.Client.Database("keyvault").Collection("datakeys").Drop(context.Background()) assert.Nil(mt, err, "error on Drop: %v", err) - keyVaultClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI(mtest.ClusterURI())) + keyVaultClient, err := mongo.Connect(options.Client().ApplyURI(mtest.ClusterURI())) assert.Nil(mt, err, "error on Connect: %v", err) datakeysColl := keyVaultClient.Database("keyvault").Collection("datakeys", options.Collection().SetWriteConcern(mtest.MajorityWc)) _, err = datakeysColl.InsertOne(context.Background(), key1Document) @@ -2621,7 +2621,7 @@ func TestClientSideEncryptionProse(t *testing.T) { SetKmsProviders(fullKmsProvidersMap). SetBypassQueryAnalysis(true) co := options.Client().SetAutoEncryptionOptions(aeo).ApplyURI(mtest.ClusterURI()) - encryptedClient, err := mongo.Connect(context.Background(), co) + encryptedClient, err := mongo.Connect(co) assert.Nil(mt, err, "error on Connect: %v", err) // Insert 0, 6, 30, and 200. @@ -2956,12 +2956,12 @@ func setup(mt *mtest.T, aeo *options.AutoEncryptionOptions, kvClientOpts *option opts := options.Client().ApplyURI(mtest.ClusterURI()).SetWriteConcern(mtest.MajorityWc). SetReadPreference(mtest.PrimaryRp).SetAutoEncryptionOptions(aeo).SetMonitor(cseMonitor) integtest.AddTestServerAPIVersion(opts) - cpt.cseClient, err = mongo.Connect(context.Background(), opts) + cpt.cseClient, err = mongo.Connect(opts) assert.Nil(mt, err, "Connect error for encrypted client: %v", err) cpt.cseColl = cpt.cseClient.Database("db").Collection("coll") } if ceo != nil { - cpt.kvClient, err = mongo.Connect(context.Background(), kvClientOpts) + cpt.kvClient, err = mongo.Connect(kvClientOpts) assert.Nil(mt, err, "Connect error for ClientEncryption key vault client: %v", err) cpt.clientEnc, err = mongo.NewClientEncryption(cpt.kvClient, ceo) assert.Nil(mt, err, "NewClientEncryption error: %v", err) @@ -3029,7 +3029,7 @@ func newDeadlockTest(mt *mtest.T) *deadlockTest { clientTestOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetWriteConcern(mtest.MajorityWc) integtest.AddTestServerAPIVersion(clientTestOpts) - if d.clientTest, err = mongo.Connect(context.Background(), clientTestOpts); err != nil { + if d.clientTest, err = mongo.Connect(clientTestOpts); err != nil { mt.Fatalf("Connect error: %v", err) } diff --git a/mongo/integration/client_side_encryption_test.go b/mongo/integration/client_side_encryption_test.go index 928c3d12aa..5851080d32 100644 --- a/mongo/integration/client_side_encryption_test.go +++ b/mongo/integration/client_side_encryption_test.go @@ -43,7 +43,7 @@ func createDataKeyAndEncrypt(mt *mtest.T, keyName string) primitive.Binary { "local": {"key": localMasterKey}, } - kvClient, err := mongo.Connect(context.Background(), kvClientOpts) + kvClient, err := mongo.Connect(kvClientOpts) defer kvClient.Disconnect(context.Background()) assert.Nil(mt, err, "Connect error: %v", err) @@ -135,7 +135,7 @@ func TestClientSideEncryptionWithExplicitSessions(t *testing.T) { integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error: %v", err) defer client.Disconnect(context.Background()) @@ -197,7 +197,7 @@ func TestClientSideEncryptionWithExplicitSessions(t *testing.T) { integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error: %v", err) defer client.Disconnect(context.Background()) @@ -361,7 +361,7 @@ func TestClientSideEncryptionCustomCrypt(t *testing.T) { clientOpts.Crypt = cc integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) defer client.Disconnect(context.Background()) assert.Nil(mt, err, "Connect error: %v", err) @@ -506,7 +506,7 @@ func TestFLE2DocsExample(t *testing.T) { { cOpts := options.Client().ApplyURI(mtest.ClusterURI()) integtest.AddTestServerAPIVersion(cOpts) - keyVaultClient, err := mongo.Connect(context.Background(), cOpts) + keyVaultClient, err := mongo.Connect(cOpts) assert.Nil(mt, err, "error in Connect: %v", err) defer keyVaultClient.Disconnect(context.Background()) ceOpts := options.ClientEncryption().SetKmsProviders(kmsProvidersMap).SetKeyVaultNamespace("keyvault.datakeys") @@ -549,7 +549,7 @@ func TestFLE2DocsExample(t *testing.T) { integtest.AddTestServerAPIVersion(cOpts) aeOpts := options.AutoEncryption().SetKmsProviders(kmsProvidersMap).SetKeyVaultNamespace("keyvault.datakeys").SetEncryptedFieldsMap(encryptedFieldsMap).SetExtraOptions(getCryptSharedLibExtraOptions()) cOpts.SetAutoEncryptionOptions(aeOpts) - encryptedClient, err := mongo.Connect(context.Background(), cOpts) + encryptedClient, err := mongo.Connect(cOpts) defer encryptedClient.Disconnect(context.Background()) assert.Nil(mt, err, "error in Connect: %v", err) // Create the FLE 2 collection docsExample.encrypted. @@ -653,7 +653,7 @@ func TestFLE2CreateCollectionWithAutoEncryption(t *testing.T) { integtest.AddTestServerAPIVersion(cOpts) var err error - encryptedClient, err = mongo.Connect(context.Background(), cOpts) + encryptedClient, err = mongo.Connect(cOpts) defer encryptedClient.Disconnect(context.Background()) assert.Nil(mt, err, "error in Connect: %v", err) } diff --git a/mongo/integration/client_test.go b/mongo/integration/client_test.go index dafea690d0..c8ba161644 100644 --- a/mongo/integration/client_test.go +++ b/mongo/integration/client_test.go @@ -181,7 +181,7 @@ func TestClient(t *testing.T) { ) authClientOpts := options.Client().ApplyURI(cs) integtest.AddTestServerAPIVersion(authClientOpts) - authClient, err := mongo.Connect(context.Background(), authClientOpts) + authClient, err := mongo.Connect(authClientOpts) assert.Nil(mt, err, "authClient Connect error: %v", err) defer func() { _ = authClient.Disconnect(context.Background()) }() @@ -326,7 +326,7 @@ func TestClient(t *testing.T) { SetServerSelectionTimeout(100 * time.Millisecond).SetHosts([]string{"invalid:123"}). SetConnectTimeout(500 * time.Millisecond).SetSocketTimeout(500 * time.Millisecond) integtest.AddTestServerAPIVersion(invalidClientOpts) - client, err := mongo.Connect(context.Background(), invalidClientOpts) + client, err := mongo.Connect(invalidClientOpts) assert.Nil(mt, err, "Connect error: %v", err) err = client.Ping(context.Background(), readpref.Primary()) assert.NotNil(mt, err, "expected error for pinging invalid host, got nil") diff --git a/mongo/integration/crud_helpers_test.go b/mongo/integration/crud_helpers_test.go index c6a06e338e..5c5cc8c609 100644 --- a/mongo/integration/crud_helpers_test.go +++ b/mongo/integration/crud_helpers_test.go @@ -124,7 +124,7 @@ func runCommandOnAllServers(commandFn func(client *mongo.Client) error) error { integtest.AddTestServerAPIVersion(opts) if mtest.ClusterTopologyKind() != mtest.Sharded { - client, err := mongo.Connect(context.Background(), opts) + client, err := mongo.Connect(opts) if err != nil { return fmt.Errorf("error creating replica set client: %v", err) } @@ -134,7 +134,7 @@ func runCommandOnAllServers(commandFn func(client *mongo.Client) error) error { } for _, host := range opts.Hosts { - shardClient, err := mongo.Connect(context.Background(), opts.SetHosts([]string{host})) + shardClient, err := mongo.Connect(opts.SetHosts([]string{host})) if err != nil { return fmt.Errorf("error creating client for mongos %v: %v", host, err) } @@ -1386,7 +1386,7 @@ func executeAdminCommand(mt *mtest.T, op *operation) { // Per the streamable hello test format description, a separate client must be used to execute this operation. clientOpts := options.Client().ApplyURI(mtest.ClusterURI()) integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(context.Background()) diff --git a/mongo/integration/csot_cse_prose_test.go b/mongo/integration/csot_cse_prose_test.go index e3b30f5c3c..f0102e70f2 100644 --- a/mongo/integration/csot_cse_prose_test.go +++ b/mongo/integration/csot_cse_prose_test.go @@ -47,7 +47,7 @@ func TestCSOTClientSideEncryptionProse(t *testing.T) { SetExtraOptions(mongocryptdSpawnArgs) cliOpts := options.Client().ApplyURI(mtest.ClusterURI()).SetAutoEncryptionOptions(aeo) integtest.AddTestServerAPIVersion(cliOpts) - encClient, err := mongo.Connect(context.Background(), cliOpts) + encClient, err := mongo.Connect(cliOpts) assert.Nil(mt, err, "Connect error: %v", err) defer func() { err = encClient.Disconnect(context.Background()) @@ -70,7 +70,7 @@ func TestCSOTClientSideEncryptionProse(t *testing.T) { mcryptOpts := options.Client().SetMonitor(mcryptMonitor). ApplyURI("mongodb://localhost:23000/?timeoutMS=1000") integtest.AddTestServerAPIVersion(mcryptOpts) - mcryptClient, err := mongo.Connect(context.Background(), mcryptOpts) + mcryptClient, err := mongo.Connect(mcryptOpts) assert.Nil(mt, err, "mongocryptd Connect error: %v", err) defer func() { err = mcryptClient.Disconnect(context.Background()) diff --git a/mongo/integration/csot_prose_test.go b/mongo/integration/csot_prose_test.go index 4f9f112b3f..7d0d387f52 100644 --- a/mongo/integration/csot_prose_test.go +++ b/mongo/integration/csot_prose_test.go @@ -57,7 +57,7 @@ func TestCSOTProse(t *testing.T) { SetMonitor(cm). ApplyURI(mtest.ClusterURI()) integtest.AddTestServerAPIVersion(cliOptions) - cli, err := mongo.Connect(context.Background(), cliOptions) + cli, err := mongo.Connect(cliOptions) assert.Nil(mt, err, "Connect error: %v", err) // Insert 50 1MB documents (OP_MSG payloads can only fit 48MB in one batch). diff --git a/mongo/integration/errors_test.go b/mongo/integration/errors_test.go index ad2da491aa..7e976b0ce5 100644 --- a/mongo/integration/errors_test.go +++ b/mongo/integration/errors_test.go @@ -75,7 +75,7 @@ func TestErrors(t *testing.T) { clientOpts := options.Client().ApplyURI(mtest.ClusterURI()) integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(context.Background(), clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(context.Background()) }() diff --git a/mongo/integration/initial_dns_seedlist_discovery_test.go b/mongo/integration/initial_dns_seedlist_discovery_test.go index 92a20a721a..c17ee1e712 100644 --- a/mongo/integration/initial_dns_seedlist_discovery_test.go +++ b/mongo/integration/initial_dns_seedlist_discovery_test.go @@ -76,7 +76,7 @@ func runSeedlistDiscoveryDirectory(mt *mtest.T, subdirectory string) { func runSeedlistDiscoveryPingTest(mt *mtest.T, clientOpts *options.ClientOptions) { ctx := context.Background() - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) assert.Nil(mt, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(ctx) }() diff --git a/mongo/integration/mtest/mongotest.go b/mongo/integration/mtest/mongotest.go index faf99e1259..d58a1dd469 100644 --- a/mongo/integration/mtest/mongotest.go +++ b/mongo/integration/mtest/mongotest.go @@ -685,13 +685,13 @@ func (t *T) createTestClient() { // pin to first mongos pinnedHostList := []string{testContext.connString.Hosts[0]} uriOpts := options.Client().ApplyURI(testContext.connString.Original).SetHosts(pinnedHostList) - t.Client, err = mongo.Connect(context.Background(), uriOpts, clientOpts) + t.Client, err = mongo.Connect(uriOpts, clientOpts) case Mock: // clear pool monitor to avoid configuration error clientOpts.PoolMonitor = nil t.mockDeployment = newMockDeployment() clientOpts.Deployment = t.mockDeployment - t.Client, err = mongo.Connect(context.Background(), clientOpts) + t.Client, err = mongo.Connect(clientOpts) case Proxy: t.proxyDialer = newProxyDialer() clientOpts.SetDialer(t.proxyDialer) @@ -709,7 +709,7 @@ func (t *T) createTestClient() { } // Pass in uriOpts first so clientOpts wins if there are any conflicting settings. - t.Client, err = mongo.Connect(context.Background(), uriOpts, clientOpts) + t.Client, err = mongo.Connect(uriOpts, clientOpts) } if err != nil { t.Fatalf("error creating client: %v", err) diff --git a/mongo/integration/mtest/setup.go b/mongo/integration/mtest/setup.go index 0c0ab21dbe..1096ba474d 100644 --- a/mongo/integration/mtest/setup.go +++ b/mongo/integration/mtest/setup.go @@ -65,7 +65,7 @@ func setupClient(opts *options.ClientOptions) (*mongo.Client, error) { } // for sharded clusters, pin to one host. Due to how the cache is implemented on 4.0 and 4.2, behavior // can be inconsistent when multiple mongoses are used - return mongo.Connect(context.Background(), opts.SetWriteConcern(wcMajority).SetHosts(opts.Hosts[:1])) + return mongo.Connect(opts.SetWriteConcern(wcMajority).SetHosts(opts.Hosts[:1])) } // Setup initializes the current testing context. diff --git a/mongo/integration/sessions_mongocryptd_prose_test.go b/mongo/integration/sessions_mongocryptd_prose_test.go index fd516445df..891d08d81c 100644 --- a/mongo/integration/sessions_mongocryptd_prose_test.go +++ b/mongo/integration/sessions_mongocryptd_prose_test.go @@ -100,9 +100,7 @@ func newTestSessionMongocryptdProseClient(mt *mtest.T) *mongo.Client { ApplyURI(uri.String()). SetMonitor(cmdMonitor) - ctx := context.Background() - - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) require.NoError(mt, err, "could not connect to mongocryptd: %v", err) return client diff --git a/mongo/integration/unified/admin_helpers.go b/mongo/integration/unified/admin_helpers.go index 4dcabb9f85..ba8eac8d7d 100644 --- a/mongo/integration/unified/admin_helpers.go +++ b/mongo/integration/unified/admin_helpers.go @@ -86,7 +86,7 @@ func runCommandOnHost(ctx context.Context, host string, commandFn func(context.C SetHosts([]string{host}) integtest.AddTestServerAPIVersion(clientOpts) - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { return fmt.Errorf("error creating client to host %q: %v", host, err) } diff --git a/mongo/integration/unified/client_entity.go b/mongo/integration/unified/client_entity.go index 66e2e55987..38ed4ed4da 100644 --- a/mongo/integration/unified/client_entity.go +++ b/mongo/integration/unified/client_entity.go @@ -189,7 +189,7 @@ func newClientEntity(ctx context.Context, em *EntityMap, entityOptions *entityOp entity.ignoredCommands[cmd] = struct{}{} } - client, err := mongo.Connect(ctx, clientOpts) + client, err := mongo.Connect(clientOpts) if err != nil { return nil, fmt.Errorf("error creating mongo.Client: %w", err) } diff --git a/mongo/integration/unified_spec_test.go b/mongo/integration/unified_spec_test.go index 4da42e6a68..63563e98d5 100644 --- a/mongo/integration/unified_spec_test.go +++ b/mongo/integration/unified_spec_test.go @@ -467,7 +467,7 @@ func executeTestRunnerOperation(mt *mtest.T, testCase *testCase, op *operation, targetHost := clientSession.PinnedServer.Addr.String() opts := options.Client().ApplyURI(mtest.ClusterURI()).SetHosts([]string{targetHost}) integtest.AddTestServerAPIVersion(opts) - client, err := mongo.Connect(context.Background(), opts) + client, err := mongo.Connect(opts) if err != nil { return fmt.Errorf("Connect error for targeted client: %w", err) } diff --git a/mongo/mongocryptd.go b/mongo/mongocryptd.go index 7af7f3a8f0..efb283e208 100644 --- a/mongo/mongocryptd.go +++ b/mongo/mongocryptd.go @@ -113,8 +113,8 @@ func (mc *mongocryptdClient) markCommand(ctx context.Context, dbName string, cmd } // connect connects the underlying Client instance. This must be called before performing any mark operations. -func (mc *mongocryptdClient) connect(ctx context.Context) error { - return mc.client.connect(ctx) +func (mc *mongocryptdClient) connect() error { + return mc.client.connect() } // disconnect disconnects the underlying Client instance. This should be called after all operations have completed. diff --git a/mongo/ocsp_test.go b/mongo/ocsp_test.go index 55cd4e1d9b..d97706855f 100644 --- a/mongo/ocsp_test.go +++ b/mongo/ocsp_test.go @@ -32,7 +32,7 @@ func TestOCSP(t *testing.T) { t.Run("tls", func(t *testing.T) { clientOpts := createOCSPClientOptions(cs.Original) - client, err := Connect(bgCtx, clientOpts) + client, err := Connect(clientOpts) assert.Nil(t, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(bgCtx) }() @@ -47,7 +47,7 @@ func TestOCSP(t *testing.T) { }) t.Run("tlsInsecure", func(t *testing.T) { clientOpts := createInsecureOCSPClientOptions(cs.Original) - client, err := Connect(bgCtx, clientOpts) + client, err := Connect(clientOpts) assert.Nil(t, err, "Connect error: %v", err) defer func() { _ = client.Disconnect(bgCtx) }() diff --git a/mongo/options/example_test.go b/mongo/options/example_test.go index 1c5fbe4356..f3dc65d1f5 100644 --- a/mongo/options/example_test.go +++ b/mongo/options/example_test.go @@ -53,7 +53,7 @@ func ExampleClientOptions_SetLoggerOptions_customLogger() { ApplyURI("mongodb://localhost:27017"). SetLoggerOptions(loggerOptions) - client, err := mongo.Connect(context.TODO(), clientOptions) + client, err := mongo.Connect(clientOptions) if err != nil { log.Fatalf("error connecting to MongoDB: %v", err) diff --git a/mongo/readpref/options_example_test.go b/mongo/readpref/options_example_test.go index af4e220ae6..bdff555d34 100644 --- a/mongo/readpref/options_example_test.go +++ b/mongo/readpref/options_example_test.go @@ -7,8 +7,6 @@ package readpref_test import ( - "context" - "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" @@ -27,7 +25,7 @@ func ExampleWithTags() { ApplyURI("mongodb://localhost:27017"). SetReadPreference(rp) - _, err := mongo.Connect(context.Background(), opts) + _, err := mongo.Connect(opts) if err != nil { panic(err) } @@ -55,7 +53,7 @@ func ExampleWithTagSets() { ApplyURI("mongodb://localhost"). SetReadPreference(rp) - _, err := mongo.Connect(context.Background(), opts) + _, err := mongo.Connect(opts) if err != nil { panic(err) } diff --git a/mongo/with_transactions_test.go b/mongo/with_transactions_test.go index 24a253059d..24fa280e6f 100644 --- a/mongo/with_transactions_test.go +++ b/mongo/with_transactions_test.go @@ -576,7 +576,7 @@ func setupConvenientTransactions(t *testing.T, extraClientOpts ...*options.Clien fullClientOpts := []*options.ClientOptions{baseClientOpts} fullClientOpts = append(fullClientOpts, extraClientOpts...) - client, err := Connect(bgCtx, fullClientOpts...) + client, err := Connect(fullClientOpts...) assert.Nil(t, err, "Connect error: %v", err) version, err := getServerVersion(client.Database("admin")) @@ -593,7 +593,7 @@ func setupConvenientTransactions(t *testing.T, extraClientOpts ...*options.Clien // For sharded clusters, disconnect the previous Client and create a new one that's pinned to a single mongos. _ = client.Disconnect(bgCtx) fullClientOpts = append(fullClientOpts, options.Client().SetHosts([]string{cs.Hosts[0]})) - client, err = Connect(bgCtx, fullClientOpts...) + client, err = Connect(fullClientOpts...) assert.Nil(t, err, "Connect error: %v", err) return client } diff --git a/mongo/writeconcern/writeconcern_example_test.go b/mongo/writeconcern/writeconcern_example_test.go index dda4b15e9c..36208805f0 100644 --- a/mongo/writeconcern/writeconcern_example_test.go +++ b/mongo/writeconcern/writeconcern_example_test.go @@ -7,8 +7,6 @@ package writeconcern_test import ( - "context" - "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/writeconcern" @@ -23,7 +21,7 @@ func Example_majority() { ApplyURI("mongodb://localhost:27017"). SetWriteConcern(wc) - _, err := mongo.Connect(context.Background(), opts) + _, err := mongo.Connect(opts) if err != nil { panic(err) } @@ -41,7 +39,7 @@ func Example_w2Journaled() { ApplyURI("mongodb://localhost:27017"). SetWriteConcern(wc) - _, err := mongo.Connect(context.Background(), opts) + _, err := mongo.Connect(opts) if err != nil { panic(err) }