From c5562483aa611be8c6c6985ec1da80e9d1224b7e Mon Sep 17 00:00:00 2001 From: GCHQDeveloper36 <73173408+GCHQDeveloper36@users.noreply.github.com> Date: Tue, 30 Apr 2024 21:26:42 +0000 Subject: [PATCH] Only use transactions on replica sets --- backend/src/services/model.ts | 26 ++++++++++++++++---------- backend/src/utils/database.ts | 5 +++++ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/backend/src/services/model.ts b/backend/src/services/model.ts index 63fa1db74..f846bf20c 100644 --- a/backend/src/services/model.ts +++ b/backend/src/services/model.ts @@ -10,6 +10,7 @@ import ModelCardRevisionModel, { ModelCardRevisionDoc } from '../models/ModelCar import { UserInterface } from '../models/User.js' import { GetModelCardVersionOptions, GetModelCardVersionOptionsKeys, GetModelFiltersKeys } from '../types/enums.js' import { isValidatorResultError } from '../types/ValidatorResultError.js' +import { isReplicaSet } from '../utils/database.js' import { toEntity } from '../utils/entity.js' import { BadReq, Forbidden, InternalError, NotFound } from '../utils/error.js' import { convertStringToId } from '../utils/id.js' @@ -224,16 +225,21 @@ export async function _setModelCard( const revision = new ModelCardRevisionModel({ ...newDocument, modelId, createdBy: user.dn }) - const message = 'Unable to save model card revision' - await mongoose.connection - .transaction(async function executeUpdate(session) { - await revision.save({ session }) - await ModelModel.updateOne({ id: modelId }, { $set: { card: newDocument } }, { session: session }) - }) - .catch((error) => { - log.error('Error when updating model card/revision. Transaction rolled back.', error) - throw InternalError(message, { modelId }) - }) + if (await isReplicaSet()) { + await mongoose.connection + .transaction(async function executeUpdate(session) { + await revision.save({ session }) + await ModelModel.updateOne({ id: modelId }, { $set: { card: newDocument } }, { session: session }) + }) + .catch((error) => { + const message = 'Unable to save model card revision' + log.error('Error when updating model card/revision. Transaction rolled back.', error) + throw InternalError(message, { modelId }) + }) + } else { + await revision.save() + await ModelModel.updateOne({ id: modelId }, { $set: { card: newDocument } }) + } return revision } diff --git a/backend/src/utils/database.ts b/backend/src/utils/database.ts index aae04ddc6..45b0363ea 100644 --- a/backend/src/utils/database.ts +++ b/backend/src/utils/database.ts @@ -31,6 +31,11 @@ export async function connectToMongoose() { } } +export async function isReplicaSet(): Promise { + const options = mongoose.connection.getClient().options + return Object.prototype.hasOwnProperty.call(options, 'replicaSet') && options.replicaSet.length > 0 +} + export async function disconnectFromMongoose() { await mongoose.disconnect() log.info({ log: false }, 'Disconnected from Mongoose')