All files / backend/drivers/postgres pool.mjs

100% Statements 69/69
100% Branches 24/24
100% Functions 24/24
100% Lines 54/54

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                                                21x   21x 21x   21x                     24x 21x               117x 229x 229x 26x 26x 5x   96x                 39x                 21x 21x     26x 14x 1x   14x 14x 14x 2x 2x   12x   14x 2x     26x       21x                     10x                 2x 2x 2x   2x                 2x 3x 3x 3x                 2x 2x 2x   2x 1x 1x               1x                   2x 2x 2x       2x 1x     2x                 2x 1x 1x                  
/*
  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.
*/
 
import {Pool} from 'pg';
import cluster from 'node:cluster';
import {isMainThread} from 'node:worker_threads';
import {changeLoggerImpl, getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {mainLogger} from '@back/utils/logger/constLoggers.mjs';
 
// Пул создаётся ещё при импорте модулей - раньше, чем точка входа ставит основной логгер, - поэтому
// ставим его и здесь: повторная установка ни на что не влияет, а настройки пула попадают в лог
changeLoggerImpl(mainLogger);
 
const logger = getLoggerWithTag('b/d/p/pool');
let pool = null;
 
const enableConnectionStat = process.env.VUE_APP_DOCHUB_LOG_POSTGRES_CONNECTION?.toLowerCase() === 'y';
 
/**
 * Тип процесса или потока, в котором создаётся пул. Пул у каждого из них свой, а нагрузка разная,
 * поэтому параметры пула можно задать на тип процесса. Имена типов те же, что в
 * VUE_APP_DOCHUB_CLUSTER_NODE_PARAMS_*:
 *  MAIN - главный процесс (в кластере управляет подом и запросы не обслуживает, в режиме backend он единственный);
 *  WORKER - fork кластера, обслуживает запросы;
 *  RELOAD - поток загрузки манифестов.
 */
export function detectProcessType() {
    if (!isMainThread) return 'RELOAD';
    return cluster.isWorker ? 'WORKER' : 'MAIN';
}
 
/**
 * Читает числовой параметр пула: сначала значение для типа процесса (<name>_<processType>), затем
 * общее (<name>). Пустое и некорректное значение пропускается, как если бы его не задавали.
 */
function readPoolParam(env, name, processType, minValue, defaultValue) {
    for (const envName of [`${name}_${processType}`, name]) {
        const raw = env[envName];
        if (raw === undefined || raw.trim() === '') continue;
        const value = Number(raw);
        if (!isNaN(value) && value >= minValue) return value;
        logger.warn(() => `${envName}=${raw} is ignored: expected a number not less than ${minValue}`);
    }
    return defaultValue;
}
 
/**
 * Собирает настройки пула для типа процесса из переменных окружения
 * @param env - переменные окружения
 * @param processType - тип процесса или потока, см. detectProcessType
 */
export function resolvePoolConfig(env, processType) {
    return {
        'connectionString': env.VUE_APP_DOCHUB_POSTGRES_URL,
        max: readPoolParam(env, 'VUE_APP_POSTGRES_POOL_SIZE', processType, 1, 50),
        idleTimeoutMillis: readPoolParam(env, 'VUE_APP_POSTGRES_IDLE_TIMEOUT_SECONDS', processType, 0, 300) * 1000,
        connectionTimeoutMillis: readPoolParam(env, 'VUE_APP_POSTGRES_CONNECTION_TIMEOUT_SECONDS', processType, 0, 5) * 1000,
        allowExitOnIdle: false // предотвращает закрытие при простое
    };
}
 
const processType = detectProcessType();
const poolConfig = resolvePoolConfig(process.env, processType);
 
export function getPgPool() {
    if (!pool || pool.ending) {
        if (pool?.ending === true) {
            logger.info(() => 'postgres pool was closed by somebody, open new');
        }
        pool = new Pool(poolConfig);
        logger.info(() => `postgres pool for process type ${processType}: max ${poolConfig.max}, idle timeout ${poolConfig.idleTimeoutMillis} ms, connection timeout ${poolConfig.connectionTimeoutMillis} ms`);
        if (enableConnectionStat) {
            logger.debug(() => 'postgres pool metrics enabled');
            setupEventListeners(pool);
        } else {
            logger.debug(() => 'postgres pool metrics disabled. If need, may enabled by VUE_APP_DOCHUB_LOG_POSTGRES_CONNECTION env with "Y" value');
        }
        pool.on('error', (err) => {
            logger.error(() => 'error in pool', err);
        });
    }
    return pool;
}
 
 
const stats = {
    connectionsCreated: 0,      // connect
    connectionsDestroyed: 0,    // remove
    connectionsAcquired: 0,     // acquire
    connectionsReleased: 0,     // release
    errorsCount: 0,             // error
    openedConnection: 0,        // открытые соединения
    connectionInUse: 0          // соединения в использовании
};
 
function getInternalMetrics(pool) {
    return {
        total: pool.totalCount,
        idle: pool.idleCount,
        waiting: pool.waitingCount
    };
}
 
function setupEventListeners(pool) {
    // Создано новое физическое соединение
    pool.on('connect', () => {
        stats.connectionsCreated++;
        stats.openedConnection++;
 
        logger.debug(() => [
            'pg pool create new connect',
            { title: 'event', obj: 'connect' },
            { title: 'stats', obj: { ...stats } },
            { title: 'poolInternal', obj: getInternalMetrics(pool) }
        ]);
    });
 
    // Клиент взят из пула
    pool.on('acquire', () => {
        stats.connectionsAcquired++;
        stats.connectionInUse++;
        logger.debug(() => [
            'pg pool use connect from pool',
            { title: 'event', obj: 'acquire' },
            { title: 'stats', obj: { ...stats } },
            { title: 'poolInternal', obj: getInternalMetrics(pool) }
        ]);
    });
 
    // Клиент возвращен в пул
    pool.on('release', (err) => {
        stats.connectionsReleased++;
        stats.connectionInUse = Math.max(0, stats.connectionInUse - 1);
 
        if (err) {
            stats.errorsCount++;
            logger.debug(() => [
                'pg pool error when release connect',
                { title: 'event', obj: 'release_error' },
                { title: 'error', obj: err.message },
                { title: 'stats', obj: { ...stats } },
                { title: 'poolInternal', obj: getInternalMetrics(pool) }
            ]);
        } else {
            logger.debug(() => [
                'pg pool success release connect',
                { title: 'event', obj: 'release' },
                { title: 'stats', obj: { ...stats } },
                { title: 'poolInternal', obj: getInternalMetrics(pool) }
            ]);
        }
    });
 
    // Соединение удалено из пула
    pool.on('remove', () => {
        stats.connectionsDestroyed++;
        stats.openedConnection = Math.max(0, stats.openedConnection - 1);
 
        // Если соединение было активным при удалении, уменьшаем и активные
        // Но берем Math.max чтобы не уйти в отрицательные, если уже учли в release
        if (stats.connectionInUse > 0) {
            stats.connectionInUse = Math.max(0, stats.connectionInUse - 1);
        }
 
        logger.debug(() => [
            'pg pool close connect',
            { title: 'event', obj: 'remove' },
            { title: 'stats', obj: { ...stats } },
            { title: 'poolInternal', obj: getInternalMetrics(pool) }
        ]);
    });
 
    // Ошибка на клиенте
    pool.on('error', (err) => {
        stats.errorsCount++;
        logger.debug(() => [
            'pg pool error on client when try to connect',
            { title: 'event', obj: 'connection_error' },
            { title: 'error', obj: err.message },
            { title: 'stats', obj: { ...stats } },
            { title: 'poolInternal', obj: getInternalMetrics(pool) }
        ]);
    });
}