Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/lib/database/DatabaseManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const path = require('path')
const config = require('../../config');
const modelsFactory = require('./models');
const repositoriesFactory = require('./repositories');
const cls = require('cls-hooked');

/**
* Sequelize implementation of the Database.
Expand All @@ -26,6 +27,8 @@ class DatabaseManager {
constructor() {
this.logger = new Log(DatabaseManager.name);
this.schema = 'public';
const o2rct_namespace = cls.createNamespace('o2rct-namespace');
Sequelize.useCLS(o2rct_namespace);

this.sequelize = new Sequelize({
...config.database,
Expand Down
78 changes: 77 additions & 1 deletion app/lib/database/repositories/Repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,23 @@
* or submit itself to any jurisdiction.
*/

const { throwWrapper, NotFoundEntityError } = require('../../utils');

const nonTransactionalFunctions = new Set(['constructor', 'asT', '_asT'])

const getTransactionalMethodsNames = (classObj, ) => {
const classesStack = [];
while (typeof Object.getPrototypeOf(classObj) !== 'object') {
classesStack.push(classObj);
classObj = Object.getPrototypeOf(classObj);
}

return classesStack
.map(cl => Object.getOwnPropertyNames(cl.prototype))
.flat()
.filter(name => ! nonTransactionalFunctions.has(name));
}

/**
* Sequelize implementation of the Repository.
*/
Expand All @@ -31,12 +48,71 @@ class Repository {
/**
* Returns all entities.
*
* @param {Object} queryClauses the find query (see sequelize findAll options) or a find query builder
* @param {Object} queryClauses the find query (see sequelize findAll options)
* @returns {Promise<array>} Promise object representing the full mock data
*/
async findAll(queryClauses = {}) {
return this.model.findAll(queryClauses);
}

/**
* Returns one entity.
*
* @param {Object} queryClauses the find query (see sequelize findOne options)
* @returns {Promise<Object>} Promise object representing the full mock data
*/
async findOne(queryClauses = {}) {
return this.model.findOne(queryClauses);
}

/**
* Apply a patch on a given dbObject and save the dbObject to the database
*
* @param {Object} dbOject the database object on which to apply the patch
* @param {Object} patch the patch to apply
* @return {Promise<void>} promise that resolves when the patch has been applied
*/
async updateOne(dbOject, patch) {
return dbOject.update(patch);
}

/**
* Find a dbObject using query clause, apply given patch to it and save the dbObject to the database
*
* @param {Object} dbOject the database object on which to apply the patch
* @param {Object} patch the patch to apply
* @throws {NotFoundEntityError} if cannot find dbObject with given query clause
* @return {Promise<void>} promise that resolves when the patch has been applied
*/
async findOneAndUpdate(query, patch) {
const entity = await this.model.findOne(query) ??
throwWrapper(new NotFoundEntityError(`No entity of model ${this.model.name} for clause ${JSON.stringify(query)}`));
await entity.update(patch);
}

_asT(customOptions) {
const { sequelize } = this.model;
getTransactionalMethodsNames(this.constructor).forEach(transactionalMethodName => {
const boundMethodWithoutTransaction = this[transactionalMethodName].bind(this);
this[transactionalMethodName] = async (...args) =>
sequelize.transaction(customOptions, async (t) => {
return await boundMethodWithoutTransaction(...args);
});
});
}

/**
* Create copy of repository object which all business related methods are wrapped with sequelize.transcation(),
* e.g: Repository.asT().findAll() is equal to sequelize.transaction((t) => Repository.findAll())
* Module cls-hooked handles passing transaction object to sequelize queries automatically.
* @property {Object} customOptions - options passed to sequelize.transaction(options, callback)
* @returns {Repository}
*/
asT(customOptions) {
const instanceWithTransactions = new this.constructor(this.model);
instanceWithTransactions._asT(customOptions);
return instanceWithTransactions;
}
}

module.exports = Repository;
2 changes: 2 additions & 0 deletions app/lib/database/repositories/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const validateSpecificRepositoriesConfiguration = (models) => {

/**
* Instantiate sequelize models repositories according to repositiry pattern.
* Each Repository Object has transactional version of itself under field 'T' @see {Repository.asT}. Those versions use global sequelize options for transactions.
* @param {Object<string, Sequelize.Model>} models dict: modelName -> sequelize model, @see specificallyDefinedRepositories
* @returns {Object<string, Repository>} dict: repositoryName -> repository instance per one model, (repositoryName = modelName + 'Repository')
*/
Expand All @@ -51,6 +52,7 @@ const repositoriesFactory = (models) => {
[modelName + 'Repository',
new (specificallyDefinedRepositories[modelName] ?? Repository) (model),
]);
modelNameToRepository.forEach(([_, repository]) => { repository.T = repository.asT() });

return Object.fromEntries(modelNameToRepository);
};
Expand Down
23 changes: 23 additions & 0 deletions app/lib/server/controllers/run.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,32 @@ const listRunsPerSimulationPassHandler = async (req, res, next) => {
}
};

const updateRunDetectorQualityHandler = async (req, res) => {
const customDTO = stdDataRequestDTO.keys({
params: {
runNumber: Joi.number(),
detectorSubsystemId: Joi.number(),
},
query: {
quality: Joi.string().required(),
},
});

const validatedDTO = await validateDtoOrRepondOnFailure(customDTO, req, res);
if (validatedDTO) {
await runService.updateRunDetectorQuality(
validatedDTO.params.runNumber,
validatedDTO.params.detectorSubsystemId,
validatedDTO.query.quality,
);
res.end();
}
};

module.exports = {
listRunsHandler,
listRunsPerPeriodHandler,
listRunsPerDataPass,
listRunsPerSimulationPassHandler,
updateRunDetectorQualityHandler,
};
6 changes: 6 additions & 0 deletions app/lib/server/routers/run.router.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,11 @@ module.exports = {
controller: RunController.listRunsHandler,
description: 'List all runs which are present in DB',
},
{
method: 'patch',
path: '/:runNumber/detector-subsystems/:detectorSubsystemId',
controller: RunController.updateRunDetectorQualityHandler,
description: 'Update run/detectorSubsystem based quality',
},
],
};
12 changes: 12 additions & 0 deletions app/lib/services/runs/RunService.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {
databaseManager: {
repositories: {
RunRepository,
RunDetectorsRepository,
},
models: {
DataPass,
Expand Down Expand Up @@ -107,6 +108,17 @@ class RunService {
});
return runs.map((run) => runAdapter.toEntity(run));
}

async updateRunDetectorQuality(runNumber, detectorId, newQuality) {
const queryClause = {
where: {
run_number: runNumber,
detector_id: detectorId,
},
};
const patch = { quality: newQuality };
await RunDetectorsRepository.T.findOneAndUpdate(queryClause, patch);
}
}

module.exports = {
Expand Down
19 changes: 19 additions & 0 deletions app/lib/utils/errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @license
* Copyright 2019-2020 CERN and copyright holders of ALICE O2.
* See http://alice-o2.web.cern.ch/copyright for details of the copyright holders.
* All rights not expressly granted are reserved.
*
* This software is distributed under the terms of the GNU General Public
* License v3 (GPL Version 3), copied verbatim in the file "COPYING".
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/

class NotFoundEntityError extends Error {}

module.exports = {
NotFoundEntityError,
};
2 changes: 2 additions & 0 deletions app/lib/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ const LogsStacker = require('./LogsStacker.js');
const objUtils = require('./obj-utils.js');
const ResProvider = require('./ResProvider.js');
const sqlUtils = require('./sql-utils.js');
const errors = require('./errors.js');

module.exports = {
ResProvider,
LogsStacker,
...sqlUtils,
...httpUtils,
...objUtils,
...errors,
};
58 changes: 58 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"homepage": "https://github.com/AliceO2Group/RunConditionTable#readme",
"dependencies": {
"@aliceo2/web-ui": "^2.0.0",
"cls-hooked": "^4.2.2",
"csvtojson": "^2.0.10",
"deepmerge": "^4.3.1",
"esm": "^3.2.25",
Expand Down Expand Up @@ -88,6 +89,7 @@
],
"bundleDependencies": [
"@aliceo2/web-ui",
"cls-hooked",
"deepmerge",
"esm",
"joi",
Expand Down
33 changes: 33 additions & 0 deletions test/database/Repository.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @license
* Copyright CERN and copyright holders of ALICE O2. This software is
* distributed under the terms of the GNU General Public License v3 (GPL
* Version 3), copied verbatim in the file "COPYING".
*
* See http://alice-o2.web.cern.ch/license for full licensing information.
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
const { databaseManager: { repositories } } = require('../../app/lib/database/DatabaseManager.js');
const assert = require('assert');

module.exports = () => {
describe('RepositoriesSuite', () => {
describe('testing if transaction methods give the same result as non-transactional ones', () => {
const testableMethodNames = new Set(['count', 'findAll', 'findOne']);
Object.values(repositories).map((repo) =>
describe(`${repo.model.name}Repository`, () => Object.getOwnPropertyNames(repo.T)
.filter(n => testableMethodNames.has(n))
.map((methodName) => {
it(`should acquire the same result from transaction and non-transactional method #${methodName}`, async () => {
const nonTransactionResult = await repo[methodName]();
const transationResult = await repo.T[methodName]();
assert.deepStrictEqual(nonTransactionResult, transationResult);
})
}))
);
});
});
};
Loading