From 3a1fdc1938fa778bb7d2364bd6697eaa68ef565c Mon Sep 17 00:00:00 2001 From: Katherine Walker Date: Fri, 7 Jun 2019 10:36:51 -0400 Subject: [PATCH] fix(sessions): ensure an error is thrown when attempting sharded transactions Fixes NODE-1931 --- lib/core/sessions.js | 12 ++++++++++++ test/functional/transactions_tests.js | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/core/sessions.js b/lib/core/sessions.js index 530b7576df..bbbc72886c 100644 --- a/lib/core/sessions.js +++ b/lib/core/sessions.js @@ -15,6 +15,10 @@ const isPromiseLike = require('./utils').isPromiseLike; const ReadPreference = require('./topologies/read_preference'); const isTransactionCommand = require('./transactions').isTransactionCommand; const resolveClusterTime = require('./topologies/shared').resolveClusterTime; +const isSharded = require('./wireprotocol/shared').isSharded; +const maxWireVersion = require('./utils').maxWireVersion; + +const MAX_FOR_TRANSACTIONS = 7; function assertAlive(session, callback) { if (session.serverSession == null) { @@ -185,6 +189,14 @@ class ClientSession extends EventEmitter { throw new MongoError('Transaction already in progress'); } + const topologyMaxWireVersion = maxWireVersion(this.topology); + if ( + isSharded(this.topology) || + (topologyMaxWireVersion != null && topologyMaxWireVersion < MAX_FOR_TRANSACTIONS) + ) { + throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + // increment txnNumber this.incrementTransactionNumber(); diff --git a/test/functional/transactions_tests.js b/test/functional/transactions_tests.js index 32dd818bd8..77bf839312 100644 --- a/test/functional/transactions_tests.js +++ b/test/functional/transactions_tests.js @@ -205,6 +205,32 @@ describe('Transactions', function() { } }); }); + + describe('startTransaction', function() { + it('should error if transactions are not supported', { + metadata: { requires: { topology: ['sharded'], mongodb: '>4.0.0' } }, + test: function(done) { + const configuration = this.configuration; + const client = configuration.newClient(configuration.writeConcernMax(), { poolSize: 1 }); + + client.connect((err, client) => { + const session = client.startSession(); + const db = client.db(configuration.db); + const coll = db.collection('transaction_error_test'); + coll.insertOne({ a: 1 }, err => { + expect(err).to.not.exist; + expect(() => session.startTransaction()).to.throw( + 'Transactions are not supported on sharded clusters in MongoDB < 4.2.' + ); + + session.endSession(() => { + client.close(done); + }); + }); + }); + } + }); + }); }); function parseTopologies(topologies) {