"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tdfHeapMiddleWareManager = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const path_1 = tslib_1.__importDefault(require("path"));
const enum_tdf_mapping_1 = require("tdf-devtools-protocol/dist/types/enum-tdf-mapping");
const config_1 = require("@/config");
const log_1 = require("@/utils/log");
const log = new log_1.Logger('tdf-heap-middleware');
// TODO 暂只缓存本地，本地单节点部署无问题。后续缓存到 redis，或者容器外部挂载数据卷
exports.tdfHeapMiddleWareManager = {
    downwardMiddleWareListMap: {
        [enum_tdf_mapping_1.TdfCommand.TDFMemoryGetHeapMeta]: async ({ msg, sendToDevtools }) => {
            var _a;
            try {
                const commandRes = msg;
                const { cachePath } = config_1.config;
                const fpath = path_1.default.join(cachePath, `${commandRes.id}.json`);
                await fs_1.default.promises.writeFile(fpath, JSON.stringify(commandRes));
                return sendToDevtools(commandRes);
            }
            catch (e) {
                log.error('write heap failed! %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
                return Promise.reject(e);
            }
        },
    },
    upwardMiddleWareListMap: {
        [enum_tdf_mapping_1.TdfCommand.TDFMemoryFetchHeapCache]: async ({ msg, sendToDevtools }) => {
            var _a;
            try {
                const req = msg;
                const { cachePath } = config_1.config;
                const fpath = path_1.default.join(cachePath, `${req.params.id}.json`);
                const cacheMsgStr = await fs_1.default.promises.readFile(fpath, 'utf8');
                const cacheMsg = JSON.parse(cacheMsgStr);
                return sendToDevtools({
                    id: req.id,
                    method: req.method,
                    result: cacheMsg.result,
                });
            }
            catch (e) {
                log.error('write heap failed! %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
                return Promise.reject(e);
            }
        },
    },
};
