All files / backend/cluster cache.mjs

80.43% Statements 148/184
100% Branches 50/50
44.61% Functions 29/65
100% Lines 146/146

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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355                                                                    70x 70x   70x 70x   70x 70x     70x       74x     4x 4x   1x         27x 27x   1x   1x       29x 29x 29x   1x         2x 2x   1x   1x       2x 2x   1x         3x 3x   1x         2x 2x 2x   1x         2x 2x 1x   1x         2x       2x 2x 2x 1x   1x         1x       2x 2x 1x   1x                 3x       3x         2x               5x         1x 2x   1x         3x 3x   1x 1x         15x 15x   13x 2x 2x         2x 2x 2x 11x 9x 4x         4x 4x   5x 5x 5x 5x 1x 1x 4x 2x   5x 3x   5x 5x     2x     2x 2x 1x     1x         2x 2x 1x 1x   1x           26x 26x   1x 1x 1x                 26x 26x   1x 1x 1x         6x 6x 6x 6x     5x 5x 3x 3x     2x   1x 1x     1x     2x   6x       3x 1x   3x 3x   2x 2x 1x 1x   1x     1x 1x         73x   1x 1x   70x 70x 70x   2x 2x 2x       70x 1x 1x 1x         30x 1x   29x 29x      
/*
  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 postgres from '../drivers/postgres.mjs';
import {
    CLUSTER_ALL_MANIFEST_ACTUAL_TIME_KEY,
    CLUSTER_COMMAND_REFRESH_TIMESTAMP,
    CLUSTER_LOAD_CYCLE_KEY,
    CLUSTER_MANIFEST,
    CLUSTER_MANIFEST_META,
    CLUSTER_MANIFEST_UPDATE_TIME_KEY,
    CLUSTER_MASTER_COMMAND,
    CLUSTER_MASTER_COMMAND_STATE,
    CLUSTER_MASTER_INFO,
    CLUSTER_MASTER_INFO_PROBE, CLUSTER_ROOT_MANIFEST_DATA,
    NodeStatus
} from './constants.mjs';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {v4 as uuidv4} from 'uuid';
import {collectActualCacheHashes} from '@back/helpers/cachePrefixByDomain.mjs';
 
const LOG_TAG = 'cluster-cache';
const logger = getLoggerWithTag(LOG_TAG);
 
const CLUSTER_MASTER_TIMEOUT = 60000;
const MASTER_SET_CHECK = 2;
 
const datalakeCacheMode = process.env.VUE_APP_DOCHUB_DATALAKE_CACHE;
let cacheDriver = null;
 
//редис удален в задаче ERA-1986 03.2026 спустя какое-то время эту проверку можно будет убрать как и остальные упоминания редиса
const redisUnsupportedMessage = `redis cache now not supported, check env VUE_APP_DOCHUB_DATALAKE_CACHE, current value ${datalakeCacheMode}`;
 
export class ClusterCache {
 
    isClusterCache = true;
 
    async updateCommandState(state) {
        try {
            await cacheDriver.setGuaranteed(CLUSTER_MASTER_COMMAND_STATE, state);
        } catch (error) {
            logger.error(() => `Update command state ${state} in cache failed. Error ${error}`);
        }
    }
 
    async getRootManifestData() {
        try {
            return JSON.parse(await cacheDriver.get(CLUSTER_ROOT_MANIFEST_DATA));
        } catch (error) {
            logger.warn(() => `Get root manifest data from cache failed, check value in cache by key '${CLUSTER_ROOT_MANIFEST_DATA}'`, error);
        }
        return undefined;
    }
 
    async setRootManifestData(rootData) {
        logger.info(() => 'set manifest root data');
        try {
            await cacheDriver.setGuaranteed(CLUSTER_ROOT_MANIFEST_DATA, JSON.stringify(rootData));
        } catch (error) {
            logger.error(() => 'Update root data in cache failed', error);
        }
    }
 
    async getCommandState() {
        try {
            return await cacheDriver.get(CLUSTER_MASTER_COMMAND_STATE);
        } catch (error) {
            logger.warn(() => `Get command state from cache failed. Error ${error}`);
        }
        return undefined;
    }
 
    async setInfoProbeState(state, nodeId) {
        try {
            await cacheDriver.setGuaranteed(CLUSTER_MASTER_INFO_PROBE + nodeId, JSON.stringify(state));
        } catch (error) {
            logger.error(() => `Update info in cache failed. Error ${error}`);
        }
    }
 
    async getInfoProbeState(nodeId) {
        try {
            return JSON.parse(await cacheDriver.get(CLUSTER_MASTER_INFO_PROBE + nodeId));
        } catch (error) {
            logger.error(() => `Get info from cache failed. Error ${error}`);
        }
    }
 
    async getAllManifestState() {
        try {
            let infoArray = await cacheDriver.getValuesWhereKeyStartWith(CLUSTER_MANIFEST_META);
            return infoArray.map(el => JSON.parse(el));
        } catch (error) {
            logger.error(() => 'Get all manifest state. Error', error);
        }
    }
 
    async setCommand(command) {
        try {
            await cacheDriver.setGuaranteed(CLUSTER_MASTER_COMMAND, command);
            logger.debug(() => `Set command ${command} to cache`);
        } catch (error) {
            logger.warn(() => `Set command ${command} to cache failed. Error ${error}`);
        }
    }
 
    async getExpectTimeManifest(manifestAlias) {
        return Number(await cacheDriver.get(CLUSTER_MANIFEST_UPDATE_TIME_KEY + manifestAlias));
    }
 
    async setExpectTimeManifest(manifestAlias) {
        let currentTimestamp = Date.now();
        try {
            await cacheDriver.setGuaranteed(CLUSTER_MANIFEST_UPDATE_TIME_KEY + manifestAlias, currentTimestamp);
            logger.debug(() => `Set expected time for update to manifest ${manifestAlias} as ${currentTimestamp}`);
        } catch (error) {
            logger.warn(() => `Set expected time for update to manifest ${manifestAlias} with ${currentTimestamp} error`, error);
        }
    }
 
    async getActualManifestTimes() {
        return JSON.parse(await cacheDriver.get(CLUSTER_ALL_MANIFEST_ACTUAL_TIME_KEY));
    }
 
    async saveActualManifestTimes(actualState) {
        try {
            await cacheDriver.setGuaranteed(CLUSTER_ALL_MANIFEST_ACTUAL_TIME_KEY, JSON.stringify(actualState));
            logger.debug(() => 'actual manifest state saved success');
        } catch (error) {
            logger.warn(() => 'actual manifest state saved error', error);
        }
    }
 
    // Ошибки чтения и записи версий загрузки пробрасываются, а не пишутся в лог: без отметки нельзя начинать
    // загрузку, а без версии итога снаружи не узнают, чем загрузка закончилась
 
    /** Версии цикла загрузки; нет записи - пустые версии */
    async getLoadCycle() {
        return JSON.parse(await cacheDriver.get(CLUSTER_LOAD_CYCLE_KEY)) ?? {};
    }
 
    async saveLoadCycle(cycle) {
        await cacheDriver.setGuaranteed(CLUSTER_LOAD_CYCLE_KEY, JSON.stringify(cycle));
    }
 
    /** Мета всех манифестов одним запросом; в отличие от getAllManifestState, сбой кеша пробрасывается */
    async readManifestMetas() {
        return (await cacheDriver.getValuesWhereKeyStartWith(CLUSTER_MANIFEST_META)).map((meta) => JSON.parse(meta));
    }
 
    /**
     * Меняет только перечисленные поля меты манифеста: мету пишут загрузчик, мастер и сохранение содержимого,
     * каждый свои поля, и одновременные записи не теряют друг друга
     */
    async mergeManifestMeta(permission, patch, removeKeys = []) {
        await cacheDriver.mergeGuaranteed(CLUSTER_MANIFEST_META + permission, patch, removeKeys);
    }
 
    /** Итог цикла (load-cycle.ts): сначала мета alias, затем цикл */
    async applyCycleResult(result) {
        for (const {permission, patch} of result.manifests) {
            await this.mergeManifestMeta(permission, patch);
        }
        await this.saveLoadCycle(result.cycle);
    }
 
    /** Метка мастера без побочных эффектов, в отличие от status(); нет записи или сбой кеша - пустой объект */
    async getMasterInfo() {
        try {
            return JSON.parse(await cacheDriver.get(CLUSTER_MASTER_INFO) || '{}');
        } catch (error) {
            logger.error(() => `Get master info from cache failed. Error ${error}`);
            return {};
        }
    }
 
    async status(nodeId) {
        try {
            let info = JSON.parse(await cacheDriver.get(CLUSTER_MASTER_INFO) || '{}');
 
            if (!info.updated || Date.now() - info.updated > CLUSTER_MASTER_TIMEOUT) {
                logger.info(() => `[myId ${nodeId}, masterId ${info.id}]: Old master died or not exist (last update timestamp ${info.updated}), now i'm a master`);
                info = {
                    id: nodeId,
                    counter: MASTER_SET_CHECK,
                    updated: Date.now()
                };
                await cacheDriver.setGuaranteed(CLUSTER_MASTER_INFO, JSON.stringify(info));
                await this.updateCommandState('Not ready');
                return {status: NodeStatus.WAIT, info: info};
            } else if (info.id === nodeId) {
                if (info.counter > 0 || !info.endLoadTime) {
                    const newInfo = {
                        id: nodeId,
                        counter: Math.max(info.counter - 1, 0),
                        updated: Date.now()
                    };
                    await cacheDriver.setGuaranteed(CLUSTER_MASTER_INFO, JSON.stringify(newInfo));
                    return {status: info.counter <= 1 ? NodeStatus.NO_MANIFEST : NodeStatus.WAIT, info: newInfo};
                } else {
                    info.updated = Date.now();
                    const refreshTimestampRaw = await cacheDriver.get(CLUSTER_COMMAND_REFRESH_TIMESTAMP);
                    const refreshTimestamp = refreshTimestampRaw && parseInt(refreshTimestampRaw);
                    if (!isNaN(refreshTimestamp) && info.endLoadTime < refreshTimestamp) {
                        logger.debug(() => `update info.endLoadTime with value ${refreshTimestamp} by value from cache (key ${CLUSTER_COMMAND_REFRESH_TIMESTAMP})`);
                        info.endLoadTime = refreshTimestamp;
                    } else if (refreshTimestampRaw) {
                        logger.debug(() => `${CLUSTER_COMMAND_REFRESH_TIMESTAMP} contains incorrect value [${refreshTimestampRaw}] (NaN or lower than info.endLoadTime [${info.endLoadTime}]), nothing to update`);
                    }
                    if (refreshTimestampRaw) {
                        await cacheDriver.del(CLUSTER_COMMAND_REFRESH_TIMESTAMP);
                    }
                    await cacheDriver.setGuaranteed(CLUSTER_MASTER_INFO, JSON.stringify(info));
                    return {status: NodeStatus.MASTER, endLoadTime: info.endLoadTime, info: info};
                }
            } else {
                return {status: info.endLoadTime ? NodeStatus.SLAVE : NodeStatus.WAIT, endLoadTime: info.endLoadTime, info: info};
            }
        } catch (error) {
            logger.warn(() => `Status communication to cache failed. Error ${error}`);
            if (error?.code === 'ECONNREFUSED') {
                return {status: NodeStatus.NOT_CONNECTED_TO_CACHE};
            }
        }
        return {status: NodeStatus.WAIT};
    }
 
    // TODO: т.к. манифест мы не иициализируем, то надо как-то переименовать
    async initializeManifest(endLoadTime) {
        try {
            const info = JSON.parse(await cacheDriver.get(CLUSTER_MASTER_INFO));
            info.endLoadTime = endLoadTime;
            await cacheDriver.setGuaranteed(CLUSTER_MASTER_INFO, JSON.stringify(info));
        } catch (error) {
            logger.warn(() => `Initialize manifest from cache failed. Error ${error}`);
        }
    }
 
    // Дешёвый read - hash/problems/commonManifestHash лежат тут, а не в тяжёлом блобе с манифестом
    async getManifestMeta(permission) {
        try {
            return JSON.parse(await cacheDriver.get(CLUSTER_MANIFEST_META + permission)) || {};
        } catch (error) {
            const traceId = uuidv4();
            logger.warn(() => `[${traceId}] Get manifest meta ${permission} from cache failed`, error);
            throw Error(`[${traceId}] Get manifest meta ${permission} from cache failed`, {cause: error});
        }
    }
 
    /**
     * Отдаёт персистентную форму storage по его permission. Это НЕ манифест: манифест лежит внутри,
     * рядом с md5Map/repositorySources/permission.
     */
    async getStorageBlob(permission) {
        try {
            return JSON.parse(await cacheDriver.get(CLUSTER_MANIFEST + permission));
        } catch (error) {
            const traceId = uuidv4();
            logger.warn(() => `[${traceId}] Get storage blob ${permission} from cache failed`, error);
            throw Error(`[${traceId}] Get storage blob ${permission} from cache failed`, {cause: error});
        }
    }
 
    async clearCache() {
        logger.info(() => 'Clear cache start');
        let deletedKeyCount = 0;
        try {
            if (['postgres'].includes(datalakeCacheMode)) {
                // Актуальные hash'и берём из меты манифестов. Сбой её чтения прерывает очистку: с
                // неполным списком под удаление ушли бы данные живых манифестов
                const manifestMetas = (await cacheDriver.getValuesWhereKeyStartWith(CLUSTER_MANIFEST_META))
                    .map((meta) => JSON.parse(meta));
                const actualHashes = collectActualCacheHashes(manifestMetas);
                if (actualHashes.length === 0) {
                    // С пустым списком под удаление ушёл бы весь кеш данных. Живых данных при этом может и
                    // не быть, но пустым список окажется и при ошибке в сборе hash'ей - поэтому не чистим
                    logger.warn(() => `Clear cache skipped: no actual hash found in ${manifestMetas.length} manifest meta(s)`);
                } else {
                    logger.debug(() => `Clear cache: keep data of ${actualHashes.length} actual hash(es) from ${manifestMetas.length} manifest meta(s)`);
                    deletedKeyCount = await cacheDriver.removeOldSeafCacheData(actualHashes);
                }
            } else {
                logger.warn(() => `clearCache: cache mode not postgres (VUE_APP_DOCHUB_DATALAKE_CACHE = ${datalakeCacheMode}), nothing to clear`);
            }
        } catch (error) {
            logger.warn(() => `Clear cache cache failed. Error ${error}`);
        }
        logger.info(() => `cacheClear: delete finish, delete ${deletedKeyCount} keys`);
    }
 
    async close() {
        if (!cacheDriver) {
            logger.debug(() => 'cacheDriver not exist. nothing to close');
        }
        try {
            switch (datalakeCacheMode) {
                case 'postgres':
                    logger.debug(() => 'close postgres connection');
                    await cacheDriver.close();
                    cacheDriver = null;
                    break;
                default:
                    logger.debug(() => `cache mode not postgres (VUE_APP_DOCHUB_DATALAKE_CACHE = ${datalakeCacheMode}), nothing to close`);
            }
        } catch (e) {
            logger.error(() => 'error when try close cache', e);
            throw e;
        }
    }
 
    async init() {
      switch (datalakeCacheMode) {
        case 'redis':
            logger.error(() => redisUnsupportedMessage);
            throw Error(redisUnsupportedMessage);
        case 'postgres':
          logger.info(() => 'PostgresSQL is used as cluster cache ');
          cacheDriver = await postgres();
          break;
        default: {
            const errorMessage = `unknown datalake cache mode (VUE_APP_DOCHUB_DATALAKE_CACHE) [${datalakeCacheMode}], allow only [postgres]`;
            logger.error(() => errorMessage);
            throw Error(errorMessage);
        }
      }
 
      if (!cacheDriver) {
          const message = 'I can not create a cluster because connecting to cache DB is impossible';
          logger.error(() => message);
          throw new Error(message);
      }
    }
 
    async getClusterCache() {
      if (cacheDriver)
        return cacheDriver;
 
      await this.init();
      return cacheDriver;
    }
}