All files / backend/helpers request.mjs

95.93% Statements 118/123
97.29% Branches 108/111
70.58% Functions 12/17
99.15% Lines 117/118

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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                                                                                                135x 135x 135x 135x   135x 1x     135x   1x 134x   1x                 40x 40x 40x 40x 40x 34x 34x   40x       135x   88x 87x 85x 85x 85x 85x 8x 77x     67x 10x 5x   19x       69x             152x 152x       135x 135x 135x       171x 171x 171x 129x 42x 9x 33x 9x 24x 9x   171x           126x 126x 116x 10x 3x 7x 2x     21x 21x     5x               261x 261x   261x 261x 9x   252x   261x   261x   152x 152x 152x 3x   149x 149x 7x 7x     142x 9x   133x 131x       119x 119x       109x 106x 106x 12x 12x 12x 10x 10x 10x   2x 2x 2x       2x 2x   94x       32x 15x 15x 15x 15x         17x   94x     3x 1x     2x 1x     1x       135x                         135x               21x 21x         21x   21x 21x 21x 8x           13x              
/*
  Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
 
  Copyright (C) 2022 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
 
  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project
 
  https://dochub.info
 
  The use of this product or its derivatives for any purpose cannot be a secret.
 
 
  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.
 
  Maintainers:
      R.Piontik <r.piontik@mail.ru>
 
  Contributors:
	  R.Piontik <r.piontik@mail.ru> - 2023
	  R.Piontik <r.piontik@mail.ru> - 2024
*/
 
import path from 'path';
import fs from 'fs';
import axios from 'axios';
import yaml from 'yaml';
import uriTool from './uri.mjs';
import gitlab from './gitlab.mjs';
import bitbucket from './bitbucket.mjs';
import { performanceLogger } from '../utils/logger/index.mjs';
import xml from '@global/helpers/xmlparser.mjs';
import './env.mjs';
import https from 'node:https';
import http from 'node:http';
import { hasStaticEtag } from '../helpers/env.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
 
const DEFAULT_REQUEST_TIMEOUT = 60000;
const MAX_REQUEST_TIMEOUT = 300000;
const REQUEST_TAG = 'request';
const logger = getLoggerWithTag(REQUEST_TAG);
 
if (global.$httpRepeater.maxSockets) {
    https.globalAgent.maxSockets = http.globalAgent.maxSockets = global.$httpRepeater.maxSockets;
}
 
if (process.env.VUE_APP_DOCHUB_GITLAB_URL) {
    // Подключаем интерцептор авторизации GitLab
    axios.interceptors.request.use(gitlab.axiosInterceptor);
} else if (process.env.VUE_APP_DOCHUB_BITBUCKET_URL) {
    // Подключаем интерцептор авторизации BitBucket
    axios.interceptors.request.use(bitbucket.axiosInterceptor);
}
 
// Помечает ошибку разборщика (YAML/JSON/XML) признаком isParseError. По нему загрузчик отличает
// ошибку содержимого файла от сетевой: ошибка разбора не повторяется и регистрируется как syntax
// Разборщик YAML кладёт linePos только в режиме prettyErrors (он же дописывает в message фрагмент кода),
// поэтому позицию считаем сами по смещению ошибки в тексте, а message оставляем как есть.
// Смещение разборщик отсчитывает в тексте, где \r\n и \r уже заменены на \n, так что считаем в нём же
function markParseError(e, url, text) {
    const error = e instanceof Error ? e : new Error(String(e));
    error.isParseError = true;
    error.parseUri = url;
    const offset = error.source?.range?.start;
    if (!error.linePos && typeof text === 'string' && Number.isInteger(offset) && offset >= 0) {
        const before = text.replace(/\r\n?/g, '\n').slice(0, offset);
        error.linePos = {start: {line: before.split('\n').length, col: offset - before.lastIndexOf('\n')}};
    }
    return error;
}
 
// Здесь разбираемся, что к нам вернулось из запроса и преобразуем к формату внутренних данных
axios.interceptors.response.use(
    (response) => {
        if (typeof response.data === 'string') {
            if (!response.config.raw) {
                const mimeType = response.headers['content-type'];
                const url = response.config.url.split('?')[0].toLowerCase();
                try {
                    if (['application/json', 'text/json'].includes(mimeType) || url.endsWith('.json/raw') || url.endsWith('.json'))
                        response.data = JSON.parse(response.data);
                    else if (['application/yaml', 'application/x-yaml', 'text/yaml', 'text/x-yaml'].includes(mimeType)
                        || url.endsWith('.yaml/raw') || url.endsWith('.yaml')
                        || url.endsWith('.yml/raw') || url.endsWith('.yml'))
                        response.data = yaml.parse(response.data);
                    else if (['application/xml', 'text/xml'].includes(mimeType) || url.endsWith('.xml/raw') || url.endsWith('.xml'))
                        response.data = xml.parse(response.data);
                } catch (e) {
                    throw markParseError(e, response.config.url, response.data);
                }
            }
        }
        return response;
    }
);
 
// Проверяет разрешен ли путь к файлу
function isAvailablePath(filePath) {
    // eslint-disable-next-line no-undef
    const relative = path.relative($paths.file_storage, filePath);
    return relative !== '' && relative !== '..'
        && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
}
 
const CONTENT_TYPE_YAML = 'application/x-yaml';
const CONTENT_TYPE_JSON = 'application/json';
const CONTENT_TYPE_XML = 'application/xhtml+xml';
 
// Определяет тип контента
function getContentType(url, result) {
    let contentType = null;
    const uri = url.split('?')[0];
    if (uri.endsWith('.yaml') || uri.endsWith('.yml') || uri.endsWith('.yaml/raw') || uri.endsWith('.yml/raw')) {
        contentType = CONTENT_TYPE_YAML;
    } else if (uri.endsWith('.json') || uri.endsWith('.json/raw')) {
        contentType = CONTENT_TYPE_JSON;
    } else if (uri.endsWith('.xml') || uri.endsWith('.xml/raw')) {
        contentType = CONTENT_TYPE_XML;
    } else if (result) {
        contentType = result?.headers?.['content-type'] ?? null;
    }
    return contentType;
}
 
// Разбирает содержимое файла по типу контента. Ошибка разборщика пробрасывается (isParseError),
// как и при чтении по HTTP. Файлы, которые не должны разбираться, читаются с raw: true
function parseFileData(contentType, fileData, url) {
    try {
        if (contentType === CONTENT_TYPE_YAML) {
            return yaml.parse(fileData);
        } else if (contentType === CONTENT_TYPE_JSON) {
            return JSON.parse(fileData);
        } else if (contentType === CONTENT_TYPE_XML) {
            return xml.parse(fileData);
        }
    } catch (e) {
        logger.debug(() => `Can't parse content type ${contentType} of ${url}: ${e.message}`);
        throw markParseError(e, url, fileData);
    }
 
    return fileData;
}
 
// Выполняет запрос по URL
//  url         - ссылка на ресурс
//  baseUIR     - базовый URI 
//  response    - Express response. Если установлен, то запрос будет работать как прокси.
async function request(url, baseURI, response, params = {}, attempt = 0) {
    const requestLogger = attempt === 0 ? performanceLogger?.getRequestLogger(url) : null;
    requestLogger?.setStart();
    // Разбираем URL
    let uri = null;
    if (baseURI) {
        uri = uriTool.makeURL(url, baseURI).url;
    } else {
        uri = new URL(url);
    }
    logger.trace(() => `request ro url ${uri}`);
    // Если локальное файловое хранилище
    if (uri.protocol === 'file:') {
        // eslint-disable-next-line no-undef
        const fileName = path.join($paths.file_storage, decodeURIComponent(uri.pathname));
        logger.trace(() => `request file with name ${fileName}`);
        if (!isAvailablePath(fileName)) {
            throw `File [${fileName}] is not available.`;
        }
        const contentType = getContentType(fileName);
        if (response) {
            contentType && response.setHeader('content-type', contentType);
            return response.sendFile(fileName, {etag: hasStaticEtag});
        } else {
            let result;
            if (params.responseType === 'arraybuffer') {
                result = { data: fs.readFileSync(fileName) };
            } else {
                const fileData = fs.readFileSync(fileName, {encoding: 'utf8', flag: 'r'});
                result = {
                    data: params.raw ? fileData : parseFileData(contentType, fileData, uri.toString())
                };
            }
            requestLogger?.setEnd();
            return result;
        }
    }
    // Если запрос по http / https
    else if ((uri.protocol === 'http:') || (uri.protocol === 'https:')) {
        const url = uri.toString();
        if (response) {
            let result = null;
            try {
                result = await axios({url, responseType: 'stream', ...params}).finally(() => requestLogger?.setEnd());
                const contentType = getContentType(url, result);
                contentType && response.setHeader('content-type', contentType);
                return result.data.pipe(response);
            } catch (e) {
                logger.error(() => `Error of request [${url}] with error [${e.message}]`);
                response.status(e?.response?.status || 500);
                response.json({
                    error: 'Error of request to original source.'
                });
            }
            requestLogger?.setEnd();
            return result;
        } else
            return await axios({url, ...params})
                // Кетч добавлен из-за проблем с BitBucket.
                .catch((err) => {
                    // Ошибка разбора - дефект содержимого файла, повтор запроса её не исправит
                    if (!err?.isParseError && err?.response?.status !== 404 && attempt < global.$httpRepeater.maxRetries) {
                        return new Promise((resolve) => {
                            const timeout = Math.min((params?.timeout || DEFAULT_REQUEST_TIMEOUT) * ++attempt, MAX_REQUEST_TIMEOUT);
                            setTimeout(
                                () => resolve(request(url, baseURI, response, {...params, timeout}, attempt)),
                                Math.floor(Math.random() * (3000 + 3000 * attempt) + 1500)
                            );
                        });
                    }
                    return Promise.reject(err);
                })
                .finally(() => requestLogger?.setEnd());
    }
    // Если запрос к GitLab
    else if (uri.protocol === 'gitlab:') {
        return request(uriTool.makeURL(uri).url, baseURI, response, params);
    }
    // Если запрос к BitBucket
    else if (uri.protocol === 'bitbucket:') {
        return request(uriTool.makeURL(uri).url, baseURI, response, params);
    }
    // eslint-disable-next-line no-console
    throw `Can not processing protocol [${uri.protocol}] for url=[${url}]`;
}
 
// Типы контента по расширению файла, которые не определяет getContentType
const CONTENT_TYPES_BY_EXTENSION = {
    svg: 'image/svg+xml',
    png: 'image/png',
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    gif: 'image/gif',
    bmp: 'image/bmp',
    webp: 'image/webp',
    ico: 'image/x-icon',
    pdf: 'application/pdf'
};
 
// Признак бинарного контента по content-type
const BINARY_CONTENT_TYPE_PATTERN = /^(image\/(?!svg)|audio\/|video\/|font\/|application\/(pdf|octet-stream|zip))/i;
 
// Возвращает содержимое ресурса без разбора и его content-type,
// так же как при проксировании запроса (см. response в request).
// Бинарный контент возвращается в base64 с признаком encoding = 'base64'
//  url         - ссылка на ресурс
//  baseUIR     - базовый URI
export async function requestRaw(url, baseURI) {
    const target = baseURI ? uriTool.makeURL(url, baseURI).url : new URL(url);
    const result = await request(url, baseURI, null, {
        raw: true,
        responseType: 'arraybuffer',
        transformResponse: [(data) => data]
    });
    const extension = target.pathname.split('.').pop().toLowerCase();
    // Расширение надежнее заголовка: git-серверы могут отдавать картинки как text/plain
    const contentType = CONTENT_TYPES_BY_EXTENSION[extension] || getContentType(target.toString(), result) || null;
    const data = Buffer.from(result.data);
    if (BINARY_CONTENT_TYPE_PATTERN.test(contentType || '')) {
        return {
            data: data.toString('base64'),
            contentType,
            encoding: 'base64'
        };
    }
    return {
        data: data.toString('utf8'),
        contentType
    };
}
 
export default request;