From b313b99276b6f5aea962daab8b755d9e9dac309f Mon Sep 17 00:00:00 2001 From: Eric Mc Sween <5454374+emcsween@users.noreply.github.com> Date: Thu, 11 May 2023 07:50:53 -0400 Subject: [PATCH] Merge pull request #13045 from overleaf/em-check-mongo-transactions Stop ServerPro/CE from booting if Mongo doesn't support transactions GitOrigin-RevId: b38c4f4ea8e74a80fe732ef5f3fe6fa703b55af1 --- .../web/app/src/infrastructure/Mongoose.js | 6 ++++ .../scripts/check-mongodb.js | 34 +++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/services/web/app/src/infrastructure/Mongoose.js b/services/web/app/src/infrastructure/Mongoose.js index 417ff3e720..5871c49925 100644 --- a/services/web/app/src/infrastructure/Mongoose.js +++ b/services/web/app/src/infrastructure/Mongoose.js @@ -54,11 +54,17 @@ mongoose.plugin(schema => { mongoose.Promise = global.Promise +async function getMongoClient() { + const mongooseInstance = await connectionPromise + return mongooseInstance.connection.getClient() +} + async function getNativeDb() { const mongooseInstance = await connectionPromise return mongooseInstance.connection.db } +mongoose.getMongoClient = getMongoClient mongoose.getNativeDb = getNativeDb mongoose.connectionPromise = connectionPromise diff --git a/services/web/modules/server-ce-scripts/scripts/check-mongodb.js b/services/web/modules/server-ce-scripts/scripts/check-mongodb.js index f2e62c94e4..38dcc8ca7f 100644 --- a/services/web/modules/server-ce-scripts/scripts/check-mongodb.js +++ b/services/web/modules/server-ce-scripts/scripts/check-mongodb.js @@ -1,12 +1,40 @@ -const { waitForDb } = require('../../../app/src/infrastructure/mongodb') +const { ObjectId } = require('mongodb') +const { waitForDb, db } = require('../../../app/src/infrastructure/mongodb') +const { getMongoClient } = require('../../../app/src/infrastructure/Mongoose') -waitForDb() +async function main() { + try { + await waitForDb() + } catch (err) { + console.error('Cannot connect to mongodb') + throw err + } + try { + await testTransactions() + } catch (err) { + console.error("Mongo instance doesn't support transactions") + throw err + } +} + +async function testTransactions() { + const mongoClient = await getMongoClient() + const session = mongoClient.startSession() + try { + await session.withTransaction(async () => { + await db.users.findOne({ _id: ObjectId() }, { session }) + }) + } finally { + await session.endSession() + } +} + +main() .then(() => { console.error('Mongodb is up.') process.exit(0) }) .catch(err => { - console.error('Cannot connect to mongodb.') console.error(err) process.exit(1) })