diff --git a/.evergreen/config.yml b/.evergreen/config.yml index 05832906d1..5e5fc0a519 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -570,6 +570,17 @@ functions: binary: bash args: ["${DRIVERS_TOOLS}/.evergreen/csfle/await-servers.sh"] + start-mongoproxy: + - command: ec2.assume_role # TODO: not sure this is needd + params: + role_arn: ${aws_test_secrets_role} + - command: subprocess.exec + params: + binary: bash + include_expansions_in_env: [AUTH, SSL, MONGODB_URI] + background: true + args: [*task-runner, start-mongoproxy] + run-kms-tls-test: - command: subprocess.exec type: test @@ -686,6 +697,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + - func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -701,12 +713,14 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" AUTH: "noauth" SSL: "nossl" MONGO_GO_DRIVER_COMPRESSOR: "snappy" + MONGO_PROXY_URI: "mongodb://127.0.0.1:28017/?directConnection=true" - name: test-standalone-noauth-nossl-zlib-compression tags: ["test", "standalone", "compression", "zlib"] @@ -717,6 +731,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -733,6 +748,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -748,7 +764,8 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "ssl" - - func: start-cse-servers + - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -764,6 +781,7 @@ tasks: AUTH: "auth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -779,6 +797,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -794,7 +813,8 @@ tasks: TOPOLOGY: "server" AUTH: "auth" SSL: "ssl" - - func: start-cse-servers + - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -811,6 +831,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "server" @@ -1231,6 +1252,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1247,6 +1269,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1262,6 +1285,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1277,6 +1301,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1295,6 +1320,7 @@ tasks: AUTH: "auth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "replica_set" @@ -1310,6 +1336,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1325,6 +1352,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1341,6 +1369,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1357,6 +1386,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1373,6 +1403,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1388,6 +1419,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1404,6 +1436,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1420,6 +1453,7 @@ tasks: AUTH: "auth" SSL: "ssl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1436,6 +1470,7 @@ tasks: AUTH: "auth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-tests vars: TOPOLOGY: "sharded_cluster" @@ -1507,6 +1542,7 @@ tasks: SSL: "nossl" REQUIRE_API_VERSION: true - func: start-cse-servers + #- func: start-mongoproxy - func: run-versioned-api-test vars: TOPOLOGY: "server" @@ -1524,6 +1560,7 @@ tasks: SSL: "nossl" REQUIRE_API_VERSION: true - func: start-cse-servers + #- func: start-mongoproxy - func: run-versioned-api-test vars: TOPOLOGY: "sharded_cluster" @@ -1541,6 +1578,7 @@ tasks: SSL: "nossl" ORCHESTRATION_FILE: "versioned-api-testing.json" - func: start-cse-servers + #- func: start-mongoproxy - func: run-versioned-api-test vars: TOPOLOGY: "server" @@ -1556,6 +1594,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-kms-tls-test vars: KMS_TLS_TESTCASE: "INVALID_CERT" @@ -1572,6 +1611,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-kms-tls-test vars: KMS_TLS_TESTCASE: "INVALID_HOSTNAME" @@ -1588,6 +1628,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-kmip-tests vars: TOPOLOGY: "server" @@ -1603,6 +1644,7 @@ tasks: AUTH: "noauth" SSL: "nossl" - func: start-cse-servers + #- func: start-mongoproxy - func: run-retry-kms-requests - name: "testgcpkms-task" diff --git a/.evergreen/run-task.sh b/.evergreen/run-task.sh index 564d937703..a5001f04b8 100755 --- a/.evergreen/run-task.sh +++ b/.evergreen/run-task.sh @@ -1,13 +1,13 @@ #!/usr/bin/env bash # # Source the env.sh file and run the given task -set -eu +set -exu -SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd) PROJECT_DIRECTORY=$(dirname $SCRIPT_DIR) -pushd ${PROJECT_DIRECTORY} > /dev/null +pushd ${PROJECT_DIRECTORY} >/dev/null source env.sh task "$@" -popd > /dev/null +popd >/dev/null diff --git a/.evergreen/setup-system.sh b/.evergreen/setup-system.sh index 542060fee4..83f00d1572 100755 --- a/.evergreen/setup-system.sh +++ b/.evergreen/setup-system.sh @@ -4,7 +4,7 @@ set -eu # Set up default environment variables. -SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd) PROJECT_DIRECTORY=$(dirname $SCRIPT_DIR) pushd $PROJECT_DIRECTORY ROOT_DIR=$(dirname $PROJECT_DIRECTORY) @@ -40,18 +40,19 @@ PATH="${GOROOT}/bin:${GOPATH}/bin:${MONGODB_BINARIES}:${EXTRA_PATH}:${PATH}" # Get the current unique version of this checkout. if [ "${IS_PATCH:-}" = "true" ]; then - CURRENT_VERSION=$(git describe)-patch-${VERSION_ID} + CURRENT_VERSION=$(git describe)-patch-${VERSION_ID} else - CURRENT_VERSION=latest + CURRENT_VERSION=latest fi # Ensure a checkout of drivers-tools. if [ ! -d "$DRIVERS_TOOLS" ]; then - git clone https://github.com/mongodb-labs/drivers-evergreen-tools $DRIVERS_TOOLS + #git clone https://github.com/mongodb-labs/drivers-evergreen-tools $DRIVERS_TOOLS + git clone -b DRIVERS-2884-mongoproxy https://github.com/prestonvasquez/drivers-evergreen-tools $DRIVERS_TOOLS fi # Write the .env file for drivers-tools. -cat < ${DRIVERS_TOOLS}/.env +cat <${DRIVERS_TOOLS}/.env SKIP_LEGACY_SHELL=1 DRIVERS_TOOLS="$DRIVERS_TOOLS" MONGO_ORCHESTRATION_HOME="$MONGO_ORCHESTRATION_HOME" @@ -67,7 +68,7 @@ go env go install github.com/go-task/task/v3/cmd/task@v3.39.1 # Write our own env file. -cat < env.sh +cat <env.sh export GOROOT="$GOROOT" export GOPATH="$GOPATH" export GOCACHE="$GOCACHE" @@ -78,12 +79,12 @@ export PATH="$PATH" EOT if [ "Windows_NT" = "$OS" ]; then - echo "export USERPROFILE=$USERPROFILE" >> env.sh - echo "export HOME=$HOME" >> env.sh + echo "export USERPROFILE=$USERPROFILE" >>env.sh + echo "export HOME=$HOME" >>env.sh fi # source the env.sh file and write the expansion file. -cat < expansion.yml +cat <expansion.yml CURRENT_VERSION: "$CURRENT_VERSION" DRIVERS_TOOLS: "$DRIVERS_TOOLS" PROJECT_DIRECTORY: "$PROJECT_DIRECTORY" diff --git a/Taskfile.yml b/Taskfile.yml index 3473cb4981..b25a76b61a 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -123,6 +123,8 @@ tasks: setup-encryption: bash etc/setup-encryption.sh + start-mongoproxy: bash etc/start-mongoproxy.sh + evg-test: - go test -exec "env PKG_CONFIG_PATH=${PKG_CONFIG_PATH} LD_LIBRARY_PATH=${LD_LIBRARY_PATH} DYLD_LIBRARY_PATH=$MACOS_LIBRARY_PATH}" ${BUILD_TAGS} -v -timeout {{.TEST_TIMEOUT}}s -p 1 ./... >> test.suite diff --git a/etc/start-mongoproxy.sh b/etc/start-mongoproxy.sh new file mode 100644 index 0000000000..ebfa66a348 --- /dev/null +++ b/etc/start-mongoproxy.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# +# Set up environment and write env.sh and expansion.yml files. +set -eux + +bash $DRIVERS_TOOLS/.evergreen/start-mongoproxy.sh diff --git a/event/monitoring.go b/event/monitoring.go index 2ca98969d7..6e2cefca2f 100644 --- a/event/monitoring.go +++ b/event/monitoring.go @@ -75,17 +75,20 @@ const ( // strings for pool command monitoring types const ( - ConnectionPoolCreated = "ConnectionPoolCreated" - ConnectionPoolReady = "ConnectionPoolReady" - ConnectionPoolCleared = "ConnectionPoolCleared" - ConnectionPoolClosed = "ConnectionPoolClosed" - ConnectionCreated = "ConnectionCreated" - ConnectionReady = "ConnectionReady" - ConnectionClosed = "ConnectionClosed" - ConnectionCheckOutStarted = "ConnectionCheckOutStarted" - ConnectionCheckOutFailed = "ConnectionCheckOutFailed" - ConnectionCheckedOut = "ConnectionCheckedOut" - ConnectionCheckedIn = "ConnectionCheckedIn" + ConnectionPoolCreated = "ConnectionPoolCreated" + ConnectionPoolReady = "ConnectionPoolReady" + ConnectionPoolCleared = "ConnectionPoolCleared" + ConnectionPoolClosed = "ConnectionPoolClosed" + ConnectionCreated = "ConnectionCreated" + ConnectionReady = "ConnectionReady" + ConnectionClosed = "ConnectionClosed" + ConnectionCheckOutStarted = "ConnectionCheckOutStarted" + ConnectionCheckOutFailed = "ConnectionCheckOutFailed" + ConnectionCheckedOut = "ConnectionCheckedOut" + ConnectionCheckedIn = "ConnectionCheckedIn" + ConnectionPendingResponseStarted = "ConnectionPendingResponseStarted" + ConnectionPendingResponseSucceeded = "ConnectionPendingResponseSucceeded" + ConnectionPendingResponseFailed = "ConnectionPendingResponseFailed" ) // MonitorPoolOptions contains pool options as formatted in pool events @@ -108,6 +111,7 @@ type PoolEvent struct { ServiceID *bson.ObjectID `json:"serviceId"` Interruption bool `json:"interruptInUseConnections"` Error error `json:"error"` + RequestID int32 `json:"requestId"` } // PoolMonitor is a function that allows the user to gain access to events occurring in the pool diff --git a/internal/driverutil/context.go b/internal/driverutil/context.go new file mode 100644 index 0000000000..5b8cd54b3a --- /dev/null +++ b/internal/driverutil/context.go @@ -0,0 +1,49 @@ +// Copyright (C) MongoDB, Inc. 2025-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driverutil + +import "context" + +// ContextKey is a custom type used for the keys in context values to avoid +// collisions. +type ContextKey string + +const ( + // ContextKeyHasMaxTimeMS represents a boolean value that indicates if + // maxTimeMS will be set on the wire message for an operation. + ContextKeyHasMaxTimeMS ContextKey = "hasMaxTimeMS" + + // ContextKeyRequestID is the requestID for a given operation. This is used to + // propagate the requestID for a pending read during connection check out. + ContextKeyRequestID ContextKey = "requestID" +) + +// WithValueHasMaxTimeMS returns a copy of the parent context with an added +// value indicating whether an operation will append maxTimeMS to the wire +// message. +func WithValueHasMaxTimeMS(parentCtx context.Context, val bool) context.Context { + return context.WithValue(parentCtx, ContextKeyHasMaxTimeMS, val) +} + +// WithRequestID returns a copy of the parent context with an added request ID +// value. +func WithRequestID(parentCtx context.Context, requestID int32) context.Context { + return context.WithValue(parentCtx, ContextKeyRequestID, requestID) +} + +// HasMaxTimeMS checks if the context is for an operation that will append +// maxTimeMS to the wire message. +func HasMaxTimeMS(ctx context.Context) bool { + return ctx.Value(ContextKeyHasMaxTimeMS) != nil +} + +// GetRequestID retrieves the request ID from the context if it exists. +func GetRequestID(ctx context.Context) (int32, bool) { + val, ok := ctx.Value(ContextKeyRequestID).(int32) + + return val, ok +} diff --git a/internal/integration/client_test.go b/internal/integration/client_test.go index 0478967a52..c500cd2217 100644 --- a/internal/integration/client_test.go +++ b/internal/integration/client_test.go @@ -13,6 +13,7 @@ import ( "os" "reflect" "strings" + "sync" "testing" "time" @@ -675,9 +676,9 @@ func TestClient(t *testing.T) { }, } + _, err := mt.Coll.InsertOne(context.Background(), bson.D{}) for _, tc := range testCases { mt.Run(tc.desc, func(mt *mtest.T) { - _, err := mt.Coll.InsertOne(context.Background(), bson.D{}) require.NoError(mt, err) mt.SetFailPoint(failpoint.FailPoint{ @@ -692,30 +693,47 @@ func TestClient(t *testing.T) { mt.ClearEvents() + wg := sync.WaitGroup{} + wg.Add(50) + for i := 0; i < 50; i++ { - // Run 50 operations, each with a timeout of 50ms. Expect + // Run 50 concurrent operations, each with a timeout of 50ms. Expect // them to all return a timeout error because the failpoint - // blocks find operations for 500ms. Run 50 to increase the + // blocks find operations for 50ms. Run 50 to increase the // probability that an operation will time out in a way that // can cause a retry. - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - err = tc.operation(ctx, mt.Coll) - cancel() - assert.ErrorIs(mt, err, context.DeadlineExceeded) - assert.True(mt, mongo.IsTimeout(err), "expected mongo.IsTimeout(err) to be true") - - // Assert that each operation reported exactly one command - // started events, which means the operation did not retry - // after the context timeout. - evts := mt.GetAllStartedEvents() - require.Len(mt, - mt.GetAllStartedEvents(), - 1, - "expected exactly 1 command started event per operation, but got %d after %d iterations", - len(evts), - i) - mt.ClearEvents() + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond) + err := tc.operation(ctx, mt.Coll) + cancel() + assert.ErrorIs(mt, err, context.DeadlineExceeded) + assert.True(mt, mongo.IsTimeout(err), "expected mongo.IsTimeout(err) to be true") + + wg.Done() + }() } + + wg.Wait() + + // Since an operation requires checking out a connection and because we + // attempt a pending read for socket timeouts and since the test forces + // 50 concurrent socket timeouts, then it's possible that an + // operation checks out a connection that has a pending read. In this + // case the operation will time out when checking out a connection, and + // a started event will not be propagated. So instead of + // checking that we got exactly 50 started events, we should instead + // ensure that the number of started events is equal to the number of + // unique connections used to process the operations. + pendingReadConns := mt.NumberConnectionsPendingReadStarted() + evts := mt.GetAllStartedEvents() + + require.Equal(mt, + len(evts)+pendingReadConns, + 50, + "expected exactly 1 command started event per operation (50), but got %d", + len(evts)+pendingReadConns) + mt.ClearEvents() + mt.ClearFailPoints() }) } }) diff --git a/internal/integration/cmap_prose_test.go b/internal/integration/cmap_prose_test.go new file mode 100644 index 0000000000..023c5f843b --- /dev/null +++ b/internal/integration/cmap_prose_test.go @@ -0,0 +1,167 @@ +// Copyright (C) MongoDB, Inc. 2025-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package integration + +import ( + "context" + "os" + "testing" + "time" + + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/internal/assert" + "go.mongodb.org/mongo-driver/v2/internal/integration/mtest" + "go.mongodb.org/mongo-driver/v2/internal/require" + "go.mongodb.org/mongo-driver/v2/mongo/options" +) + +func TestCMAPProse_PendingResponse_ConnectionAliveness(t *testing.T) { + const timeout = 200 * time.Millisecond + + // Skip on compressor due to proxy complexity. + if os.Getenv("MONGO_GO_DRIVER_COMPRESSOR") != "" { + t.Skip("Skipping test because MONGO_GO_DRIVER_COMPRESSOR is set, which is not supported by the proxy") + } + + // Skip on auth due to proxy complexity. + if os.Getenv("AUTH") == "auth" { + t.Skip("Skipping test because AUTH is set") + } + + // Skip on SSL due to proxy complexity. + if os.Getenv("SSL") == "ssl" { + t.Skip("Skipping test because SSL is set") + } + + // Skip unless the proxy URI is set. + if os.Getenv("MONGO_PROXY_URI") == "" { + t.Skip("Skipping test because MONGO_PROXY_URI is not set") + } + + // Create a direct connection to the proxy server. + proxyURI := os.Getenv("MONGO_PROXY_URI") + + clientOpts := options.Client().ApplyURI(proxyURI).SetMaxPoolSize(1).SetDirect(true) + mt := mtest.New(t, mtest.NewOptions().ClientOptions(clientOpts).ClientType(mtest.MongoProxy)) + + opts := mtest.NewOptions().CreateCollection(false) + mt.RunOpts("fails", opts, func(mt *mtest.T) { + // Create a command document that instructs the proxy to dely 2x the + // timeoutMS for the operation then never respond. + proxyTest := bson.D{ + {Key: "actions", Value: bson.A{ + // Causes the timeout in the initial try. + bson.D{{Key: "delayMs", Value: 400}}, + // Send nothing back to the client, ever. + bson.D{{Key: "sendBytes", Value: 0}}, + }}, + } + + type myStruct struct { + Name string `bson:"name"` + Age int `bson:"age"` + } + + cmd := bson.D{ + {Key: "insert", Value: "mycoll"}, + {Key: "documents", Value: bson.A{myStruct{Name: "Alice", Age: 30}}}, + {Key: "proxyTest", Value: proxyTest}, + } + + db := mt.Client.Database("testdb") + coll := db.Collection("mycoll") + + _ = coll.Drop(context.Background()) // Ensure the collection is clean before the test. + + // Run the command against the proxy with timeoutMS. + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + err := db.RunCommand(ctx, cmd).Err() + require.Error(t, err, "expected command to fail due to timeout") + assert.ErrorIs(t, err, context.DeadlineExceeded) + + // Wait 3 seconds to ensure there is time left in the pending response state. + time.Sleep(3 * time.Second) + + // Run an insertOne without a timeout. Expect the pending response to fail + // at the aliveness check. However, the insert should succeed since pending + // response failures are retryable. + _, err = coll.InsertOne(context.Background(), myStruct{Name: "Bob", Age: 25}) + require.NoError(t, err, "expected insertOne to succeed after pending response aliveness check") + + // There should be 1 ConnectionPendingResponseStarted event. + assert.Equal(mt, 1, mt.NumberConnectionsPendingReadStarted()) + + // There should be 1 ConnectionPendingResponseFailed event. + assert.Equal(mt, 1, mt.NumberConnectionsPendingReadFailed()) + + // There should be 0 ConnectionPendingResponseSucceeded event. + assert.Equal(mt, 0, mt.NumberConnectionsPendingReadSucceeded()) + + // There should be 1 ConnectionClosed event. + assert.Equal(mt, 1, mt.NumberConnectionsClosed()) + }) + + mt.RunOpts("succeeds", opts, func(mt *mtest.T) { + // Create a command document that instructs the proxy to dely 2x the + // timeoutMS for the operation, then responds with exactly 1 byte for + // the alivness check and finally with the entire message. + proxyTest := bson.D{ + {Key: "actions", Value: bson.A{ + // Causes the timeout in the initial try. + bson.D{{Key: "delayMs", Value: 400}}, + // Send the rest of the response for discarding on retry. + bson.D{{Key: "sendAll", Value: true}}, + }}, + } + + type myStruct struct { + Name string `bson:"name"` + Age int `bson:"age"` + } + + cmd := bson.D{ + {Key: "insert", Value: "mycoll"}, + {Key: "documents", Value: bson.A{myStruct{Name: "Alice", Age: 30}}}, + {Key: "proxyTest", Value: proxyTest}, + } + + db := mt.Client.Database("testdb") + coll := db.Collection("mycoll") + + _ = coll.Drop(context.Background()) // Ensure the collection is clean before the test. + + // Run the command against the proxy with timeoutMS. + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + err := db.RunCommand(ctx, cmd).Err() + require.Error(mt, err, "expected command to fail due to timeout") + assert.ErrorIs(mt, err, context.DeadlineExceeded) + + // Wait 3 seconds to ensure there is time left in the pending response state. + time.Sleep(3 * time.Second) + + // Run an insertOne without a timeout. Expect the pending response to fail + // at the aliveness check. + _, err = coll.InsertOne(context.Background(), myStruct{Name: "Bob", Age: 25}) + require.NoError(mt, err, "expected insertOne to succeed after pending response aliveness check") + + // There should be 1 ConnectionPendingResponseStarted event. + assert.Equal(mt, 2, mt.NumberConnectionsPendingReadStarted()) + + // There should be 0 ConnectionPendingResponseFailed event. + assert.Equal(mt, 1, mt.NumberConnectionsPendingReadFailed()) + + // There should be 1 ConnectionPendingResponseSucceeded event. + assert.Equal(mt, 1, mt.NumberConnectionsPendingReadSucceeded()) + + // The connection should not have been closed. + assert.Equal(mt, 0, mt.NumberConnectionsClosed()) + }) +} diff --git a/internal/integration/csot_test.go b/internal/integration/csot_test.go index 6808efb2a4..877f5e0341 100644 --- a/internal/integration/csot_test.go +++ b/internal/integration/csot_test.go @@ -38,12 +38,13 @@ func TestCSOT_maxTimeMS(t *testing.T) { mt := mtest.New(t, mtest.NewOptions().CreateClient(false)) testCases := []struct { - desc string - commandName string - setup func(coll *mongo.Collection) error - operation func(ctx context.Context, coll *mongo.Collection) error - sendsMaxTimeMS bool - topologies []mtest.TopologyKind + desc string + commandName string + setup func(coll *mongo.Collection) error + operation func(ctx context.Context, coll *mongo.Collection) error + sendsMaxTimeMS bool + topologies []mtest.TopologyKind + preventsConnClosureWithTimeoutMS bool }{ { desc: "FindOne", @@ -55,7 +56,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { operation: func(ctx context.Context, coll *mongo.Collection) error { return coll.FindOne(ctx, bson.D{}).Err() }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "Find", @@ -68,7 +70,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.Find(ctx, bson.D{}) return err }, - sendsMaxTimeMS: false, + sendsMaxTimeMS: false, + preventsConnClosureWithTimeoutMS: false, }, { desc: "FindOneAndDelete", @@ -80,7 +83,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { operation: func(ctx context.Context, coll *mongo.Collection) error { return coll.FindOneAndDelete(ctx, bson.D{}).Err() }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "FindOneAndUpdate", @@ -92,7 +96,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { operation: func(ctx context.Context, coll *mongo.Collection) error { return coll.FindOneAndUpdate(ctx, bson.D{}, bson.M{"$set": bson.M{"key": "value"}}).Err() }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "FindOneAndReplace", @@ -104,7 +109,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { operation: func(ctx context.Context, coll *mongo.Collection) error { return coll.FindOneAndReplace(ctx, bson.D{}, bson.D{}).Err() }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "InsertOne", @@ -113,7 +119,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.InsertOne(ctx, bson.D{}) return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "InsertMany", @@ -122,7 +129,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.InsertMany(ctx, []interface{}{bson.D{}}) return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "UpdateOne", @@ -131,7 +139,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.UpdateOne(ctx, bson.D{}, bson.M{"$set": bson.M{"key": "value"}}) return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "UpdateMany", @@ -140,7 +149,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.UpdateMany(ctx, bson.D{}, bson.M{"$set": bson.M{"key": "value"}}) return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "ReplaceOne", @@ -149,7 +159,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.ReplaceOne(ctx, bson.D{}, bson.D{}) return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "DeleteOne", @@ -158,7 +169,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.DeleteOne(ctx, bson.D{}) return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "DeleteMany", @@ -168,6 +180,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { return err }, sendsMaxTimeMS: true, + + preventsConnClosureWithTimeoutMS: true, }, { desc: "Distinct", @@ -175,7 +189,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { operation: func(ctx context.Context, coll *mongo.Collection) error { return coll.Distinct(ctx, "name", bson.D{}).Err() }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: true, }, { desc: "Aggregate", @@ -184,7 +199,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { _, err := coll.Aggregate(ctx, mongo.Pipeline{}) return err }, - sendsMaxTimeMS: false, + sendsMaxTimeMS: false, + preventsConnClosureWithTimeoutMS: false, }, { desc: "Watch", @@ -196,7 +212,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { } return err }, - sendsMaxTimeMS: true, + sendsMaxTimeMS: true, + preventsConnClosureWithTimeoutMS: false, // Change Streams aren't supported on standalone topologies. topologies: []mtest.TopologyKind{ mtest.ReplicaSet, @@ -218,7 +235,8 @@ func TestCSOT_maxTimeMS(t *testing.T) { var res []bson.D return cursor.All(ctx, &res) }, - sendsMaxTimeMS: false, + sendsMaxTimeMS: false, + preventsConnClosureWithTimeoutMS: false, }, } @@ -348,56 +366,57 @@ func TestCSOT_maxTimeMS(t *testing.T) { assertMaxTimeMSNotSet(mt, evt.Command) } }) + if tc.preventsConnClosureWithTimeoutMS { + opts := mtest.NewOptions(). + // Blocking failpoints don't work on pre-4.2 and sharded + // clusters. + Topologies(mtest.Single, mtest.ReplicaSet). + MinServerVersion("4.2") + mt.RunOpts("prevents connection closure", opts, func(mt *mtest.T) { + if tc.setup != nil { + err := tc.setup(mt.Coll) + require.NoError(mt, err) + } - opts := mtest.NewOptions(). - // Blocking failpoints don't work on pre-4.2 and sharded - // clusters. - Topologies(mtest.Single, mtest.ReplicaSet). - MinServerVersion("4.2") - mt.RunOpts("prevents connection closure", opts, func(mt *mtest.T) { - if tc.setup != nil { - err := tc.setup(mt.Coll) - require.NoError(mt, err) - } - - mt.SetFailPoint(failpoint.FailPoint{ - ConfigureFailPoint: "failCommand", - Mode: failpoint.ModeAlwaysOn, - Data: failpoint.Data{ - FailCommands: []string{tc.commandName}, - BlockConnection: true, - // Note that some operations (currently Find and - // Aggregate) do not send maxTimeMS by default, meaning - // that the server will only respond after BlockTimeMS - // is elapsed. If the amount of time that the driver - // waits for responses after a timeout is significantly - // lower than BlockTimeMS, this test will start failing - // for those operations. - BlockTimeMS: 500, - }, - }) - - tpm := eventtest.NewTestPoolMonitor() - mt.ResetClient(options.Client(). - SetPoolMonitor(tpm.PoolMonitor)) - - // Run 5 operations that time out, then assert that no - // connections were closed. - for i := 0; i < 5; i++ { - ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond) - err := tc.operation(ctx, mt.Coll) - cancel() - - if !mongo.IsTimeout(err) { - t.Logf("Operation %d returned a non-timeout error: %v", i, err) + mt.SetFailPoint(failpoint.FailPoint{ + ConfigureFailPoint: "failCommand", + Mode: failpoint.ModeAlwaysOn, + Data: failpoint.Data{ + FailCommands: []string{tc.commandName}, + BlockConnection: true, + // Note that some operations (currently Find and + // Aggregate) do not send maxTimeMS by default, meaning + // that the server will only respond after BlockTimeMS + // is elapsed. If the amount of time that the driver + // waits for responses after a timeout is significantly + // lower than BlockTimeMS, this test will start failing + // for those operations. + BlockTimeMS: 500, + }, + }) + + tpm := eventtest.NewTestPoolMonitor() + mt.ResetClient(options.Client(). + SetPoolMonitor(tpm.PoolMonitor)) + + // Run 5 operations that time out, then assert that no + // connections were closed. + for i := 0; i < 5; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond) + err := tc.operation(ctx, mt.Coll) + cancel() + + if !mongo.IsTimeout(err) { + t.Logf("Operation %d returned a non-timeout error: %v", i, err) + } } - } - closedEvents := tpm.Events(func(pe *event.PoolEvent) bool { - return pe.Type == event.ConnectionClosed + closedEvents := tpm.Events(func(pe *event.PoolEvent) bool { + return pe.Type == event.ConnectionClosed + }) + assert.Len(mt, closedEvents, 0, "expected no connection closed event") }) - assert.Len(mt, closedEvents, 0, "expected no connection closed event") - }) + } }) } diff --git a/internal/integration/mtest/mongotest.go b/internal/integration/mtest/mongotest.go index 3967bf7f82..71aea259a1 100644 --- a/internal/integration/mtest/mongotest.go +++ b/internal/integration/mtest/mongotest.go @@ -55,7 +55,11 @@ type T struct { // It must be accessed using the atomic package and should be at the beginning of the struct. // - atomic bug: https://pkg.go.dev/sync/atomic#pkg-note-BUG // - suggested layout: https://go101.org/article/memory-layout.html - connsCheckedOut int64 + connsCheckedOut int64 + connPendingReadStarted int64 + connPendingReadSucceeded int64 + connPendingReadFailed int64 + connClosed int64 *testing.T @@ -348,6 +352,24 @@ func (t *T) NumberConnectionsCheckedOut() int { return int(atomic.LoadInt64(&t.connsCheckedOut)) } +// NumberConnectionsPendingReadStarted returns the number of connections that have +// started a pending read. +func (t *T) NumberConnectionsPendingReadStarted() int { + return int(atomic.LoadInt64(&t.connPendingReadStarted)) +} + +func (t *T) NumberConnectionsClosed() int { + return int(atomic.LoadInt64(&t.connClosed)) +} + +func (t *T) NumberConnectionsPendingReadSucceeded() int { + return int(atomic.LoadInt64(&t.connPendingReadSucceeded)) +} + +func (t *T) NumberConnectionsPendingReadFailed() int { + return int(atomic.LoadInt64(&t.connPendingReadFailed)) +} + // ClearEvents clears the existing command monitoring events. func (t *T) ClearEvents() { t.started = t.started[:0] @@ -547,6 +569,11 @@ func (t *T) TrackFailPoint(fpName string) { // ClearFailPoints disables all previously set failpoints for this test. func (t *T) ClearFailPoints() { + // Run some arbitrary command to ensure that any connection that would + // otherwise blocking during a pending read is closed. This could happen if + // the mode times > 1 and the blocking time is > default pending read timeout. + _ = t.Client.Ping(context.Background(), nil) + db := t.Client.Database("admin") for _, fp := range t.failPointNames { cmd := failpoint.FailPoint{ @@ -640,6 +667,14 @@ func (t *T) createTestClient() { atomic.AddInt64(&t.connsCheckedOut, 1) case event.ConnectionCheckedIn: atomic.AddInt64(&t.connsCheckedOut, -1) + case event.ConnectionPendingResponseStarted: + atomic.AddInt64(&t.connPendingReadStarted, 1) + case event.ConnectionPendingResponseSucceeded: + atomic.AddInt64(&t.connPendingReadSucceeded, 1) + case event.ConnectionPendingResponseFailed: + atomic.AddInt64(&t.connPendingReadFailed, 1) + case event.ConnectionClosed: + atomic.AddInt64(&t.connClosed, 1) } }, }) @@ -660,6 +695,8 @@ func (t *T) createTestClient() { t.mockDeployment = drivertest.NewMockDeployment() clientOpts.Deployment = t.mockDeployment + t.Client, err = mongo.Connect(clientOpts) + case MongoProxy: t.Client, err = mongo.Connect(clientOpts) case Proxy: t.proxyDialer = newProxyDialer() diff --git a/internal/integration/mtest/options.go b/internal/integration/mtest/options.go index aff188b481..72d3affddc 100644 --- a/internal/integration/mtest/options.go +++ b/internal/integration/mtest/options.go @@ -43,6 +43,9 @@ const ( // Proxy specifies a client that proxies messages to the server and also stores parsed copies. The proxied // messages can be retrieved via T.GetProxiedMessages or T.GetRawProxiedMessages. Proxy + // MongoProxy specifies a client that communicates with a MongoDB proxy server + // as defined in Drivers Evergreen Tools. + MongoProxy ) var ( diff --git a/internal/integration/unified/event.go b/internal/integration/unified/event.go index abbec74439..9ee8fe7404 100644 --- a/internal/integration/unified/event.go +++ b/internal/integration/unified/event.go @@ -16,27 +16,30 @@ import ( type monitoringEventType string const ( - commandStartedEvent monitoringEventType = "CommandStartedEvent" - commandSucceededEvent monitoringEventType = "CommandSucceededEvent" - commandFailedEvent monitoringEventType = "CommandFailedEvent" - poolCreatedEvent monitoringEventType = "PoolCreatedEvent" - poolReadyEvent monitoringEventType = "PoolReadyEvent" - poolClearedEvent monitoringEventType = "PoolClearedEvent" - poolClosedEvent monitoringEventType = "PoolClosedEvent" - connectionCreatedEvent monitoringEventType = "ConnectionCreatedEvent" - connectionReadyEvent monitoringEventType = "ConnectionReadyEvent" - connectionClosedEvent monitoringEventType = "ConnectionClosedEvent" - connectionCheckOutStartedEvent monitoringEventType = "ConnectionCheckOutStartedEvent" - connectionCheckOutFailedEvent monitoringEventType = "ConnectionCheckOutFailedEvent" - connectionCheckedOutEvent monitoringEventType = "ConnectionCheckedOutEvent" - connectionCheckedInEvent monitoringEventType = "ConnectionCheckedInEvent" - serverDescriptionChangedEvent monitoringEventType = "ServerDescriptionChangedEvent" - serverHeartbeatFailedEvent monitoringEventType = "ServerHeartbeatFailedEvent" - serverHeartbeatStartedEvent monitoringEventType = "ServerHeartbeatStartedEvent" - serverHeartbeatSucceededEvent monitoringEventType = "ServerHeartbeatSucceededEvent" - topologyDescriptionChangedEvent monitoringEventType = "TopologyDescriptionChangedEvent" - topologyOpeningEvent monitoringEventType = "TopologyOpeningEvent" - topologyClosedEvent monitoringEventType = "TopologyClosedEvent" + commandStartedEvent monitoringEventType = "CommandStartedEvent" + commandSucceededEvent monitoringEventType = "CommandSucceededEvent" + commandFailedEvent monitoringEventType = "CommandFailedEvent" + poolCreatedEvent monitoringEventType = "PoolCreatedEvent" + poolReadyEvent monitoringEventType = "PoolReadyEvent" + poolClearedEvent monitoringEventType = "PoolClearedEvent" + poolClosedEvent monitoringEventType = "PoolClosedEvent" + connectionCreatedEvent monitoringEventType = "ConnectionCreatedEvent" + connectionReadyEvent monitoringEventType = "ConnectionReadyEvent" + connectionClosedEvent monitoringEventType = "ConnectionClosedEvent" + connectionCheckOutStartedEvent monitoringEventType = "ConnectionCheckOutStartedEvent" + connectionCheckOutFailedEvent monitoringEventType = "ConnectionCheckOutFailedEvent" + connectionCheckedOutEvent monitoringEventType = "ConnectionCheckedOutEvent" + connectionCheckedInEvent monitoringEventType = "ConnectionCheckedInEvent" + connectionPendingResponseStarted monitoringEventType = "ConnectionPendingResponseStarted" + connectionPendingResponseSucceeded monitoringEventType = "ConnectionPendingResponseSucceeded" + connectionPendingResponseFailed monitoringEventType = "ConnectionPendingResponseFailed" + serverDescriptionChangedEvent monitoringEventType = "ServerDescriptionChangedEvent" + serverHeartbeatFailedEvent monitoringEventType = "ServerHeartbeatFailedEvent" + serverHeartbeatStartedEvent monitoringEventType = "ServerHeartbeatStartedEvent" + serverHeartbeatSucceededEvent monitoringEventType = "ServerHeartbeatSucceededEvent" + topologyDescriptionChangedEvent monitoringEventType = "TopologyDescriptionChangedEvent" + topologyOpeningEvent monitoringEventType = "TopologyOpeningEvent" + topologyClosedEvent monitoringEventType = "TopologyClosedEvent" ) func monitoringEventTypeFromString(eventStr string) (monitoringEventType, bool) { @@ -69,6 +72,12 @@ func monitoringEventTypeFromString(eventStr string) (monitoringEventType, bool) return connectionCheckedOutEvent, true case "connectioncheckedinevent": return connectionCheckedInEvent, true + case "connectionpendingresponsestarted": + return connectionPendingResponseStarted, true + case "connectionpendingresponsesucceeded": + return connectionPendingResponseSucceeded, true + case "connectionpendingresponsefailed": + return connectionPendingResponseFailed, true case "serverdescriptionchangedevent": return serverDescriptionChangedEvent, true case "serverheartbeatfailedevent": @@ -112,6 +121,12 @@ func monitoringEventTypeFromPoolEvent(evt *event.PoolEvent) monitoringEventType return connectionCheckedOutEvent case event.ConnectionCheckedIn: return connectionCheckedInEvent + case event.ConnectionPendingResponseStarted: + return connectionPendingResponseStarted + case event.ConnectionPendingResponseSucceeded: + return connectionPendingResponseSucceeded + case event.ConnectionPendingResponseFailed: + return connectionPendingResponseFailed default: return "" } diff --git a/internal/integration/unified/event_verification.go b/internal/integration/unified/event_verification.go index 56c53f8adb..eb3e8b49be 100644 --- a/internal/integration/unified/event_verification.go +++ b/internal/integration/unified/event_verification.go @@ -56,7 +56,10 @@ type cmapEvent struct { Reason *string `bson:"reason"` } `bson:"connectionCheckOutFailedEvent"` - ConnectionCheckedInEvent *struct{} `bson:"connectionCheckedInEvent"` + ConnectionCheckedInEvent *struct{} `bson:"connectionCheckedInEvent"` + ConnectionPendingResponseStarted *struct{} `bson:"connectionPendingResponseStarted"` + ConnectionPendingResponseSucceeded *struct{} `bson:"connectionPendingResponseSucceeded"` + ConnectionPendingResponseFailed *struct{} `bson:"connectionPendingResponseFailed"` PoolClearedEvent *struct { HasServiceID *bool `bson:"hasServiceId"` @@ -359,6 +362,18 @@ func verifyCMAPEvents(client *clientEntity, expectedEvents *expectedEvents) erro if _, pooled, err = getNextPoolEvent(pooled, event.ConnectionCheckedIn); err != nil { return newEventVerificationError(idx, client, "failed to get next pool event: %v", err.Error()) } + case evt.ConnectionPendingResponseStarted != nil: + if _, pooled, err = getNextPoolEvent(pooled, event.ConnectionPendingResponseStarted); err != nil { + return newEventVerificationError(idx, client, "failed to get next pool event: %v", err.Error()) + } + case evt.ConnectionPendingResponseSucceeded != nil: + if _, pooled, err = getNextPoolEvent(pooled, event.ConnectionPendingResponseSucceeded); err != nil { + return newEventVerificationError(idx, client, "failed to get next pool event: %v", err.Error()) + } + case evt.ConnectionPendingResponseFailed != nil: + if _, pooled, err = getNextPoolEvent(pooled, event.ConnectionPendingResponseFailed); err != nil { + return newEventVerificationError(idx, client, "failed to get next pool event: %v", err.Error()) + } case evt.PoolClearedEvent != nil: var actual *event.PoolEvent if actual, pooled, err = getNextPoolEvent(pooled, event.ConnectionPoolCleared); err != nil { diff --git a/internal/integration/unified/schema_version.go b/internal/integration/unified/schema_version.go index 7908b39017..f1f5447883 100644 --- a/internal/integration/unified/schema_version.go +++ b/internal/integration/unified/schema_version.go @@ -16,7 +16,7 @@ import ( var ( supportedSchemaVersions = map[int]string{ - 1: "1.22", + 1: "1.24", } ) diff --git a/internal/logger/component.go b/internal/logger/component.go index a601707cbf..366a482b86 100644 --- a/internal/logger/component.go +++ b/internal/logger/component.go @@ -14,32 +14,35 @@ import ( ) const ( - CommandFailed = "Command failed" - CommandStarted = "Command started" - CommandSucceeded = "Command succeeded" - ConnectionPoolCreated = "Connection pool created" - ConnectionPoolReady = "Connection pool ready" - ConnectionPoolCleared = "Connection pool cleared" - ConnectionPoolClosed = "Connection pool closed" - ConnectionCreated = "Connection created" - ConnectionReady = "Connection ready" - ConnectionClosed = "Connection closed" - ConnectionCheckoutStarted = "Connection checkout started" - ConnectionCheckoutFailed = "Connection checkout failed" - ConnectionCheckedOut = "Connection checked out" - ConnectionCheckedIn = "Connection checked in" - ServerSelectionFailed = "Server selection failed" - ServerSelectionStarted = "Server selection started" - ServerSelectionSucceeded = "Server selection succeeded" - ServerSelectionWaiting = "Waiting for suitable server to become available" - TopologyClosed = "Stopped topology monitoring" - TopologyDescriptionChanged = "Topology description changed" - TopologyOpening = "Starting topology monitoring" - TopologyServerClosed = "Stopped server monitoring" - TopologyServerHeartbeatFailed = "Server heartbeat failed" - TopologyServerHeartbeatStarted = "Server heartbeat started" - TopologyServerHeartbeatSucceeded = "Server heartbeat succeeded" - TopologyServerOpening = "Starting server monitoring" + CommandFailed = "Command failed" + CommandStarted = "Command started" + CommandSucceeded = "Command succeeded" + ConnectionPoolCreated = "Connection pool created" + ConnectionPoolReady = "Connection pool ready" + ConnectionPoolCleared = "Connection pool cleared" + ConnectionPoolClosed = "Connection pool closed" + ConnectionCreated = "Connection created" + ConnectionReady = "Connection ready" + ConnectionClosed = "Connection closed" + ConnectionCheckoutStarted = "Connection checkout started" + ConnectionCheckoutFailed = "Connection checkout failed" + ConnectionCheckedOut = "Connection checked out" + ConnectionCheckedIn = "Connection checked in" + ConnectionPendingResponseStarted = "Pending response started" + ConnectionPendingResponseSucceeded = "Pending response succeeded" + ConnectionPendingResponseFailed = "Pending response failed" + ServerSelectionFailed = "Server selection failed" + ServerSelectionStarted = "Server selection started" + ServerSelectionSucceeded = "Server selection succeeded" + ServerSelectionWaiting = "Waiting for suitable server to become available" + TopologyClosed = "Stopped topology monitoring" + TopologyDescriptionChanged = "Topology description changed" + TopologyOpening = "Starting topology monitoring" + TopologyServerClosed = "Stopped server monitoring" + TopologyServerHeartbeatFailed = "Server heartbeat failed" + TopologyServerHeartbeatStarted = "Server heartbeat started" + TopologyServerHeartbeatSucceeded = "Server heartbeat succeeded" + TopologyServerOpening = "Starting server monitoring" ) const ( diff --git a/x/mongo/driver/operation.go b/x/mongo/driver/operation.go index 50136456e4..d322b0c1ae 100644 --- a/x/mongo/driver/operation.go +++ b/x/mongo/driver/operation.go @@ -76,6 +76,13 @@ type RetryablePoolError interface { Retryable() bool } +// RetryablePendingResponseError is an error that indicates that an error +// occurred while reading a pending response caused by a socket timeout is +// retryable. +type RetryablePendingResponseError interface { + Retryable() bool +} + // labeledError is an error that can have error labels added to it. type labeledError interface { error @@ -641,6 +648,11 @@ func (op Operation) Execute(ctx context.Context) error { if srvr == nil || conn == nil { srvr, conn, err = op.getServerAndConnection(ctx, requestID, deprioritizedServers) if err != nil { + // If the returned error is a context error, return it immediately. + if ctx.Err() != nil { + err = ctx.Err() + } + // If the returned error is retryable and there are retries remaining (negative // retries means retry indefinitely), then retry the operation. Set the server // and connection to nil to request a new server and connection. @@ -785,6 +797,14 @@ func (op Operation) Execute(ctx context.Context) error { if moreToCome { roundTrip = op.moreToComeRoundTrip } + + // Set context values to handle a pending read in case of a socket + // timeout. + if maxTimeMS != 0 { + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, startedInfo.requestID) + } + res, err = roundTrip(ctx, conn, *wm) if ep, ok := srvr.(ErrorProcessor); ok { diff --git a/x/mongo/driver/topology/connection.go b/x/mongo/driver/topology/connection.go index b1bf1d13f1..8ddffb925d 100644 --- a/x/mongo/driver/topology/connection.go +++ b/x/mongo/driver/topology/connection.go @@ -7,6 +7,7 @@ package topology import ( + "bufio" // Import bufio "context" "crypto/tls" "encoding/binary" @@ -46,6 +47,12 @@ var ( func nextConnectionID() uint64 { return atomic.AddUint64(&globalConnectionID, 1) } +type pendingResponseState struct { + remainingBytes int32 + requestID int32 + start time.Time +} + type connection struct { // state must be accessed using the atomic package and should be at the beginning of the struct. // - atomic bug: https://pkg.go.dev/sync/atomic#pkg-note-BUG @@ -53,7 +60,8 @@ type connection struct { state int64 id string - nc net.Conn // When nil, the connection is closed. + nc net.Conn // When nil, the connection is closed. + br *bufio.Reader // When non-nil, used to read from nc. addr address.Address idleTimeout time.Duration idleStart atomic.Value // Stores a time.Time @@ -81,9 +89,11 @@ type connection struct { // accessTokens in the OIDC authenticator cache. oidcTokenGenID uint64 - // awaitRemainingBytes indicates the size of server response that was not completely - // read before returning the connection to the pool. - awaitRemainingBytes *int32 + // pendingResponseState contains information required to attempt a pending read + // in the event of a socket timeout for an operation that has appended + // maxTimeMS to the wire message. + pendingResponseState *pendingResponseState + pendingResponseStateMu sync.Mutex } // newConnection handles the creation of a connection. It does not connect the connection. @@ -233,6 +243,9 @@ func (c *connection) connect(ctx context.Context) (err error) { c.nc = tlsNc } + // Initialize the buffered reader now that we have a finalized net.Conn. + c.br = bufio.NewReader(c.nc) + // running hello and authentication is handled by a handshaker on the configuration instance. handshaker := c.config.handshaker if handshaker == nil { @@ -409,11 +422,14 @@ func (c *connection) readWireMessage(ctx context.Context) ([]byte, error) { dst, errMsg, err := c.read(ctx) if err != nil { - if c.awaitRemainingBytes == nil { - // If the connection was not marked as awaiting response, close the - // connection because we don't know what the connection state is. + c.pendingResponseStateMu.Lock() + if c.pendingResponseState == nil { + // If there is no pending read on the connection, use the pre-CSOT + // behavior and close the connection because we don't know if there are + // other bytes left to read. c.close() } + c.pendingResponseStateMu.Unlock() message := errMsg return nil, ConnectionError{ ConnectionID: c.id, @@ -473,10 +489,16 @@ func (c *connection) read(ctx context.Context) (bytesRead []byte, errMsg string, // We do a ReadFull into an array here instead of doing an opportunistic ReadAtLeast into dst // because there might be more than one wire message waiting to be read, for example when // reading messages from an exhaust cursor. - n, err := io.ReadFull(c.nc, sizeBuf[:]) + n, err := io.ReadFull(c.nc, sizeBuf[:]) // Use the buffered reader if err != nil { - if l := int32(n); l == 0 && isCSOTTimeout(err) { - c.awaitRemainingBytes = &l + if l := int32(n); l == 0 && isCSOTTimeout(err) && driverutil.HasMaxTimeMS(ctx) { + requestID, _ := driverutil.GetRequestID(ctx) + + c.pendingResponseState = &pendingResponseState{ + remainingBytes: l, + requestID: requestID, + start: time.Now(), + } } return nil, "incomplete read of message header", err } @@ -488,11 +510,17 @@ func (c *connection) read(ctx context.Context) (bytesRead []byte, errMsg string, dst := make([]byte, size) copy(dst, sizeBuf[:]) - n, err = io.ReadFull(c.nc, dst[4:]) + n, err = io.ReadFull(c.nc, dst[4:]) // Use the buffered reader if err != nil { remainingBytes := size - 4 - int32(n) - if remainingBytes > 0 && isCSOTTimeout(err) { - c.awaitRemainingBytes = &remainingBytes + if remainingBytes > 0 && isCSOTTimeout(err) && driverutil.HasMaxTimeMS(ctx) { + requestID, _ := driverutil.GetRequestID(ctx) + + c.pendingResponseState = &pendingResponseState{ + remainingBytes: remainingBytes, + requestID: requestID, + start: time.Now(), + } } return dst, "incomplete read of full message", err } diff --git a/x/mongo/driver/topology/connection_test.go b/x/mongo/driver/topology/connection_test.go index 5b2f39f272..995c0f97f7 100644 --- a/x/mongo/driver/topology/connection_test.go +++ b/x/mongo/driver/topology/connection_test.go @@ -7,6 +7,7 @@ package topology import ( + "bufio" "context" "crypto/tls" "errors" @@ -380,7 +381,7 @@ func TestConnection(t *testing.T) { t.Run("size read errors", func(t *testing.T) { err := errors.New("Read error") tnc := &testNetConn{readerr: err} - conn := &connection{id: "foobar", nc: tnc, state: connConnected} + conn := &connection{id: "foobar", nc: tnc, state: connConnected, br: bufio.NewReader(tnc)} listener := newTestCancellationListener(false) conn.cancellationListener = listener @@ -397,7 +398,7 @@ func TestConnection(t *testing.T) { t.Run("size too small errors", func(t *testing.T) { err := errors.New("malformed message length: 3") tnc := &testNetConn{readerr: err, buf: []byte{0x03, 0x00, 0x00, 0x00}} - conn := &connection{id: "foobar", nc: tnc, state: connConnected} + conn := &connection{id: "foobar", nc: tnc, state: connConnected, br: bufio.NewReader(tnc)} listener := newTestCancellationListener(false) conn.cancellationListener = listener @@ -414,7 +415,7 @@ func TestConnection(t *testing.T) { t.Run("full message read errors", func(t *testing.T) { err := errors.New("Read error") tnc := &testNetConn{readerr: err, buf: []byte{0x11, 0x00, 0x00, 0x00}} - conn := &connection{id: "foobar", nc: tnc, state: connConnected} + conn := &connection{id: "foobar", nc: tnc, state: connConnected, br: bufio.NewReader(tnc)} listener := newTestCancellationListener(false) conn.cancellationListener = listener @@ -450,7 +451,7 @@ func TestConnection(t *testing.T) { err := errors.New("length of read message too large") tnc := &testNetConn{buf: make([]byte, len(tc.buffer))} copy(tnc.buf, tc.buffer) - conn := &connection{id: "foobar", nc: tnc, state: connConnected, desc: tc.desc} + conn := &connection{id: "foobar", nc: tnc, state: connConnected, desc: tc.desc, br: bufio.NewReader(tnc)} listener := newTestCancellationListener(false) conn.cancellationListener = listener @@ -467,7 +468,7 @@ func TestConnection(t *testing.T) { want := []byte{0x0A, 0x00, 0x00, 0x00, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A} tnc := &testNetConn{buf: make([]byte, len(want))} copy(tnc.buf, want) - conn := &connection{id: "foobar", nc: tnc, state: connConnected} + conn := &connection{id: "foobar", nc: tnc, state: connConnected, br: bufio.NewReader(tnc)} listener := newTestCancellationListener(false) conn.cancellationListener = listener @@ -497,7 +498,7 @@ func TestConnection(t *testing.T) { readBuf := []byte{10, 0, 0, 0} nc := newCancellationReadConn(&testNetConn{}, tc.skip, readBuf) - conn := &connection{id: "foobar", nc: nc, state: connConnected} + conn := &connection{id: "foobar", nc: nc, state: connConnected, br: bufio.NewReader(nc)} listener := newTestCancellationListener(false) conn.cancellationListener = listener @@ -525,7 +526,7 @@ func TestConnection(t *testing.T) { }) t.Run("closes connection if context is cancelled even if the socket read succeeds", func(t *testing.T) { tnc := &testNetConn{buf: []byte{0x0A, 0x00, 0x00, 0x00, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A}} - conn := &connection{id: "foobar", nc: tnc, state: connConnected} + conn := &connection{id: "foobar", nc: tnc, state: connConnected, br: bufio.NewReader(tnc)} listener := newTestCancellationListener(true) conn.cancellationListener = listener @@ -566,7 +567,7 @@ func TestConnection(t *testing.T) { t.Run("cancellation listener callback", func(t *testing.T) { t.Run("closes connection", func(t *testing.T) { tnc := &testNetConn{} - conn := &connection{state: connConnected, nc: tnc} + conn := &connection{state: connConnected, nc: tnc, br: bufio.NewReader(tnc), id: "foobar"} conn.cancellationListenerCallback() assert.True(t, conn.state == connDisconnected, "expected connection state %v, got %v", connDisconnected, diff --git a/x/mongo/driver/topology/pool.go b/x/mongo/driver/topology/pool.go index 162bb9c1af..b566c386c4 100644 --- a/x/mongo/driver/topology/pool.go +++ b/x/mongo/driver/topology/pool.go @@ -8,8 +8,9 @@ package topology import ( "context" + "encoding/binary" + "errors" "fmt" - "io" "net" "sync" "sync/atomic" @@ -574,6 +575,10 @@ func (p *pool) checkOut(ctx context.Context) (conn *connection, err error) { return nil, w.err } + if err := awaitPendingResponse(ctx, p, w.conn); err != nil { + return nil, err + } + duration = time.Since(start) if mustLogPoolMessage(p) { keysAndValues := logger.KeyValues{ @@ -630,6 +635,10 @@ func (p *pool) checkOut(ctx context.Context) (conn *connection, err error) { return nil, w.err } + if err := awaitPendingResponse(ctx, p, w.conn); err != nil { + return nil, err + } + duration := time.Since(start) if mustLogPoolMessage(p) { keysAndValues := logger.KeyValues{ @@ -769,82 +778,315 @@ func (p *pool) removeConnection(conn *connection, reason reason, err error) erro return nil } -var ( - // BGReadTimeout is the maximum amount of the to wait when trying to read - // the server reply on a connection after an operation timed out. The - // default is 400ms. - // - // Deprecated: BGReadTimeout is intended for internal use only and may be - // removed or modified at any time. - BGReadTimeout = 400 * time.Millisecond +// PendingResponseTimeout is the maximum amount of the to wait when trying to +// read the server reply on a connection after an operation timed out. The +// default is 3000 milliseconds. +// +// Deprecated: PendingResponseTimeout is intended for internal use only and may +// be removed or modified at any time. +var PendingResponseTimeout = 3000 * time.Millisecond + +// publishPendingResponseStarted will log a message to the pool logger and +// publish an event to the pool monitor if they are set. +func publishPendingResponseStarted(pool *pool, conn *connection) { + prs := conn.pendingResponseState + if prs == nil { + return + } - // BGReadCallback is a callback for monitoring the behavior of the - // background-read-on-timeout connection preserving mechanism. - // - // Deprecated: BGReadCallback is intended for internal use only and may be - // removed or modified at any time. - BGReadCallback func(addr string, start, read time.Time, errs []error, connClosed bool) -) + // log a message to the pool logger if it is set. + if mustLogPoolMessage(pool) { + keysAndValues := logger.KeyValues{ + logger.KeyDriverConnectionID, conn.driverConnectionID, + logger.KeyRequestID, prs.requestID, + } -// bgRead sets a new read deadline on the provided connection and tries to read -// any bytes returned by the server. If successful, it checks the connection -// into the provided pool. If there are any errors, it closes the connection. -// -// It calls the package-global BGReadCallback function, if set, with the -// address, timings, and any errors that occurred. -func bgRead(pool *pool, conn *connection, size int32) { - var err error - start := time.Now() + logPoolMessage(pool, logger.ConnectionPendingResponseStarted, keysAndValues...) + } - defer func() { - read := time.Now() - errs := make([]error, 0) - connClosed := false + // publish an event to the pool monitor if it is set. + if pool.monitor != nil { + event := &event.PoolEvent{ + Type: event.ConnectionPendingResponseStarted, + Address: pool.address.String(), + ConnectionID: conn.driverConnectionID, + RequestID: prs.requestID, + } + + pool.monitor.Event(event) + } +} + +func publishPendingResponseFailed(pool *pool, conn *connection, dur time.Duration, err error) { + prs := conn.pendingResponseState + if prs == nil { + return + } + + reason := event.ReasonError + if errors.Is(err, context.DeadlineExceeded) { + reason = event.ReasonTimedOut + } + + if mustLogPoolMessage(pool) { + keysAndValues := logger.KeyValues{ + logger.KeyDriverConnectionID, conn.driverConnectionID, + logger.KeyRequestID, prs.requestID, + logger.KeyReason, reason, + logger.KeyError, err.Error(), + } + + logPoolMessage(pool, logger.ConnectionPendingResponseFailed, keysAndValues...) + } + + if pool.monitor != nil { + e := &event.PoolEvent{ + Type: event.ConnectionPendingResponseFailed, + Address: pool.address.String(), + ConnectionID: conn.driverConnectionID, + RequestID: prs.requestID, + Reason: reason, + Error: err, + Duration: dur, + } + pool.monitor.Event(e) + } +} + +func publishPendingResponseSucceeded(pool *pool, conn *connection, dur time.Duration) { + prs := conn.pendingResponseState + if prs == nil { + return + } + + if mustLogPoolMessage(pool) { + keysAndValues := logger.KeyValues{ + logger.KeyDriverConnectionID, conn.driverConnectionID, + logger.KeyRequestID, prs.requestID, + logger.KeyDurationMS, dur.Milliseconds(), + } + + logPoolMessage(pool, logger.ConnectionPendingResponseSucceeded, keysAndValues...) + } + + if pool.monitor != nil { + event := &event.PoolEvent{ + Type: event.ConnectionPendingResponseSucceeded, + Address: pool.address.String(), + ConnectionID: conn.driverConnectionID, + RequestID: prs.requestID, + Duration: dur, + } + + pool.monitor.Event(event) + } +} + +func peekConnectionAlive(conn *connection) (int, error) { + // very short deadline so we don’t block + if err := conn.nc.SetReadDeadline(time.Now().Add(1 * time.Millisecond)); err != nil { + return 0, err + } + // Peek(1) will fill the bufio.Reader’s buffer if needed, + // but will NOT advance it. + bytes, err := conn.br.Peek(1) + return len(bytes), err +} + +func attemptPendingResponse(ctx context.Context, conn *connection, remainingTime time.Duration) (int, error) { + state := conn.pendingResponseState + if state == nil { + return 0, fmt.Errorf("no pending read state") + } + + // compute an absolute deadline combining ctx + our leftover + var dl time.Time + if dl0, ok := ctx.Deadline(); ok && time.Now().Add(remainingTime).After(dl0) { + dl = dl0 + } else { + dl = time.Now().Add(remainingTime) + } + if err := conn.nc.SetReadDeadline(dl); err != nil { + return 0, fmt.Errorf("setting read deadline: %w", err) + } + + totalRead := 0 + + // if we haven’t even parsed the 4-byte length yet, peek it + if state.remainingBytes == 0 { + hdr, err := conn.br.Peek(4) if err != nil { - errs = append(errs, err) - connClosed = true - err = conn.close() - if err != nil { - errs = append(errs, fmt.Errorf("error closing conn after reading: %w", err)) + return 0, fmt.Errorf("peeking length prefix: %w", err) + } + msgLen := int(binary.LittleEndian.Uint32(hdr)) + // consume those 4 bytes now that we know the message length + if _, err := conn.br.Discard(4); err != nil { + return 0, fmt.Errorf("discarding length prefix: %w", err) + } + state.remainingBytes = int32(msgLen) - 4 + } + + buf := make([]byte, 4096) + for state.remainingBytes > 0 { + // refresh the deadline so large messages don't time out + if err := conn.nc.SetReadDeadline(time.Now().Add(time.Until(dl))); err != nil { + return totalRead, fmt.Errorf("renewing deadline: %w", err) + } + + toRead := int32(len(buf)) + if state.remainingBytes < toRead { + toRead = state.remainingBytes + } + + n, err := conn.br.Read(buf[:toRead]) + if n > 0 { + totalRead += n + state.remainingBytes -= int32(n) + } + if err != nil { + // if it's just a timeout, record how much is left + if ne, ok := err.(net.Error); ok && ne.Timeout() { + return totalRead, fmt.Errorf("timeout discarding %d bytes: %w", + state.remainingBytes, err) } + return totalRead, fmt.Errorf("reading body: %w", err) } + } + + return totalRead + 4, nil +} + +// poolClearedError is an error returned when the connection pool is cleared or currently paused. It +// is a retryable error. +type pendingResponseError struct { + err error +} + +var _ error = pendingResponseError{} +var _ driver.RetryablePoolError = pendingResponseError{} + +func (pre pendingResponseError) Error() string { + if pre.err == nil { + return "" + } + return pre.err.Error() +} + +// Retryable returns true. All poolClearedErrors are retryable. +func (pendingResponseError) Retryable() bool { return true } + +func (pre pendingResponseError) Unwrap() error { + if pre.err == nil { + return nil + } + return pre.err +} + +// awaitPendingResponse sets a new read deadline on the provided connection and +// tries to read any bytes returned by the server. If there are any errors, the +// connection will be checked back into the pool to be retried. +func awaitPendingResponse(ctx context.Context, pool *pool, conn *connection) error { + conn.pendingResponseStateMu.Lock() + defer conn.pendingResponseStateMu.Unlock() + + // If there are no bytes pending read, do nothing. + if conn.pendingResponseState == nil { + return nil + } + publishPendingResponseStarted(pool, conn) + + var ( + pendingResponseState = conn.pendingResponseState + remainingTime = pendingResponseState.start.Add(PendingResponseTimeout).Sub(time.Now()) + err error + bytesRead int + alivenessCheck bool + ) + + st := time.Now() + if remainingTime <= 0 { + // If there is no remaining time, we can just peek at the connection to check + // aliveness. In such cases, we don't want to close the connection. + bytesRead, err = peekConnectionAlive(conn) + + // Mark this attempt as alive but check the connection back it the pull and + // send a retryable error. + alivenessCheck = true + } else { + bytesRead, err = attemptPendingResponse(ctx, conn, remainingTime) + } + + endTime := time.Now() + endDuration := time.Since(st) + + if err != nil { // No matter what happens, always check the connection back into the // pool, which will either make it available for other operations or // remove it from the pool if it was closed. - err = pool.checkInNoEvent(conn) - if err != nil { - errs = append(errs, fmt.Errorf("error checking in: %w", err)) + // + // TODO(GODRIVER-3385): Figure out how to handle this error. It's possible + // that a single connection can be checked out to handle multiple concurrent + // operations. This is likely a bug in the Go Driver. So it's possible that + // the connection is idle at the point of check-in. + defer func() { + dur := time.Since(st) + publishPendingResponseFailed(pool, conn, dur, err) + + _ = pool.checkInNoEvent(conn) + }() + + isCSOTTimeout := func(err error) bool { + // If the error was a timeout error, instead of closing the + // connection mark it as awaiting response so the pool can read the + // response before making it available to other operations. + nerr := net.Error(nil) + return errors.As(err, &nerr) && nerr.Timeout() } - if BGReadCallback != nil { - BGReadCallback(conn.addr.String(), start, read, errs, connClosed) + if !isCSOTTimeout(err) { + if err := conn.close(); err != nil { + return pendingResponseError{err: err} + } + return pendingResponseError{err: err} } - }() + } - err = conn.nc.SetReadDeadline(time.Now().Add(BGReadTimeout)) - if err != nil { - err = fmt.Errorf("error setting a read deadline: %w", err) - return + // If the read was successful, then we should refresh the remaining timeout. + if bytesRead > 0 { + pendingResponseState.start = endTime } - if size == 0 { - var sizeBuf [4]byte - _, err = io.ReadFull(conn.nc, sizeBuf[:]) - if err != nil { - err = fmt.Errorf("error reading the message size: %w", err) - return + // If the remaining time has been exceeded, then close the connection. + if endTime.Sub(pendingResponseState.start) > PendingResponseTimeout { + if err := conn.close(); err != nil { + return pendingResponseError{err: err} } - size, err = conn.parseWmSizeBytes(sizeBuf) - if err != nil { - return - } - size -= 4 } - _, err = io.CopyN(io.Discard, conn.nc, int64(size)) + if err != nil { - err = fmt.Errorf("error discarding %d byte message: %w", size, err) + return pendingResponseError{err: err} + } + + // If the connection is alive but undrained we can check it back into the pool + // and return a pendingResponseError to indicate that the connection is + // alive and retryable. + if alivenessCheck { + dur := time.Since(st) + publishPendingResponseFailed(pool, conn, dur, err) + + _ = pool.checkInNoEvent(conn) + + // TODO this should be a special error noting that the remainting timeout + // has been exceeded. + return pendingResponseError{err: fmt.Errorf("connection is alive and retryable: %w", err)} } + + publishPendingResponseSucceeded(pool, conn, endDuration) + + conn.pendingResponseState = nil + + return nil } // checkIn returns an idle connection to the pool. If the connection is perished or the pool is @@ -886,21 +1128,6 @@ func (p *pool) checkInNoEvent(conn *connection) error { return ErrWrongPool } - // If the connection has an awaiting server response, try to read the - // response in another goroutine before checking it back into the pool. - // - // Do this here because we want to publish checkIn events when the operation - // is done with the connection, not when it's ready to be used again. That - // means that connections in "awaiting response" state are checked in but - // not usable, which is not covered by the current pool events. We may need - // to add pool event information in the future to communicate that. - if conn.awaitRemainingBytes != nil { - size := *conn.awaitRemainingBytes - conn.awaitRemainingBytes = nil - go bgRead(p, conn, size) - return nil - } - // Bump the connection idle start time here because we're about to make the // connection "available". The idle start time is used to determine how long // a connection has been idle and when it has reached its max idle time and diff --git a/x/mongo/driver/topology/pool_test.go b/x/mongo/driver/topology/pool_test.go index f58e1cf204..89268b664b 100644 --- a/x/mongo/driver/topology/pool_test.go +++ b/x/mongo/driver/topology/pool_test.go @@ -18,6 +18,7 @@ import ( "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/assert" "go.mongodb.org/mongo-driver/v2/internal/csot" + "go.mongodb.org/mongo-driver/v2/internal/driverutil" "go.mongodb.org/mongo-driver/v2/internal/eventtest" "go.mongodb.org/mongo-driver/v2/internal/require" "go.mongodb.org/mongo-driver/v2/mongo/address" @@ -1161,24 +1162,10 @@ func TestPool_maintain(t *testing.T) { }) } -func TestBackgroundRead(t *testing.T) { +func TestAwaitPendingRead(t *testing.T) { t.Parallel() - newBGReadCallback := func(errsCh chan []error) func(string, time.Time, time.Time, []error, bool) { - return func(_ string, _, _ time.Time, errs []error, _ bool) { - errsCh <- errs - close(errsCh) - } - } - t.Run("incomplete read of message header", func(t *testing.T) { - errsCh := make(chan []error) - var originalCallback func(string, time.Time, time.Time, []error, bool) - originalCallback, BGReadCallback = BGReadCallback, newBGReadCallback(errsCh) - t.Cleanup(func() { - BGReadCallback = originalCallback - }) - timeout := 10 * time.Millisecond cleanup := make(chan struct{}) @@ -1202,24 +1189,21 @@ func TestBackgroundRead(t *testing.T) { conn, err := p.checkOut(context.Background()) require.NoError(t, err) + ctx, cancel := csot.WithTimeout(context.Background(), &timeout) defer cancel() + + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, -1) + _, err = conn.readWireMessage(ctx) regex := regexp.MustCompile( `^connection\(.*\[-\d+\]\) incomplete read of message header: context deadline exceeded: client timed out waiting for server response: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, ) assert.True(t, regex.MatchString(err.Error()), "error %q does not match pattern %q", err, regex) - assert.Nil(t, conn.awaitRemainingBytes, "conn.awaitRemainingBytes should be nil") - close(errsCh) // this line causes a double close if BGReadCallback is ever called. + assert.Nil(t, conn.pendingResponseState, "conn.awaitRemainingBytes should be nil") }) t.Run("timeout reading message header, successful background read", func(t *testing.T) { - errsCh := make(chan []error) - var originalCallback func(string, time.Time, time.Time, []error, bool) - originalCallback, BGReadCallback = BGReadCallback, newBGReadCallback(errsCh) - t.Cleanup(func() { - BGReadCallback = originalCallback - }) - timeout := 10 * time.Millisecond addr := bootstrapConnections(t, 1, func(nc net.Conn) { @@ -1233,8 +1217,20 @@ func TestBackgroundRead(t *testing.T) { require.NoError(t, err) }) + var pendingReadError error + monitor := &event.PoolMonitor{ + Event: func(pe *event.PoolEvent) { + if pe.Type == event.ConnectionPendingResponseFailed { + pendingReadError = pe.Error + } + }, + } + p := newPool( - poolConfig{Address: address.Address(addr.String())}, + poolConfig{ + Address: address.Address(addr.String()), + PoolMonitor: monitor, + }, ) defer p.close(context.Background()) err := p.ready() @@ -1242,8 +1238,13 @@ func TestBackgroundRead(t *testing.T) { conn, err := p.checkOut(context.Background()) require.NoError(t, err) + ctx, cancel := csot.WithTimeout(context.Background(), &timeout) defer cancel() + + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, -1) + _, err = conn.readWireMessage(ctx) regex := regexp.MustCompile( `^connection\(.*\[-\d+\]\) incomplete read of message header: context deadline exceeded: client timed out waiting for server response: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, @@ -1251,22 +1252,13 @@ func TestBackgroundRead(t *testing.T) { assert.True(t, regex.MatchString(err.Error()), "error %q does not match pattern %q", err, regex) err = p.checkIn(conn) require.NoError(t, err) - var bgErrs []error - select { - case bgErrs = <-errsCh: - case <-time.After(3 * time.Second): - assert.Fail(t, "did not receive expected error after waiting for 3 seconds") - } - require.Len(t, bgErrs, 0, "expected no error from bgRead()") + + _, err = p.checkOut(context.Background()) + require.NoError(t, err) + + require.NoError(t, pendingReadError) }) t.Run("timeout reading message header, incomplete head during background read", func(t *testing.T) { - errsCh := make(chan []error) - var originalCallback func(string, time.Time, time.Time, []error, bool) - originalCallback, BGReadCallback = BGReadCallback, newBGReadCallback(errsCh) - t.Cleanup(func() { - BGReadCallback = originalCallback - }) - timeout := 10 * time.Millisecond addr := bootstrapConnections(t, 1, func(nc net.Conn) { @@ -1280,8 +1272,20 @@ func TestBackgroundRead(t *testing.T) { require.NoError(t, err) }) + var pendingReadError error + monitor := &event.PoolMonitor{ + Event: func(pe *event.PoolEvent) { + if pe.Type == event.ConnectionPendingResponseFailed { + pendingReadError = pe.Error + } + }, + } + p := newPool( - poolConfig{Address: address.Address(addr.String())}, + poolConfig{ + Address: address.Address(addr.String()), + PoolMonitor: monitor, + }, ) defer p.close(context.Background()) err := p.ready() @@ -1289,8 +1293,13 @@ func TestBackgroundRead(t *testing.T) { conn, err := p.checkOut(context.Background()) require.NoError(t, err) + ctx, cancel := csot.WithTimeout(context.Background(), &timeout) defer cancel() + + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, -1) + _, err = conn.readWireMessage(ctx) regex := regexp.MustCompile( `^connection\(.*\[-\d+\]\) incomplete read of message header: context deadline exceeded: client timed out waiting for server response: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, @@ -1298,23 +1307,13 @@ func TestBackgroundRead(t *testing.T) { assert.True(t, regex.MatchString(err.Error()), "error %q does not match pattern %q", err, regex) err = p.checkIn(conn) require.NoError(t, err) - var bgErrs []error - select { - case bgErrs = <-errsCh: - case <-time.After(3 * time.Second): - assert.Fail(t, "did not receive expected error after waiting for 3 seconds") - } - require.Len(t, bgErrs, 1, "expected 1 error from bgRead()") - assert.EqualError(t, bgErrs[0], "error reading the message size: unexpected EOF") + + _, err = p.checkOut(context.Background()) + require.Error(t, err) + + assert.EqualError(t, pendingReadError, "peeking length prefix: EOF") }) t.Run("timeout reading message header, background read timeout", func(t *testing.T) { - errsCh := make(chan []error) - var originalCallback func(string, time.Time, time.Time, []error, bool) - originalCallback, BGReadCallback = BGReadCallback, newBGReadCallback(errsCh) - t.Cleanup(func() { - BGReadCallback = originalCallback - }) - timeout := 10 * time.Millisecond cleanup := make(chan struct{}) @@ -1332,17 +1331,35 @@ func TestBackgroundRead(t *testing.T) { require.NoError(t, err) }) + var pendingReadError error + monitor := &event.PoolMonitor{ + Event: func(pe *event.PoolEvent) { + if pe.Type == event.ConnectionPendingResponseFailed { + pendingReadError = pe.Error + } + }, + } + p := newPool( - poolConfig{Address: address.Address(addr.String())}, + poolConfig{ + Address: address.Address(addr.String()), + PoolMonitor: monitor, + }, ) + defer p.close(context.Background()) err := p.ready() require.NoError(t, err) conn, err := p.checkOut(context.Background()) require.NoError(t, err) + ctx, cancel := csot.WithTimeout(context.Background(), &timeout) defer cancel() + + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, -1) + _, err = conn.readWireMessage(ctx) regex := regexp.MustCompile( `^connection\(.*\[-\d+\]\) incomplete read of message header: context deadline exceeded: client timed out waiting for server response: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, @@ -1350,26 +1367,16 @@ func TestBackgroundRead(t *testing.T) { assert.True(t, regex.MatchString(err.Error()), "error %q does not match pattern %q", err, regex) err = p.checkIn(conn) require.NoError(t, err) - var bgErrs []error - select { - case bgErrs = <-errsCh: - case <-time.After(3 * time.Second): - assert.Fail(t, "did not receive expected error after waiting for 3 seconds") - } - require.Len(t, bgErrs, 1, "expected 1 error from bgRead()") + + _, err = p.checkOut(context.Background()) + require.Error(t, err) + wantErr := regexp.MustCompile( - `^error discarding 6 byte message: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, + `^timeout discarding 2 bytes: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, ) - assert.True(t, wantErr.MatchString(bgErrs[0].Error()), "error %q does not match pattern %q", bgErrs[0], wantErr) + assert.True(t, wantErr.MatchString(pendingReadError.Error()), "error %q does not match pattern %q", pendingReadError, wantErr) }) t.Run("timeout reading full message, successful background read", func(t *testing.T) { - errsCh := make(chan []error) - var originalCallback func(string, time.Time, time.Time, []error, bool) - originalCallback, BGReadCallback = BGReadCallback, newBGReadCallback(errsCh) - t.Cleanup(func() { - BGReadCallback = originalCallback - }) - timeout := 10 * time.Millisecond addr := bootstrapConnections(t, 1, func(nc net.Conn) { @@ -1386,17 +1393,35 @@ func TestBackgroundRead(t *testing.T) { require.NoError(t, err) }) + var pendingReadError error + monitor := &event.PoolMonitor{ + Event: func(pe *event.PoolEvent) { + if pe.Type == event.ConnectionPendingResponseFailed { + pendingReadError = pe.Error + } + }, + } + p := newPool( - poolConfig{Address: address.Address(addr.String())}, + poolConfig{ + Address: address.Address(addr.String()), + PoolMonitor: monitor, + }, ) + defer p.close(context.Background()) err := p.ready() require.NoError(t, err) conn, err := p.checkOut(context.Background()) require.NoError(t, err) + ctx, cancel := csot.WithTimeout(context.Background(), &timeout) defer cancel() + + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, -1) + _, err = conn.readWireMessage(ctx) regex := regexp.MustCompile( `^connection\(.*\[-\d+\]\) incomplete read of full message: context deadline exceeded: client timed out waiting for server response: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, @@ -1404,22 +1429,13 @@ func TestBackgroundRead(t *testing.T) { assert.True(t, regex.MatchString(err.Error()), "error %q does not match pattern %q", err, regex) err = p.checkIn(conn) require.NoError(t, err) - var bgErrs []error - select { - case bgErrs = <-errsCh: - case <-time.After(3 * time.Second): - assert.Fail(t, "did not receive expected error after waiting for 3 seconds") - } - require.Len(t, bgErrs, 0, "expected no error from bgRead()") + + _, err = p.checkOut(context.Background()) + require.NoError(t, err) + + require.NoError(t, pendingReadError) }) t.Run("timeout reading full message, background read EOF", func(t *testing.T) { - errsCh := make(chan []error) - var originalCallback func(string, time.Time, time.Time, []error, bool) - originalCallback, BGReadCallback = BGReadCallback, newBGReadCallback(errsCh) - t.Cleanup(func() { - BGReadCallback = originalCallback - }) - timeout := 10 * time.Millisecond addr := bootstrapConnections(t, 1, func(nc net.Conn) { @@ -1436,17 +1452,35 @@ func TestBackgroundRead(t *testing.T) { require.NoError(t, err) }) + var pendingReadError error + monitor := &event.PoolMonitor{ + Event: func(pe *event.PoolEvent) { + if pe.Type == event.ConnectionPendingResponseFailed { + pendingReadError = pe.Error + } + }, + } + p := newPool( - poolConfig{Address: address.Address(addr.String())}, + poolConfig{ + Address: address.Address(addr.String()), + PoolMonitor: monitor, + }, ) + defer p.close(context.Background()) err := p.ready() require.NoError(t, err) conn, err := p.checkOut(context.Background()) require.NoError(t, err) + ctx, cancel := csot.WithTimeout(context.Background(), &timeout) defer cancel() + + ctx = driverutil.WithValueHasMaxTimeMS(ctx, true) + ctx = driverutil.WithRequestID(ctx, -1) + _, err = conn.readWireMessage(ctx) regex := regexp.MustCompile( `^connection\(.*\[-\d+\]\) incomplete read of full message: context deadline exceeded: client timed out waiting for server response: read tcp 127.0.0.1:.*->127.0.0.1:.*: i\/o timeout$`, @@ -1454,14 +1488,11 @@ func TestBackgroundRead(t *testing.T) { assert.True(t, regex.MatchString(err.Error()), "error %q does not match pattern %q", err, regex) err = p.checkIn(conn) require.NoError(t, err) - var bgErrs []error - select { - case bgErrs = <-errsCh: - case <-time.After(3 * time.Second): - assert.Fail(t, "did not receive expected error after waiting for 3 seconds") - } - require.Len(t, bgErrs, 1, "expected 1 error from bgRead()") - assert.EqualError(t, bgErrs[0], "error discarding 3 byte message: EOF") + + _, err = p.checkOut(context.Background()) + require.Error(t, err) + + assert.EqualError(t, pendingReadError, "reading body: EOF") }) }