"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const nestedCounters_1 = require("../utils/nestedCounters");
const network_1 = require("../network");
const NodeList_1 = require("../p2p/NodeList");
const Self = __importStar(require("../p2p/Self"));
const Context = __importStar(require("../p2p/Context"));
const logger_1 = require("../logger");
class RateLimiting {
    constructor(config, seqLogger) {
        this.limitRate = config.limitRate;
        this.loadLimit = config.loadLimit;
        this.seqLogger = seqLogger;
    }
    calculateThrottlePropotion(load, limit) {
        const throttleRange = 1 - limit;
        const throttleAmount = load - limit;
        const throttleProportion = throttleAmount / throttleRange;
        return throttleProportion;
    }
    getWinningLoad(nodeLoad, queueLoad) {
        let loads = { ...nodeLoad, ...queueLoad };
        let maxThrottle = 0;
        let loadType;
        for (let key in loads) {
            if (this.loadLimit[key] == null) {
                continue; //not checking load limit for undefined or 0 limit.
            }
            if (loads[key] < this.loadLimit[key])
                continue;
            let throttle = this.calculateThrottlePropotion(loads[key], this.loadLimit[key]);
            /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('loadRelated', `ratelimit reached: ${key} > ${this.loadLimit[key]}`);
            if (throttle > maxThrottle) {
                maxThrottle = throttle;
                loadType = key;
            }
        }
        if (loadType) {
            nestedCounters_1.nestedCountersInstance.countEvent('loadRelated', `ratelimit winning load factor: ${loadType}`);
        }
        return {
            throttle: maxThrottle,
            loadType,
        };
    }
    isOverloaded(txId) {
        if (!this.limitRate)
            return false;
        const nodeLoad = Context.shardus.loadDetection.getCurrentNodeLoad();
        const queueLoad = Context.shardus.loadDetection.getQueueLoad();
        let { throttle, loadType } = this.getWinningLoad(nodeLoad, queueLoad);
        if (throttle > 0) {
            // TODO: add counter to track max load type
        }
        let overloaded = Math.random() < throttle;
        if (overloaded) {
            /* prettier-ignore */ if (logger_1.logFlags.seqdiagram)
                this.seqLogger.info(`0x53455106 ${(0, network_1.shardusGetTime)()} tx:${txId} Note over ${NodeList_1.activeIdToPartition.get(Self.id)}: overloaded_type ${loadType}:${throttle}`);
            /* prettier-ignore */ if (logger_1.logFlags.seqdiagram)
                this.seqLogger.info(`0x53455106 ${(0, network_1.shardusGetTime)()} tx:${txId} Note over ${NodeList_1.activeIdToPartition.get(Self.id)}: overloaded_node ${nodeLoad.internal}/${nodeLoad.external}`);
            /* prettier-ignore */ if (logger_1.logFlags.seqdiagram)
                this.seqLogger.info(`0x53455106 ${(0, network_1.shardusGetTime)()} tx:${txId} Note over ${NodeList_1.activeIdToPartition.get(Self.id)}: overloaded_queue ${queueLoad.txTimeInQueue}/${queueLoad.queueLength}}/${queueLoad.executeQueueLength}`);
            nestedCounters_1.nestedCountersInstance.countEvent('loadRelated', 'txRejected:' + loadType);
        }
        return overloaded;
    }
    configUpdated() {
        try {
            if (this.limitRate !== Context.config.rateLimiting.limitRate) {
                this.limitRate = Context.config.rateLimiting.limitRate;
                console.log('Config updated for rateLimiting.limitRate', this.limitRate);
                nestedCounters_1.nestedCountersInstance.countEvent('RateLimiting', 'limitRate config updated');
            }
            if (JSON.stringify(this.loadLimit) !== JSON.stringify(Context.config.rateLimiting.loadLimit)) {
                this.loadLimit = Context.config.rateLimiting.loadLimit;
                console.log('Config updated for rateLimiting.loadLimit', this.loadLimit);
                nestedCounters_1.nestedCountersInstance.countEvent('RateLimiting', 'loadLimit config updated');
            }
        }
        catch (e) {
            nestedCounters_1.nestedCountersInstance.countEvent('RateLimiting', 'config update failed');
        }
    }
}
exports.default = RateLimiting;
//# sourceMappingURL=index.js.map