Skip to content
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
1 change: 1 addition & 0 deletions QualityControl/common/library/runStatus.enum.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ export const RunStatus = Object.freeze({
ENDED: 'ENDED',
ONGOING: 'ONGOING',
NOT_FOUND: 'NOT_FOUND',
UNKNOWN: 'UNKNOWN',
});
14 changes: 13 additions & 1 deletion QualityControl/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import { layoutOwnerMiddleware } from './middleware/layouts/layoutOwner.middlewa
import { layoutIdMiddleware } from './middleware/layouts/layoutId.middleware.js';
import { layoutServiceMiddleware } from './middleware/layouts/layoutService.middleware.js';
import { statusComponentMiddleware } from './middleware/status/statusComponent.middleware.js';
import { runStatusFilterMiddleware } from './middleware/filters/runStatusFilter.middleware.js';
import { runModeMiddleware } from './middleware/filters/runMode.middleware.js';

/**
* Adds paths and binds websocket to instance of HttpServer passed
Expand Down Expand Up @@ -55,7 +57,12 @@ export const setup = (http, ws) => {
http.get('/object/:id', objectGetByIdValidation, objectController.getObjectById.bind(objectController));
http.get('/object', objectGetContentsValidation, objectController.getObjectContent.bind(objectController));

http.get('/objects', objectsGetValidation, objectController.getObjects.bind(objectController), { public: true });
http.get(
'/objects',
objectsGetValidation,
runModeMiddleware,
objectController.getObjects.bind(objectController),
);

http.get('/layouts', layoutController.getLayoutsHandler.bind(layoutController));
http.get('/layout/:id', layoutController.getLayoutHandler.bind(layoutController));
Expand Down Expand Up @@ -94,4 +101,9 @@ export const setup = (http, ws) => {
http.get('/checkUser', userController.addUserHandler.bind(userController));

http.get('/filter/configuration', filterController.getFilterConfigurationHandler.bind(filterController));
http.get(
'/filter/run-status/:runNumber',
runStatusFilterMiddleware,
filterController.getRunStatusHandler.bind(filterController),
);
};
24 changes: 24 additions & 0 deletions QualityControl/lib/controllers/FilterController.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
* or submit itself to any jurisdiction.
*/

import {
LogManager,
updateAndSendExpressResponseFromNativeError,
}
from '@aliceo2/web-ui';

/**
* Gateaway class to be used to retrieve data with regard to filters
*/
Expand All @@ -25,6 +31,24 @@ export class FilterController {
* @type {FilterService}
*/
this._filterService = filterService;
this._logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'qcg'}/filter-ctrl`);
}

/**
* HTTP GET endpoint for retrieving the status of a run from Bookkeeping
* @param {Request} req - HTTP request
* @param {Response} res - HTTP response to provide run status information
*/
async getRunStatusHandler(req, res) {
try {
const runStatus = await this._filterService.getRunStatus(req.params.runNumber);
res.status(200).json({
runStatus: runStatus,
});
} catch (error) {
this._logger.errorMessage('Error getting run status:', error);
updateAndSendExpressResponseFromNativeError(res, error);
}
}

/**
Expand Down
19 changes: 5 additions & 14 deletions QualityControl/lib/controllers/ObjectController.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* or submit itself to any jurisdiction.
*/
'use strict';
import { InvalidInputError, LogManager, updateAndSendExpressResponseFromNativeError } from '@aliceo2/web-ui';
import { LogManager, updateAndSendExpressResponseFromNativeError } from '@aliceo2/web-ui';

/**
* Gateway for all QC Objects requests
Expand Down Expand Up @@ -48,19 +48,10 @@ export class ObjectController {
try {
const { prefix, fields, filters = {}, inRunMode = false } = req.query;

const { RunNumber: runNumber } = filters;
const parsedRunNumber = parseInt(runNumber, 10);

if (inRunMode && (!runNumber || isNaN(parsedRunNumber))) {
return updateAndSendExpressResponseFromNativeError(
res,
new InvalidInputError(!runNumber
? 'RunNumber is required when in run mode'
: 'RunNumber must be a number'),
);
} else if (inRunMode && runNumber && !isNaN(parsedRunNumber)) {
const { paths, runStatus } = await this._runModeService.retrievePathsAndSetRunStatus(parsedRunNumber, prefix);
return res.status(200).json({ paths, runStatus });
if (inRunMode) {
const runNumber = filters?.RunNumber;
const { paths } = await this._runModeService.retrievePathsAndSetRunStatus(runNumber);
return res.status(200).json({ paths });
}

const objectsData = await this._objService.retrieveLatestVersionOfObjects({
Expand Down
28 changes: 28 additions & 0 deletions QualityControl/lib/dtos/filters/RunNumberDto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @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.
*/

import Joi from 'joi';

export const RunNumberDto = Joi.number()
.required()
.integer()
.min(0)
.max(999999)
.messages({
'any.required': 'Run number is required',
'number.base': 'Run number must be a number',
'number.integer': 'Run number must be an integer',
'number.min': 'Run number must be positive',
'number.max': 'Run number must not exceed 999999',
});
43 changes: 43 additions & 0 deletions QualityControl/lib/middleware/filters/runMode.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* @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.
*/

import { InvalidInputError, updateAndSendExpressResponseFromNativeError } from '@aliceo2/web-ui';
import { RunNumberDto } from '../../dtos/filters/RunNumberDto.js';

/**
* Middleware function to validate the run number if in run mode.
* @param {object} req - The request object.
* @param {object} res - The response object.
* @param {Function} next - The next middleware function in the stack.
* @returns {Promise<void>}
*/
export const runModeMiddleware = async (req, res, next) => {
const { inRunMode = false, filters = {} } = req.query;
if (!inRunMode) {
next();
return;
}
try {
const validatedRunNumber = await RunNumberDto.validateAsync(filters?.RunNumber);
req.query.filters = { ...filters, RunNumber: validatedRunNumber };
next();
} catch (error) {
updateAndSendExpressResponseFromNativeError(
res,
error.isJoi
? new InvalidInputError(error.details[0].message)
: error,
);
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* @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.
*/

import { InvalidInputError, updateAndSendExpressResponseFromNativeError } from '@aliceo2/web-ui';
import { RunNumberDto } from '../../dtos/filters/RunNumberDto.js';

/**
* Middleware function to validate the run number and attach it to the request object.
f
* @param {object} req - The request object.
* @param {object} res - The response object.
* @param {Function} next - The next middleware function in the stack.
* @returns {Promise<void>}
*/
export const runStatusFilterMiddleware = async (req, res, next) => {
try {
const validatedRunNumber = await RunNumberDto.validateAsync(req.params.runNumber);
req.params.runNumber = validatedRunNumber;
next();
} catch (error) {
updateAndSendExpressResponseFromNativeError(
res,
error.isJoi
? new InvalidInputError(error.details[0].message)
: error,
);
}
};
29 changes: 26 additions & 3 deletions QualityControl/lib/services/FilterService.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
*/

import { LogManager } from '@aliceo2/web-ui';
const logger = LogManager.getLogger('filter/service');
import { RunStatus } from '../../common/library/runStatus.enum.js';
const LOG_FACILITY = `${process.env.npm_config_log_label ?? 'qcg'}/filter-svc`;

/**
* High level service that composes, processes and maps data from the bookkeeping service
Expand All @@ -25,14 +26,15 @@ export class FilterService {
* @param {object} config - Config object file that defines the refresh intervals for checking run status and runtypes
*/
constructor(bookkeepingService, config) {
this._logger = LogManager.getLogger(LOG_FACILITY);
this._bookkeepingService = bookkeepingService;
this._runTypes = [];

this._runTypesRefreshInterval = config?.bookkeeping?.runTypesRefreshInterval ??
(config?.bookkeeping ? 24 * 60 * 60 * 1000 : -1);

this.initFilters().catch((error) => {
logger.errorMessage(`FilterService initialization failed: ${error.message || error}`);
this._logger.errorMessage(`FilterService initialization failed: ${error.message || error}`);
});
}

Expand Down Expand Up @@ -61,7 +63,7 @@ export class FilterService {
}
this._runTypes.sort();
} catch (error) {
logger.errorMessage(`Error while retrieving run types: ${error.message || error}`);
this._logger.errorMessage(`Error while retrieving run types: ${error.message || error}`);
this._runTypes = [];
}
}
Expand All @@ -81,4 +83,25 @@ export class FilterService {
get runTypes() {
return [...this._runTypes];
}

/**
* This method is used to retrieve the run status from the bookkeeping service
* @param {number} runNumber - run number to retrieve the status for
* @returns {Promise<string>} - resolves with the run status
*/
async getRunStatus(runNumber) {
try {
const runStatus = await this._bookkeepingService.retrieveRunStatus(runNumber);

if (!runStatus || !Object.values(RunStatus).includes(runStatus)) {
this._logger.warnMessage(`Invalid run status received for run ${runNumber}: ${runStatus}`);
return RunStatus.UNKNOWN;
}
return runStatus;
} catch (error) {
const message = `Error while retrieving run status for run ${runNumber}: ${error.message || error}`;
this._logger.errorMessage(message);
return RunStatus.UNKNOWN;
}
}
}
3 changes: 1 addition & 2 deletions QualityControl/lib/services/RunModeService.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class RunModeService {
async retrievePathsAndSetRunStatus(runNumber) {
if (this._ongoingRuns.has(runNumber)) {
const cachedPaths = parseObjects(this._ongoingRuns.get(runNumber), QCObjectDto);
return { paths: cachedPaths, runStatus: RunStatus.ONGOING };
return { paths: cachedPaths };
}

const runStatus = await this._bookkeepingService.retrieveRunStatus(runNumber);
Expand All @@ -70,7 +70,6 @@ export class RunModeService {

return {
paths: parsedPaths,
runStatus,
};
}

Expand Down
72 changes: 72 additions & 0 deletions QualityControl/test/api/filters/api-get-run-status.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @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.
*/

import { suite, test } from 'node:test';
import { URL_ADDRESS, OWNER_TEST_TOKEN } from '../config.js';
import request from 'supertest';

export const apiGetRunStatusTests = () => {
suite('GET /filter/run-status/:runNumber', () => {
test('should return a 403 error if no authentication token is provided', async () => {
await request(`${URL_ADDRESS}/api/filter/run-status/123456`)
.get('')
.expect(403);
});

test('should return a 404 error if run number is not provided', async () => {
await request(`${URL_ADDRESS}/api/filter/run-status/`)
.get(`?token=${OWNER_TEST_TOKEN}`)
.expect(404, {
error: '404 - Page not found',
message: 'The requested URL was not found on this server.',
});
});

test('should return a 400 error for invalid run number (negative)', async () => {
await request(`${URL_ADDRESS}/api/filter/run-status/-1`)
.get(`?token=${OWNER_TEST_TOKEN}`)
.expect(400, {
message: 'Run number must be positive',
status: 400,
title: 'Invalid Input',
});
});

test('should return a 400 error for invalid run number (too large)', async () => {
await request(`${URL_ADDRESS}/api/filter/run-status/1000000`)
.get(`?token=${OWNER_TEST_TOKEN}`)
.expect(400, {
message: 'Run number must not exceed 999999',
status: 400,
title: 'Invalid Input',
});
});

test('should return a 400 error for invalid run number (not a number)', async () => {
await request(`${URL_ADDRESS}/api/filter/run-status/invalid`)
.get(`?token=${OWNER_TEST_TOKEN}`)
.expect(400, {
message: 'Run number must be a number',
status: 400,
title: 'Invalid Input',
});
});

test('should successfully get run status for valid run number', async () => {
await request(`${URL_ADDRESS}/api/filter/run-status/123456`)
.get(`?token=${OWNER_TEST_TOKEN}`)
.expect(200);
});
});
};
Loading