All files / backend/helpers recalculate-datasets.mjs

90.38% Statements 47/52
81.25% Branches 13/16
54.54% Functions 6/11
100% Lines 47/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108                                        1x 1x     10x 10x 1x   9x         5x 5x         5x 5x 5x     8x 8x             5x 5x   3x 2x   3x 3x   3x         6x 1x   5x 4x   5x 10x   10x 10x 10x 10x 10x 4x     10x 4x 4x   4x 4x   6x 6x   1x 1x 1x   1x 1x 1x       5x   5x    
/*
  Copyright (C) 2023 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import generateDatasetErrorDesc from '@global/helpers/generate-dataset-error-desc.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import { v4 as uuidv4 } from 'uuid';
 
const LOG_TAG = 'datasets-calculate';
const logger = getLoggerWithTag(LOG_TAG);
 
function datasetOriginsAsArray(datasetDefinition) {
    const origin = datasetDefinition.origin;
    if (typeof origin === 'object') {
        return Object.values(origin);
    } else {
        return [origin];
    }
}
 
export default async function recalculateDatasetsBackend(manifest, driver, processedDatasets) {
    logger.debug(() => 'Datasets warm up started');
    const problems = {
        id: 'dataset--problems',
        title: 'Datasets',
        items: []
    };
    const registeredProblems = new Set();
    let recalculateCounter = 0;
    const datasetsWithError = {};
 
    function registerProblem(datasetKey, description) {
        registeredProblems.add(datasetKey);
        problems.items.push({
            uid: datasetKey,
            description: description
        });
    }
 
    async function calcDataset(key) {
        recalculateCounter++;
        return await driver.getData(manifest, { origin: key, source: '($)' }, undefined, undefined, datasetsWithError)
            .catch((err) => {
                if(!datasetsWithError[key]) {
                    datasetsWithError[key] = {error: err};
                }
                Eif (!registeredProblems.has(key)) {
                    registerProblem(key, generateDatasetErrorDesc(key, err, datasetsWithError, manifest));
                }
                logger.error(() => `Dataset ${key} warm up failed`, err);
            });
    }
    
    async function handleDataset(processedDatasets, key) {
        if (processedDatasets[key]) {
            return;
        }
        await calcDataset(key);
        processedDatasets[key] = true;
    }
    for (const key of Object.keys(manifest.datasets)) {
        logger.debug(() => `Processing dataset ${key}`);
 
        const datasetDefinition = manifest.datasets[key];
        const datasetOrigins = datasetOriginsAsArray(datasetDefinition);
        const originsWithError = [];
        for (const origin of datasetOrigins) {
            if (registeredProblems.has(origin)) {
                originsWithError.push(origin);
            }
        }
        if (originsWithError.length !== 0) {
            Eif(!datasetsWithError[key]) {
                datasetsWithError[key] = {error: {message: 'Ошибки в датасетах, указанных в origin'}};
            }
            registerProblem(key, generateDatasetErrorDesc(key, 'Ошибки в датасетах, указанных в origin', datasetsWithError, manifest));
            continue;
        }
        try {
            await handleDataset(processedDatasets, key);
        } catch (err) {
            let customMessage = '';
            Eif (err.name === 'RangeError') {
                customMessage = 'The calculated dataset result is too large to process (RangeError)';
            }
            const errorUuid = uuidv4();
            logger.error(() => `${errorUuid}: Failed handleDataset of dataset: ${key}. ${customMessage}`, err);
            registerProblem(key, `Датасет ${key} не удалось рассчитать из-за ошибки. uuid = ${errorUuid}`);
        }
    }
 
    logger.debug(() => `Пересчитано ${recalculateCounter} датасетов из ${Object.keys(manifest.datasets).length}.`);
 
    return problems;
}