"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const CircuitBreaker = require("opossum");
class DegradeRuleManager {
    constructor() {
        this.ruleMap = new Map();
    }
    loadRule(pid, breakerOptions) {
        if (!breakerOptions) {
            this.ruleMap.delete(pid);
            return;
        }
        if (this.ruleMap.has(pid)) {
            this.setRule(pid, breakerOptions);
        }
        else {
            this.addRule(pid, breakerOptions);
        }
    }
    /**
     * 获取熔断器
     *
     * @param pid 项目ID
     */
    getCircuitBreaker(pid) {
        return this.ruleMap.get(pid);
    }
    /**
     * 生成熔断配置
     * @param pid 项目ID
     * @param breakerOptions
     */
    addRule(pid, breakerOptions) {
        const circuitBreaker = new CircuitBreaker((action) => __awaiter(this, void 0, void 0, function* () {
            yield action();
        }), breakerOptions);
        this.ruleMap.set(pid, circuitBreaker);
    }
    /**
     * 覆盖原有的熔断配置
     *
     * @param pid 项目ID
     * @param breakerOptions
     */
    setRule(pid, breakerOptions) {
        const circuitBreaker = this.ruleMap.get(pid);
        if (!circuitBreaker) {
            return;
        }
        const options = circuitBreaker.options;
        options.timeout = breakerOptions.timeout; //响应超时ms
        options.errorThresholdPercentage = breakerOptions.errorThresholdPercentage; //触发比例
        options.resetTimeout = breakerOptions.resetTimeout; //熔断时长
        options.rollingCountTimeout = breakerOptions.rollingCountTimeout; //计时周期
    }
}
exports.default = new DegradeRuleManager();
