All files / backend/storage problems-registry.mjs

95% Statements 19/20
100% Branches 8/8
80% Functions 4/5
100% Lines 17/17

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                                                  2x   2x                                 80x           80x 80x 25x   55x               161x 161x 161x     28x 28x 25x   3x   28x   133x 133x    
/*
  Copyright (C) 2026 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.
*/
 
// Регистр ошибок загрузки («Проблемы») и запрос к источнику с регистрацией ошибок.
// Вынесено из cache.mjs (у него top-level await и PostgreSQL, jest его не загружает), чтобы логика
// ошибок проверялась настоящим кодом. Функции работают через this кэша: this.errors - регистр ошибок.
 
import md5 from 'md5';
import request from '../helpers/request.mjs';
import {describeParseError} from '../helpers/parse-error.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
 
const logger = getLoggerWithTag('manifest-cache');
 
export const errorType = {
    system: 'Внутрисистемная ошибка',
    syntax: 'Синтаксическая ошибка',
    net: 'Сетевая ошибка',
    // Дубль импорта и дефекты $package - одна группа, как во фронтовом парсере плагинов
    package: 'Ошибки пакетов и импортов',
    core: 'Ошибка ядра'
};
 
// Регистрирует ошибку
// type         - Секция ошибки (system/syntax/net/package/core)
// uid          - Уникальный идентификатор ошибки. Ошибка с тем же uid в той же секции повторно не добавляется.
// title        - Определяет представление ошибки в дереве.
// location     - URL с расположением объекта, где выявлена ошибка.
// correction   - Краткое пояснение, как исправить ошибку.
// description  - Описание причины ошибки.
export function registerError(type, uid, title, location, correction, description) {
    !this.errors[type] && (this.errors[type] = {
        id: `$error.${type}`,
        title: errorType[type] || 'Неизвестная ошибка',
        items: []
    });
    // В лог пишем каждое обращение, в «Проблемах» повтор с тем же uid не нужен
    logger.error(() => `${title}: ${description} [${location}]`);
    if (this.errors[type].items.some((item) => item.uid === uid)) {
        return;
    }
    this.errors[type].items.push({
        uid, title, location, correction, description
    });
}
 
// Выполняет запрос к данным. Ошибку содержимого файла (YAML/JSON) регистрирует как syntax,
// остальные ошибки - как net
export async function requestWithErrors(url) {
    let result = null;
    try {
        result = await request(url);
    } catch(e) {
        // url бывает объектом URL (файл ролей v1): в «Проблемах» адрес должен быть строкой
        const location = String(url);
        if (e?.isParseError) {
            this.registerError('syntax', md5(location), location, location, 'Исправьте ошибку в файле', describeParseError(e));
        } else {
            this.registerError('net', md5(location), 'Request error', location, 'See details in error log of backed server', e.message);
        }
        throw e;
    }
    logger.debug(() => `Source [${url}] is imported.`);
    return result;
}