All files / backend/middlewares manifestFromCache.mjs

85.56% Statements 83/97
100% Branches 44/44
39.13% Functions 9/23
100% Lines 79/79

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                                                                        28x 28x 28x                           48x 69x 69x 69x 2x   67x 4x     63x 18x   45x   63x   52x 52x   37x 37x   41x 40x   1x     69x                     29x       29x     5x 5x   24x       3x 3x   21x       21x                   48x       57x 57x 5x 5x 5x 5x   52x 2x 2x 2x 2x     50x 50x         50x       45x 45x 45x 4x 4x 4x     41x 2x     39x 39x       52x 7x 7x 7x         45x     45x 45x 37x   8x   45x   45x 45x 4x 4x 4x   41x   4x 4x 4x     37x 37x                   43x 2x        
/*
  Copyright (C) 2025 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 {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {ensureReaderHarness} from '@back/storage/harness.ts';
import {
    checkAllKeys,
    ensureStoragesLoaded,
    getPermissionByAlias, getStorage,
    isCommonManifestDeclared,
    isPermissionByAliasEmpty
} from '@back/storage/storageHolder.ts';
import {ROLES_MODE_V2_ENABLED} from '@back/helpers/env.mjs';
import {
    DEFAULT_PERMISSION_FOR_COMMON_MANIFEST
} from '@back/cluster/constants.mjs';
import {toStorageBlob} from '@back/storage/storage-blob.ts';
import {isCommonStorage} from '@back/storage/storage-types.ts';
import {performanceLogger} from '@back/utils/logger/index.mjs';
import {HttpHeaders} from '@global/helpers/httpHeaders.mjs';
import {isInternalJsonataRequest, noNeedManifest} from '@back/helpers/manifestNeedChecker.mjs';
import {getPermissionWithAccess} from '@back/utils/get-user-permission.mjs';
 
const LOG_TAG = '/b/m/manifestFromCache';
const logger = getLoggerWithTag(LOG_TAG);
const perfLogger = performanceLogger?.getGenericLogger();
 
 
/**
 * Добавляем в запрос storage (манифест вместе с md5Map/hash/problems и рантайм-обвязкой) - req.storage.
 * Если работаем в режиме кластера, тогда:
 *  - собираем storage на основе полученных прав если ролевая модель включена
 *  - собираем storage по общему манифесту если ролевая модель выключена
 * Если работаем в режиме backend, тогда берём storage из app.storage
 * @param app - глобальное пространство
 * @param cache - реализация кеша
 */
export default (app, cache) => {
 
    app.use(async(req, res, next) => {
        try {
            perfLogger?.setStart();
            if (noNeedManifest(req)) {
                return next();
            }
            if (!app.isCluster) {
                req.storage = app.storage;
            } else {
                let permissions;
                if (ROLES_MODE_V2_ENABLED && isInternalJsonataRequest(req)) {
                    permissions = getPermissionsByOrgHeader(req, res);
                } else {
                    permissions = getPermissionsForUser(req, res);
                }
                if (!permissions) return;
 
                const storage = await getStorageForPermissions(permissions, res);
                if (!storage) return;
 
                req.storage = storage;
                logger.trace(() => `apply storage by manifest hash ${storage.hash}`);
            }
            if (req.storage) {
                next();
            } else {
                res.status(401).json({error: 'access denied'});
            }
        } finally {
            perfLogger?.setEnd();
        }
    });
 
    /**
     * Читает storage одного permission из кластерного кеша. Блоб и мету читаем параллельно: блобы
     * тяжёлые (common - единицы МБ), а последовательное чтение превращало холодный старт воркера в
     * сумму round-trip'ов.
     * @returns storage либо undefined, если поднимать нечего
     */
    async function loadStorageFromCache(permission) {
        const [storageBlob, meta] = await Promise.all([
            cache.getStorageBlob(permission),
            cache.getManifestMeta(permission)
        ]);
        if (!storageBlob) {
            // Права есть, а блоба в кластерном кеше нет: загрузка упала, блоб ещё не записан
            // после старта, либо импорт убрали из root-манифеста
            logger.warn(() => `no storage blob in cluster cache for permission ${permission}, skip it`);
            return undefined;
        }
        if (!meta?.manifestHash) {
            // hash ключует кеш датасетов вместе с permission - без него ключ становится
            // "undefined.<permission>" и не меняется при смене содержимого манифеста, отдавая
            // устаревшие данные из кеша, поэтому такой storage не поднимаем
            logger.warn(() => `storage blob for permission ${permission} has no manifestHash in meta, skip it`);
            return undefined;
        }
        logger.trace(() => `raised storage from cluster cache for permission ${permission}`);
        // Поднимаем тем же селектором, которым писали, поэтому лишние поля старых блобов
        // (включая нерабочую после сериализации обвязку) сюда не попадут. hash/problems/
        // commonManifestHash персистятся отдельно в manifestMeta - собираем всё обратно здесь
        return {
            ...toStorageBlob(storageBlob),
            hash: meta.manifestHash,
            manifestHash: meta.manifestHash,
            problems: meta.problems,
            commonManifestHash: meta.commonManifestHash
        };
    }
 
    // Если запущены в режиме кластера, то проверяем, подходит ли кеш для использования. Если нет - кидаем ошибку
    app.isCluster && throwIfCacheNotValidForUse(cache);
 
 
    function getPermissionsByOrgHeader(req, res) {
        const orgCtx = req.headers[HttpHeaders.X_SFA_ORGCTX];
        if (!orgCtx) {
            const message = `required header ${HttpHeaders.X_SFA_ORGCTX} not found or empty`;
            logger.warn(() => `permission filter by domain rejected request: ${message}`);
            res.status(400).json({error: message});
            return;
        }
        if (isPermissionByAliasEmpty()) {
            const message = 'no data of root manifest, try later, check logs';
            logger.warn(() => `permission filter by domain rejected request: ${message}`);
            res.set(HttpHeaders.RETRY_AFTER, '60').status(503).json({error: message});
            return;
        }
 
        const permission = getPermissionByAlias(orgCtx);
        logger.trace(() => [
            'permission resolved from domain alias',
            {title: 'domain(orgCtx from header)', obj: orgCtx},
            {title: 'permission associated by domain', obj: permission}
        ]);
        return permission ? [permission] : [];
    }
 
    function getPermissionsForUser(req, res) {
        const userPermissions = getPermissionWithAccess(req)?.map(({rp}) => rp);
        logger.trace(() => `user permissions = ${userPermissions}`);
        if (!userPermissions?.length) {
            logger.debug(() => 'user have no permissions in jwt');
            res.status(401).json({error: 'no manifest for user permissions (empty permissions)'});
            return;
        }
 
        if (!ROLES_MODE_V2_ENABLED) {
            return userPermissions;
        }
 
        const orgPermissions = getPermissionsByOrgHeader(req, res);
        return orgPermissions?.filter(permission => userPermissions.includes(permission));
    }
 
    async function getStorageForPermissions(userPermissions, res) {
        if (userPermissions.length === 0) {
            logger.debug(() => 'user have no permissions after filter by org ctx (no have permission on selected orgctx)');
            res.status(401).json({error: 'no manifest for user permissions (empty permissions or only common)'});
            return;
        }
 
        // Общий манифест подмешиваем, только если он объявлен в root-манифесте.
        // Иначе кластерный кеш будет искать блоб и мету для несуществующего storage.
        const permissions = isCommonManifestDeclared()
            ? [...userPermissions, DEFAULT_PERMISSION_FOR_COMMON_MANIFEST]
            : userPermissions;
        const notExistPermissions = checkAllKeys(permissions);
        if (notExistPermissions.length) {
            logger.debug(() => `permissions ${notExistPermissions} are not in process cache, read them from cluster cache`);
        } else {
            logger.trace(() => `all permissions ${permissions} are already in process cache, no read from cluster cache needed`);
        }
        await ensureStoragesLoaded(notExistPermissions, loadStorageFromCache);
 
        const storage = getStorage(permissions);
        if (!storage) {
            logger.debug(() => `no storage found for permissions ${permissions}`);
            res.status(401).json({error: 'no manifest for user permissions (not found)'});
            return;
        }
        if (isCommonStorage(storage)) {
            // Если манифест организации не поднялся, одного общего манифеста недостаточно.
            logger.warn(() => `only common manifest resolved for permissions ${permissions}, role manifest is not loaded`);
            res.status(401).json({error: 'no manifest for user permissions (empty permissions or only common)'});
            return;
        }
 
        await ensureReaderHarness(storage);
        return storage;
    }
 
    /**
     * Для работы этого фильтра нужен кластерный кеш (ClusterCache): из него берутся блобы storage и их мета
     * Если ее нет, то использовать такой кеш не получится
     * @param cache
     * @returns {boolean}
     */
    function throwIfCacheNotValidForUse(cache) {
        if (!cache || !cache.isClusterCache) {
            throw Error('It\'s impossible to use the passed cache for middleware operation; the required getStorageBlob function is missing. The cache implementation must be modified or it must not be passed.');
        }
    }
};