"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Prometheus = void 0;
const tslib_1 = require("tslib");
const node_http_1 = tslib_1.__importDefault(require("node:http"));
const prom_client_1 = tslib_1.__importStar(require("prom-client"));
const logger_1 = require("./utils/logger");
const types_1 = require("./config/types");
class Prometheus {
    server;
    register;
    // Api metrics
    apiTotalRequests;
    apiLatency;
    apiErrors;
    // Global
    isHealthy;
    networkStatus;
    orderStatusCountTotal;
    orderStatusCount;
    orderLifecycleCount;
    executionRevertedError;
    transmitterError;
    eventQueueProcessingHealthcheckRates;
    eventQueueProcessing;
    eventQueueProcessingTime;
    eventQueueProcessingFailed;
    tokenApproval;
    statusTransitionTime;
    statusTransitionTimeRelative;
    orderIngestionTime;
    blockFetchTime;
    // Dynamo
    statusTransition;
    dynamoCall;
    //
    // Metrics
    //
    balance;
    totalBalance;
    gasTooHigh;
    circuitDisconnects;
    rpcCall;
    transmitterQueue;
    distributorClaimSegments;
    l3Bonuses;
    currentBaseRewardL3;
    l3Attestations;
    l2AttestationsThroughput;
    l2AttestationsSent;
    l2AttestationsDelivered;
    l2ClaimableAttestationsDelivered;
    l2AttestationsSize;
    assetsCounter;
    l3DLQAttestations;
    l2EscrowGMPNotMatching;
    l2EscrowGMPNotMatchingSent;
    l2LateOrdersSentToDLQ;
    l2LateOrdersReSentFromDLQ;
    pendingOrderCount;
    xRecordsCharged;
    // Gas Metrics
    gasPrices;
    // RemoteOrder estimations
    gasLimits;
    gasFees;
    gasFeesUSD;
    gasUsed;
    // Executor
    bidCompleted;
    bidHeatmap;
    bidFailed;
    bidDifficulty;
    ordersAtProfit;
    ordersAtLoss;
    ordersProfitTotal;
    ordersLossTotal;
    orderAvgProfitPercentage;
    orderAvgLossPercentage;
    executorsBalances;
    profitability;
    profitabilityExecutor;
    profitabilitySourceDest;
    executionsCompleted;
    executionsConfirmed;
    availableUnderbidMarginUSD;
    executionsFailed;
    executionsHeatMap;
    claimsCompleted;
    claimsFailed;
    unclaimableByExecutor;
    claimsHeatmap;
    claimsTotal;
    expenditures;
    USDExpensesATT;
    USDIncomesATT;
    incomes;
    claimsPending;
    averagePace;
    executedAmount;
    claimedAmount;
    insuranceRefundedAmount;
    BRNRewardsCollectedAmount;
    BRNRewardsToUsersAmount;
    TRNRewardsCollectedAmount;
    // Guardian
    attestersContractcurrentBatchIndex;
    attestationsGuardianPending;
    attestationsTotal;
    attestationsCompleted;
    attestationsRevertsCompleted;
    attestationsFailed;
    attestationsPending;
    attestationsHeatMap;
    attestationsDLQTotal;
    orderBookchainHeight;
    // FastWriter
    orderValue;
    refundValue;
    fastWriterTxsAcceptedHeatMap;
    fastWriterTxsSent;
    fastWriterTxsAccepted;
    fastWriterTxsFailed;
    fastWriterTxsExpired;
    fastWriterExpiredTxsRefunded;
    // Monitor
    protocolFeesAccrued;
    protocolFeesCollectorBalance;
    remoteOrder;
    remoteOrderBalance;
    remoteOrderRefundableOnlyAfterAttestation;
    remoteOrderIsHalted;
    remoteOrderProtocolFee;
    remoteOrderProtocolFeeMinLow;
    remoteOrderProtocolFeeMinHigh;
    remoteOrderTimeout;
    remoteOrderMinMaxAmounts;
    activeExecutors;
    avgExecutorProfitUSDLastDay;
    version;
    doubleSpend;
    // Pricer
    currentEthPrice;
    pendingValidationTime;
    pendingValidations;
    pricerEstimateError;
    pricerEstimateTips;
    estimateFee;
    estimateFeeDetailed;
    cacheBytesWrite;
    // Prophet
    prophetAdHocBlockFetch;
    invalidConfirmation;
    confirmationMissingBid;
    overTimeConfirmation;
    mismatchingConfirmationId;
    confirmedRefund;
    txFeesUSD;
    txTimeMetrics;
    eventEmitted;
    lifecycleGasFeesUSD;
    protocolFeeWei;
    protocolFeeUSD;
    protocolFeeFlatUSD;
    protocolFeeWeiForEstimate;
    protocolFeeUSDForEstimate;
    totalFeesUSD;
    destinationGasFeesUSD;
    sourceGasFeesUSD;
    executorsProfitsWei;
    ordersProfitsWei;
    executorMismatch;
    // Placer
    placerOrdersInProcessing;
    // Redshift
    redshiftQueryDuration;
    redshiftQueries;
    redshiftFailedQueries;
    redshiftQueryRowsReturned;
    // Messiah
    messiahRestarts;
    messiahBlocksHeatMap;
    messiahReceiptsReUsed;
    messiahBlockReUsed;
    messiahOrderMissed;
    messiahEventsScanned;
    messiahTowerExceptions;
    messiahCurrentTimestamp;
    messiahLostOrderClosed;
    messiahOrderClosed;
    messiahOrderOpened;
    messiahUpToDateDistance;
    messiahPerMinuteRate;
    messiahBlockScanned;
    messiahTowerSize;
    messiahDLQSize;
    messiahGasUsed;
    messiahBlockProcessingTime;
    messiahRelevantTxInBlock;
    messiahBlockFetchTime;
    messiahLocalSQSQueueSize;
    messiahHourlyStatements;
    messiahHourlyTime;
    config;
    alternativePort;
    constructor(config, _alternativePort) {
        this.config = config;
        this.alternativePort = _alternativePort;
        const Registry = prom_client_1.default.Registry;
        const defaultLabels = {
            variant: config.instance,
        };
        this.register = new Registry();
        this.register.setDefaultLabels(defaultLabels);
        this.createMetrics();
    }
    createMetrics() {
        // Collects default metrics
        (0, prom_client_1.collectDefaultMetrics)({ register: this.register });
        this.apiTotalRequests = new prom_client_1.Counter({
            name: 'api_total_requests',
            help: 'Total number of API requests',
            labelNames: ['endpoint'],
            registers: [this.register],
        });
        this.apiLatency = new prom_client_1.Histogram({
            name: 'api_latency_seconds',
            help: 'Latency of API requests in seconds',
            labelNames: ['endpoint'],
            registers: [this.register],
            buckets: [0.1, 0.5, 1, 2, 5, 10], // latency buckets in seconds
        });
        this.apiErrors = new prom_client_1.Counter({
            name: 'api_errors_total',
            help: 'Total number of API errors',
            labelNames: ['endpoint'],
            registers: [this.register],
        });
        this.networkStatus = new prom_client_1.Gauge({
            name: 'network_status',
            help: 'Network status (1 for online, 0 for offline)',
            labelNames: ['networkId', 'rpcHostname'],
            registers: [this.register],
        });
        this.executionRevertedError = new prom_client_1.Counter({
            name: 'execution_reverted_error',
            help: 'Number of times execution reverted',
            labelNames: ['code', 'networkId'],
            registers: [this.register],
        });
        this.transmitterError = new prom_client_1.Counter({
            name: 'transmitter_error_total',
            help: 'Number of transmitter failed',
            labelNames: ['code', 'networkId', 'lifecycle'],
            registers: [this.register],
        });
        this.eventEmitted = new prom_client_1.Counter({
            name: 'event_emitted_total',
            help: 'Number of times event was emitted',
            labelNames: ['name', 'networkId'],
            registers: [this.register],
        });
        this.messiahEventsScanned = new prom_client_1.Counter({
            name: 'messiah_events_scanned',
            help: 'Number of times SQS event queues completed',
            labelNames: ['eventName', 'networkId', 'sourceNetwork', 'destinationNetwork', 'podNumber'],
            registers: [this.register],
        });
        this.eventQueueProcessing = new prom_client_1.Counter({
            name: 'event_sqs_queue_processing',
            help: 'Number of times SQS event queues completed',
            labelNames: ['eventName', 'networkId', 'sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.eventQueueProcessingFailed = new prom_client_1.Counter({
            name: 'event_sqs_queue_processing_failed',
            help: 'Number of times SQS event queues failed',
            labelNames: ['eventName', 'networkId', 'reason'],
            registers: [this.register],
        });
        this.tokenApproval = new prom_client_1.Counter({
            name: 'token_approval_total',
            help: 'Result of token approvals',
            labelNames: ['networkId', 'assetNumber', 'result'],
            registers: [this.register],
        });
        this.statusTransitionTime = new prom_client_1.Histogram({
            name: 'status_transition_time_seconds',
            help: 'Time taken for status transitions in seconds',
            labelNames: ['statusTransition', 'source', 'destination'],
            registers: [this.register],
            buckets: [1, 2, 5, 10, 30, 60, 300, 600, 1800, 3600], // buckets in seconds
        });
        this.statusTransitionTimeRelative = new prom_client_1.Histogram({
            name: 'status_transition_time_relative_seconds',
            help: 'Time taken for status transitions in seconds',
            labelNames: ['statusTransition', 'source', 'destination'],
            registers: [this.register],
            buckets: [1, 2, 5, 10, 30, 60, 300, 600, 1800, 3600], // buckets in seconds
        });
        this.orderIngestionTime = new prom_client_1.Histogram({
            name: 'order_ingestion_time_seconds',
            help: 'Time taken to ingest orders in seconds',
            labelNames: ['networkId'],
            registers: [this.register],
            buckets: [0.5, 1, 2, 5, 10, 30, 60, 300, 900, 3600], // buckets in seconds
        });
        this.blockFetchTime = new prom_client_1.Histogram({
            name: 'block_fetch_time_seconds',
            help: 'Time taken fetch block with receipts on average in seconds',
            labelNames: ['networkId'],
            registers: [this.register],
            buckets: [0.5, 1, 2, 5, 10, 30, 60, 300, 900, 3600], // buckets in seconds
        });
        this.eventQueueProcessingHealthcheckRates = new prom_client_1.Counter({
            name: 'event_queue_processing_healthcheck_rates',
            help: 'Healthcheck rates for event queue processing',
            labelNames: ['sqsDirectionLabel', 'queueName', 'label'],
            registers: [this.register],
        });
        this.eventQueueProcessingTime = new prom_client_1.Gauge({
            name: 'event_queue_processing_time',
            help: 'Time taken to process SQS events',
            labelNames: ['eventName', 'networkId'],
            registers: [this.register],
        });
        this.statusTransition = new prom_client_1.Counter({
            name: 'status_transition_total',
            help: 'Number of times status transitioned',
            labelNames: ['statusTransition'],
            registers: [this.register],
        });
        this.dynamoCall = new prom_client_1.Counter({
            name: 'dynamo_call_total',
            help: 'Number of times DynamoDB call was made',
            labelNames: ['app', 'table', 'index', 'type', 'context'],
            registers: [this.register],
        });
        this.orderStatusCount = new prom_client_1.Gauge({
            name: 'order_status_count',
            help: 'Order status count',
            labelNames: ['status', 'offset'],
            registers: [this.register],
        });
        this.orderStatusCountTotal = new prom_client_1.Gauge({
            name: 'order_status_count_total',
            help: 'Order status count_total',
            labelNames: ['status'],
            registers: [this.register],
        });
        this.orderLifecycleCount = new prom_client_1.Counter({
            name: 'order_lifecycle_count_total',
            help: 'Order lifecycle count',
            labelNames: ['lifecycle'],
            registers: [this.register],
        });
        this.circuitDisconnects = new prom_client_1.Counter({
            name: 'circuit_disconnects_total',
            help: 'Number of times circuit rpc server has disconnected',
            labelNames: ['endpoint'],
            registers: [this.register],
        });
        this.rpcCall = new prom_client_1.Counter({
            name: 'rpc_call_total',
            help: 'Number of times rpc call has been made',
            labelNames: ['url', 'status', 'network', 'rpcHostname'],
            registers: [this.register],
        });
        this.xRecordsCharged = new prom_client_1.Counter({
            name: 'x_records_charged_total',
            help: 'Number of times x records charged',
            registers: [this.register],
        });
        this.executedAmount = new prom_client_1.Counter({
            name: 'executed_amount_total',
            help: 'Amount of executed orders',
            labelNames: ['networkId', 'asset'],
            registers: [this.register],
        });
        this.claimedAmount = new prom_client_1.Counter({
            name: 'claimed_amount_total',
            help: 'Amount of claimed executions',
            labelNames: ['networkId', 'asset'],
            registers: [this.register],
        });
        this.insuranceRefundedAmount = new prom_client_1.Counter({
            name: 'insurance_refunded_amount_total',
            help: 'Amount of total insurance refunded post executions',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.BRNRewardsCollectedAmount = new prom_client_1.Counter({
            name: 'brn_rewards_amount_total',
            help: 'Amount of total BRN Rewards collected post executions',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.BRNRewardsToUsersAmount = new prom_client_1.Counter({
            name: 'brn_user_rewards_amount_total',
            help: 'Amount of total BRN Rewards distributed to users',
            labelNames: ['networkId', 'isMainnet'],
            registers: [this.register],
        });
        this.TRNRewardsCollectedAmount = new prom_client_1.Counter({
            name: 'trn_rewards_amount_total',
            help: 'Amount of total TRN Rewards collected post executions',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.claimsPending = new prom_client_1.Gauge({
            name: 'claims_pending',
            help: 'Number of claims pending',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.averagePace = new prom_client_1.Gauge({
            name: 'average_pace',
            help: 'Average pace of orders in seconds',
            labelNames: [],
            registers: [this.register],
        });
        this.claimsHeatmap = new prom_client_1.Counter({
            name: 'claims_heatmap',
            help: 'Number of times claims happened',
            registers: [this.register],
            labelNames: ['sourceNetwork', 'destinationNetwork'],
        });
        this.claimsTotal = new prom_client_1.Counter({
            name: 'claims_total',
            help: 'Number of times claims happened',
            registers: [this.register],
            labelNames: ['sourceNetwork'],
        });
        this.claimsCompleted = new prom_client_1.Counter({
            name: 'claims_completed',
            help: 'Number of times claims completed',
            registers: [this.register],
            labelNames: ['sourceNetwork'],
        });
        this.unclaimableByExecutor = new prom_client_1.Counter({
            name: 'unclaimable_by_executor',
            help: 'Number of times unclaimable by executor',
            registers: [this.register],
            labelNames: ['networkId'],
        });
        this.claimsFailed = new prom_client_1.Counter({
            name: 'claims_failed',
            help: 'Number of times claims failed',
            registers: [this.register],
            labelNames: ['sourceNetwork'],
        });
        this.ordersAtProfit = new prom_client_1.Counter({
            name: 'orders_at_profit',
            help: 'Number of orders at profit',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.ordersAtLoss = new prom_client_1.Counter({
            name: 'orders_at_loss',
            help: 'Number of orders at loss',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.bidDifficulty = new prom_client_1.Gauge({
            name: 'bid_difficulty',
            help: 'Bid difficulty',
            labelNames: [],
            registers: [this.register],
        });
        this.ordersProfitTotal = new prom_client_1.Gauge({
            name: 'orders_profit',
            help: 'The cumulative total profit of orders for given network',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.ordersLossTotal = new prom_client_1.Gauge({
            name: 'orders_loss',
            help: 'The cumulative total loss of orders for given network',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.orderAvgProfitPercentage = new prom_client_1.Gauge({
            name: 'orders_profit_percentage',
            help: 'Average profit percentage per executed order',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.orderAvgLossPercentage = new prom_client_1.Gauge({
            name: 'orders_loss_percentage',
            help: 'Average loss percentage per executed order',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.executorsBalances = new prom_client_1.Gauge({
            name: 'executors_balances',
            help: 'Executor balances',
            labelNames: ['executor', 'networkId', 'asset'],
            registers: [this.register],
        });
        this.bidCompleted = new prom_client_1.Counter({
            name: 'bid_completed_total',
            help: 'Number of times bid completed',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.bidHeatmap = new prom_client_1.Counter({
            name: 'bid_heatmap_total',
            help: 'Number of times bid completed',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.bidFailed = new prom_client_1.Counter({
            name: 'bid_failed_total',
            help: 'Number of times bid failed',
            labelNames: ['sourceNetwork', 'reason'],
            registers: [this.register],
        });
        this.attestersContractcurrentBatchIndex = new prom_client_1.Gauge({
            name: 'attesters_contract_current_batch_index',
            help: 'Current batch index of attesters contract',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.attestationsPending = new prom_client_1.Gauge({
            name: 'attestations_pending',
            help: 'Total of pending attestations',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.transmitterQueue = new prom_client_1.Gauge({
            name: 'transmitter_queue',
            help: 'Total items in transmitter',
            labelNames: ['name', 'networkId'],
            registers: [this.register],
        });
        this.distributorClaimSegments = new prom_client_1.Gauge({
            name: 'distributor_claim_segments',
            help: 'Claim segments stats in distributor',
            labelNames: ['name', 'status'],
            registers: [this.register],
        });
        this.currentBaseRewardL3 = new prom_client_1.Gauge({
            name: 'current_base_reward_l3',
            help: 'Current Base Reward L3',
            labelNames: [],
            registers: [this.register],
        });
        this.l3Bonuses = new prom_client_1.Gauge({
            name: 'l3_bonuses',
            help: 'L3 Bonuses',
            labelNames: ['label', 'assetId'],
            registers: [this.register],
        });
        this.l3Attestations = new prom_client_1.Gauge({
            name: 'l3_attestations',
            help: 'L3 Attestations',
            labelNames: ['name', 'networkId'],
            registers: [this.register],
        });
        this.l2AttestationsThroughput = new prom_client_1.Gauge({
            name: 'l2_attestations_throughput',
            help: 'L2 Attestations Throughput',
            labelNames: ['name', 'networkId'],
            registers: [this.register],
        });
        this.l2AttestationsSent = new prom_client_1.Gauge({
            name: 'l2_attestations_sent',
            help: 'L2 Attestations in Batch Sent',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.l2AttestationsDelivered = new prom_client_1.Gauge({
            name: 'l2_attestations_delivered',
            help: 'L2 Attestations in Batch Delivered',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.l2ClaimableAttestationsDelivered = new prom_client_1.Gauge({
            name: 'l2_claimable_attestations_delivered',
            help: 'L2 Claimable Attestations in Batch Delivered',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.l2AttestationsSize = new prom_client_1.Gauge({
            name: 'l2_attestations_size',
            help: 'L2 Attestations in Batch Size',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.assetsCounter = new prom_client_1.Counter({
            name: 'assets_counter',
            help: 'Assets Counter',
            labelNames: ['sourceNetwork', 'destinationNetwork', 'assetAToBLabel'],
            registers: [this.register],
        });
        this.l3DLQAttestations = new prom_client_1.Counter({
            name: 'l3_dlq_attestations',
            help: 'L3 DLQ Attestations',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.l2EscrowGMPNotMatching = new prom_client_1.Counter({
            name: 'l2_escrow_gmp_not_matching',
            help: 'L2 Escrow GMP Not Matching',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.l2EscrowGMPNotMatchingSent = new prom_client_1.Counter({
            name: 'l2_escrow_gmp_not_matching_sent',
            help: 'L2 Escrow GMP Not Matching and Re-sent',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.l2LateOrdersReSentFromDLQ = new prom_client_1.Counter({
            name: 'l2_late_orders_resent_from_dlq',
            help: 'L2 Late Orders Re-sent from DLQ',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.l2LateOrdersSentToDLQ = new prom_client_1.Counter({
            name: 'l2_late_orders_sent_to_dlq',
            help: 'L2 Late Orders Sent to DLQ',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.pendingOrderCount = new prom_client_1.Gauge({
            name: 'pending_order_count_on_l3_pending_book',
            help: 'Number of pending orders on L3 Pending Book',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.attestationsHeatMap = new prom_client_1.Counter({
            name: 'attestations_heatmap',
            help: 'Total of successful attestations',
            labelNames: ['destinationNetwork', 'sourceNetwork', 'type'],
            registers: [this.register],
        });
        this.attestationsGuardianPending = new prom_client_1.Gauge({
            name: 'attestations_guardian_pending',
            help: 'Number of pending attestations in guardian',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.attestationsTotal = new prom_client_1.Counter({
            name: 'attestations_total',
            help: 'Total of attestations',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.attestationsCompleted = new prom_client_1.Counter({
            name: 'attestations_completed_total',
            help: 'Total of successful attestations',
            labelNames: ['sourceNetwork', 'type'],
            registers: [this.register],
        });
        this.attestationsRevertsCompleted = new prom_client_1.Counter({
            name: 'attestations_reverts_completed_total',
            help: 'Total of successful revert attestations',
            labelNames: [],
            registers: [this.register],
        });
        this.attestationsFailed = new prom_client_1.Counter({
            name: 'attestations_failed_total',
            help: 'Total of failed attestations',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.attestationsDLQTotal = new prom_client_1.Gauge({
            name: 'attestations_dlq_total',
            help: 'Total of successful attestations released',
            labelNames: ['networkId', 'type'],
            registers: [this.register],
        });
        this.orderBookchainHeight = new prom_client_1.Gauge({
            name: 'order_book_chain_height',
            help: 'Order book chain height',
            labelNames: ['label'],
            registers: [this.register],
        });
        this.gasTooHigh = new prom_client_1.Gauge({
            name: 'gas_too_high',
            help: 'Gas too high',
            registers: [this.register],
            labelNames: ['networkId'],
        });
        this.totalBalance = new prom_client_1.Gauge({
            name: 'total_balance_native',
            help: 'Total Native Balance',
            registers: [this.register],
            labelNames: ['name', 'token'],
        });
        this.balance = new prom_client_1.Gauge({
            name: 'balance',
            help: 'Balance',
            registers: [this.register],
            labelNames: ['name', 'sourceNetwork', 'token', 'address'],
        });
        this.executionsHeatMap = new prom_client_1.Counter({
            name: 'executions_heatmap',
            help: 'Number executions',
            registers: [this.register],
            labelNames: ['sourceNetwork', 'destinationNetwork'],
        });
        this.expenditures = new prom_client_1.Counter({
            name: 'expenditures',
            help: 'Amount of money spent on executions in each network in each asset',
            registers: [this.register],
            labelNames: ['destinationNetwork', 'sourceNetwork', 'asset'],
        });
        this.USDExpensesATT = new prom_client_1.Counter({
            name: 'usd_expenses_att',
            help: 'Total of USD gained (ATT - at the time) by rewards claimed of executions in each network in each asset',
            registers: [this.register],
            labelNames: [],
        });
        this.USDIncomesATT = new prom_client_1.Counter({
            name: 'usd_incomes_att',
            help: 'Total of USD gained (ATT - at the time) by rewards claimed of executions in each network in each asset',
            registers: [this.register],
            labelNames: [],
        });
        this.incomes = new prom_client_1.Counter({
            name: 'incomes',
            help: 'Amount of money gained by rewards claimed of executions in each network in each asset',
            registers: [this.register],
            labelNames: ['destinationNetwork', 'sourceNetwork', 'asset'],
        });
        this.profitabilityExecutor = new prom_client_1.Counter({
            name: 'profitability_executor',
            help: 'Profitability ratio',
            labelNames: ['destinationNetwork', 'result'],
            registers: [this.register],
        });
        this.profitability = new prom_client_1.Counter({
            name: 'profitability',
            help: 'Profitability ratio',
            labelNames: ['destinationNetwork', 'result'],
            registers: [this.register],
        });
        this.profitabilitySourceDest = new prom_client_1.Counter({
            name: 'profitability_source_dest',
            help: 'Profitability ratio for source and destination network',
            labelNames: ['sourceNetwork', 'destinationNetwork', 'result'],
            registers: [this.register],
        });
        // Metric of executor
        this.executionsCompleted = new prom_client_1.Counter({
            name: 'executions_completed_total',
            help: 'Number of times execution completed',
            labelNames: ['destinationNetwork'],
            registers: [this.register],
        });
        // Metric for event
        this.executionsConfirmed = new prom_client_1.Counter({
            name: 'executions_confirmed_total',
            help: 'Number of times execution commited',
            labelNames: ['destinationNetwork'],
            registers: [this.register],
        });
        // Metric for underbidding
        this.availableUnderbidMarginUSD = new prom_client_1.Gauge({
            name: 'available_underbid_margin_usd_total',
            help: 'Available underbid margin in USD',
            labelNames: ['destinationNetwork', 'assetCode'],
            registers: [this.register],
        });
        this.executionsFailed = new prom_client_1.Counter({
            name: 'executions_failed_total',
            help: 'Number of times execution failed',
            labelNames: ['destinationNetwork'],
            registers: [this.register],
        });
        this.orderValue = new prom_client_1.Counter({
            name: 'order_value_total',
            help: 'Value of order',
            labelNames: ['networkId', 'asset'],
            registers: [this.register],
        });
        this.refundValue = new prom_client_1.Counter({
            name: 'refund_value_total',
            help: 'Refund value',
            labelNames: ['networkId', 'asset'],
            registers: [this.register],
        });
        this.fastWriterTxsAcceptedHeatMap = new prom_client_1.Counter({
            name: 'fastwriter_txs_accepted_heatmap',
            help: 'Number of txs sent from FastWriter, in total',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.fastWriterTxsSent = new prom_client_1.Counter({
            name: 'fastwriter_txs_sent_total',
            help: 'Number of txs sent from FastWriter, in total',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.fastWriterTxsAccepted = new prom_client_1.Counter({
            name: 'fastwriter_txs_accepted_total',
            help: 'Number of txs sent from FastWriter, that have been successful/accepted, in total',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.fastWriterTxsFailed = new prom_client_1.Counter({
            name: 'fastwriter_txs_failed_total',
            help: 'Number of txs sent from FastWriter, that have failed, in total',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.fastWriterTxsExpired = new prom_client_1.Counter({
            name: 'fastwriter_txs_expired_total',
            help: 'Number of txs sent from FastWriter, that have expired, in total',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.fastWriterExpiredTxsRefunded = new prom_client_1.Counter({
            name: 'fastwriter_expired_txs_refunded_total',
            help: 'Number of txs sent from FastWriter, that have expired and was refunded, in total',
            labelNames: ['sourceNetwork'],
            registers: [this.register],
        });
        this.protocolFeesAccrued = new prom_client_1.Gauge({
            name: 'protocol_fees_accrued',
            help: 'Protocol Fees Accrued',
            labelNames: ['networkId', 'assetAddress'],
            registers: [this.register],
        });
        this.protocolFeesCollectorBalance = new prom_client_1.Gauge({
            name: 'protocol_fees_collector_balance',
            help: 'Protocol Fees Collector Balance',
            labelNames: ['networkId', 'protocolFeesCollector'],
            registers: [this.register],
        });
        this.remoteOrder = new prom_client_1.Gauge({
            name: 'remote_order',
            help: 'Remote Order Contract',
            registers: [this.register],
        });
        this.remoteOrderBalance = new prom_client_1.Gauge({
            name: 'remote_order_balance',
            help: 'Remote Order Balance',
            labelNames: ['networkId', 'asset'],
            registers: [this.register],
        });
        this.remoteOrderRefundableOnlyAfterAttestation = new prom_client_1.Gauge({
            name: 'remote_order_refundable_only_after_attestation',
            help: 'Remote Order Refundable Only After Attestation',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.remoteOrderIsHalted = new prom_client_1.Gauge({
            name: 'remote_order_is_halted',
            help: 'Remote Order Is Halted',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.remoteOrderProtocolFeeMinHigh = new prom_client_1.Gauge({
            name: 'remote_order_protocol_fee_min_high',
            help: 'Remote Order Protocol Fee Min High',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.remoteOrderProtocolFeeMinLow = new prom_client_1.Gauge({
            name: 'remote_order_protocol_fee_min_low',
            help: 'Remote Order Protocol Fee Min Low',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.remoteOrderProtocolFee = new prom_client_1.Gauge({
            name: 'remote_order_protocol_fee',
            help: 'Remote Order Protocol Fee',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.remoteOrderTimeout = new prom_client_1.Gauge({
            name: 'remote_order_order_timeout',
            help: 'Remote Order Order Timeout',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.remoteOrderMinMaxAmounts = new prom_client_1.Gauge({
            name: 'remote_order_order_min_max_amounts',
            help: 'Remote Order Min and Max Allowed Amounts',
            labelNames: ['networkId', 'asset', 'type'],
            registers: [this.register],
        });
        this.activeExecutors = new prom_client_1.Gauge({
            name: 'active_executors',
            help: 'Active Executors over time',
            labelNames: ['offset'],
            registers: [this.register],
        });
        this.avgExecutorProfitUSDLastDay = new prom_client_1.Gauge({
            name: 'avg_executor_profit_usd_last_day',
            help: 'Average Executor Profit USD last day',
            labelNames: [],
            registers: [this.register],
        });
        this.version = new prom_client_1.Gauge({
            name: 'version',
            help: 'Version',
            labelNames: ['networkId', 'contract'],
            registers: [this.register],
        });
        this.doubleSpend = new prom_client_1.Counter({
            name: 'double_spend_total',
            help: 'Number of double spend',
            registers: [this.register],
        });
        this.gasPrices = new prom_client_1.Gauge({
            name: 'gas_prices',
            help: 'Gas Prices in ether',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.gasLimits = new prom_client_1.Gauge({
            name: 'gas_limits',
            help: 'Gas Limits units from RemoteOrder estimation',
            labelNames: ['networkId', 'lifecycle'],
            registers: [this.register],
        });
        this.gasFees = new prom_client_1.Gauge({
            name: 'gas_fees',
            help: 'Gas Fees in ether from RemoteOrder estimation',
            labelNames: ['networkId', 'lifecycle'],
            registers: [this.register],
        });
        this.gasFeesUSD = new prom_client_1.Gauge({
            name: 'gas_fees_usd',
            help: 'Gas Fees in USD',
            labelNames: ['networkId', 'lifecycle'],
            registers: [this.register],
        });
        this.gasUsed = new prom_client_1.Gauge({
            name: 'gas_used',
            help: 'Gas Used in gwei to execute tx',
            labelNames: ['networkId', 'name'],
            registers: [this.register],
        });
        this.currentEthPrice = new prom_client_1.Gauge({
            name: 'current_eth_price',
            help: 'Current Eth Price',
            labelNames: ['provider'],
            registers: [this.register],
        });
        this.pendingValidationTime = new prom_client_1.Gauge({
            name: 'pending_validation_time',
            help: 'Time taken to validate',
            labelNames: ['name'],
            registers: [this.register],
        });
        this.pendingValidations = new prom_client_1.Gauge({
            name: 'pending_validations',
            help: 'Number of pending validations',
            labelNames: ['name', 'status'],
            registers: [this.register],
        });
        this.pricerEstimateTips = new prom_client_1.Gauge({
            name: 'pricer_estimate_tips',
            help: 'Pricer estimate tips',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.pricerEstimateError = new prom_client_1.Counter({
            name: 'pricer_estimate_error_total',
            help: 'Number of times pricer estimate error',
            labelNames: ['type'],
            registers: [this.register],
        });
        this.overTimeConfirmation = new prom_client_1.Counter({
            name: 'overtime_confirmation',
            help: 'Overtime Confirmation',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.confirmationMissingBid = new prom_client_1.Counter({
            name: 'confirmation_missing_bid_total',
            help: 'Confirmation Missing Bid',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.mismatchingConfirmationId = new prom_client_1.Counter({
            name: 'mismatch_confirmation_id',
            help: 'Mismatching Confirmation Id received via Prophet',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.confirmedRefund = new prom_client_1.Counter({
            name: 'confirmed_refund',
            help: 'Refund claimed on verified execution caught via Prophet',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.invalidConfirmation = new prom_client_1.Counter({
            name: 'invalid_confirmation',
            help: 'Invalid Confirmation',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.prophetAdHocBlockFetch = new prom_client_1.Counter({
            name: 'prophet_adhoc_block_fetch',
            help: 'Adhoc block fetch from Prophet',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.messiahGasUsed = new prom_client_1.Gauge({
            name: 'messiah_gas_useed',
            help: 'Messiah DLQ size',
            labelNames: ['networkId', 'eventName'],
            registers: [this.register],
        });
        this.estimateFee = new prom_client_1.Histogram({
            name: 'estimate_fee',
            help: 'Estimate fee in dollars',
            labelNames: ['label'],
            buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 5, 10],
            registers: [this.register],
        });
        this.estimateFeeDetailed = new prom_client_1.Histogram({
            name: 'estimate_fee_detailed',
            help: 'Estimate fee in dollars',
            labelNames: ['label'],
            buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 5, 10],
            registers: [this.register],
        });
        this.cacheBytesWrite = new prom_client_1.Counter({
            name: 'cache_bytes_write_total',
            help: 'Total payload bytes write to cache',
            labelNames: ['key'],
            registers: [this.register],
        });
        this.messiahDLQSize = new prom_client_1.Gauge({
            name: 'messiah_dlq_size',
            help: 'Messiah DLQ size',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.txFeesUSD = new prom_client_1.Gauge({
            name: 'chain_tx_fees',
            help: 'Tx Fees per chain in USD',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.placerOrdersInProcessing = new prom_client_1.Gauge({
            name: 'placer_orders_in_processing',
            help: 'Number of orders in processing by Placer',
            registers: [this.register],
        });
        this.executorMismatch = new prom_client_1.Counter({
            name: 'executor_mismatch',
            help: 'Executor Mismatch',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.ordersProfitsWei = new prom_client_1.Gauge({
            name: 'orders_profits_wei',
            help: 'Submitted Orders Profit in Wei',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.executorsProfitsWei = new prom_client_1.Gauge({
            name: 'executors_profits_wei',
            help: 'Executor Profit in Wei',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.sourceGasFeesUSD = new prom_client_1.Gauge({
            name: 'source_gas_fees_usd',
            help: 'Gas Fees in USD estimated on source network',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.destinationGasFeesUSD = new prom_client_1.Gauge({
            name: 'destination_gas_fees_usd',
            help: 'Gas Fees in USD estimated on destination network',
            labelNames: ['networkId'],
            registers: [this.register],
        });
        this.totalFeesUSD = new prom_client_1.Gauge({
            name: 'total_fees_usd',
            help: 'Total Fees estimated in USD',
            labelNames: ['sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.protocolFeeUSDForEstimate = new prom_client_1.Gauge({
            name: 'protocol_fee_usd_for_estimate',
            help: 'Protocol Fee in USD used for estimates',
            labelNames: ['describer', 'networkId'],
            registers: [this.register],
        });
        this.protocolFeeWeiForEstimate = new prom_client_1.Gauge({
            name: 'protocol_fee_wei_for_estimate',
            help: 'Protocol Fee used for estimates',
            labelNames: ['describer', 'networkId'],
            registers: [this.register],
        });
        this.protocolFeeFlatUSD = new prom_client_1.Gauge({
            name: 'protocol_fee_flat_usd',
            help: 'Protocol Fee in USD',
            labelNames: ['label', 'networkId'],
            registers: [this.register],
        });
        this.protocolFeeUSD = new prom_client_1.Gauge({
            name: 'protocol_fee_usd',
            help: 'Protocol Fee in USD',
            labelNames: ['lifecycle', 'networkId'],
            registers: [this.register],
        });
        this.protocolFeeWei = new prom_client_1.Gauge({
            name: 'protocol_fee_wei',
            help: 'Protocol Fee in Wei',
            labelNames: ['lifecycle', 'networkId'],
            registers: [this.register],
        });
        this.txTimeMetrics = new prom_client_1.Gauge({
            name: 'tx_time_metrics',
            help: 'Transaction time in seconds for each event',
            labelNames: ['eventName'],
            registers: [this.register],
        });
        this.lifecycleGasFeesUSD = new prom_client_1.Gauge({
            name: 'lifecycle_gas_fees_usd',
            help: 'Gas Fees in USD per lifecycle',
            labelNames: ['lifecycle', 'sourceNetwork', 'destinationNetwork'],
            registers: [this.register],
        });
        this.redshiftQueryDuration = new prom_client_1.Gauge({
            name: 'redshift_query_duration',
            help: 'Redshift query time in seconds for each data',
            labelNames: ['describer'],
            registers: [this.register],
        });
        this.redshiftQueries = new prom_client_1.Counter({
            name: 'redshift_queries',
            help: 'Total number of redshift queries',
            labelNames: ['describer'],
            registers: [this.register],
        });
        this.redshiftFailedQueries = new prom_client_1.Counter({
            name: 'redshift_failed_queries',
            help: 'Total number of failed redshift queries',
            labelNames: ['describer'],
            registers: [this.register],
        });
        this.redshiftQueryRowsReturned = new prom_client_1.Histogram({
            name: 'redshift_query_rows_returned',
            help: 'Number of rows returned by Redshift queries',
            labelNames: ['describer'],
            registers: [this.register],
            buckets: [1, 10, 100, 1000, 10000],
        });
        this.messiahLocalSQSQueueSize = new prom_client_1.Gauge({
            name: 'messiah_local_sqs_queue_size',
            help: 'Messiah local sqs queue size',
            labelNames: ['podNumber'],
            registers: [this.register],
        });
        this.messiahPerMinuteRate = new prom_client_1.Gauge({
            name: 'messiah_rate_per_minute',
            help: 'Messiah per minute rate',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahUpToDateDistance = new prom_client_1.Gauge({
            name: 'messiah_distance',
            help: 'Messiah Distance',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahCurrentTimestamp = new prom_client_1.Gauge({
            name: 'messiah_current_timestamp',
            help: 'Messiah current timestamp',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahOrderOpened = new prom_client_1.Counter({
            name: 'messiah_order_opened',
            help: 'Messiah order opened',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahOrderClosed = new prom_client_1.Counter({
            name: 'messiah_order_closed',
            help: 'Messiah order closed',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahLostOrderClosed = new prom_client_1.Counter({
            name: 'messiah_deleted_order_closed',
            help: 'Messiah order closed',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahBlockScanned = new prom_client_1.Gauge({
            name: 'messiah_block_scanned',
            help: 'Messiah block scanned',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahRelevantTxInBlock = new prom_client_1.Gauge({
            name: 'messiah_relevant_tx_in_block',
            help: 'Messiah relevant tx in block',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahBlockFetchTime = new prom_client_1.Gauge({
            name: 'messiah_block_fetch_time',
            help: 'Messiah block fetch time with receipts',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahBlockProcessingTime = new prom_client_1.Gauge({
            name: 'messiah_block_processing_time',
            help: 'Messiah block processing time',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahTowerSize = new prom_client_1.Gauge({
            name: 'messiah_tower_size',
            help: 'Messiah tower size',
            labelNames: ['networkId', 'podNumber', 'label'],
            registers: [this.register],
        });
        this.messiahTowerExceptions = new prom_client_1.Counter({
            name: 'messiah_tower_exceptions',
            help: 'Messiah tower exceptions',
            labelNames: ['networkId', 'podNumber', 'label'],
            registers: [this.register],
        });
        this.messiahHourlyStatements = new prom_client_1.Gauge({
            name: 'messiah_hourly_statements',
            help: 'Messiah hourly statements',
            labelNames: [],
            registers: [this.register],
        });
        this.messiahHourlyTime = new prom_client_1.Gauge({
            name: 'messiah_hourly_time',
            help: 'Messiah hourly time',
            labelNames: [],
            registers: [this.register],
        });
        this.messiahRestarts = new prom_client_1.Counter({
            name: 'messiah_restarts',
            help: 'Messiah restarts',
            labelNames: ['podNumber'],
            registers: [this.register],
        });
        this.messiahBlocksHeatMap = new prom_client_1.Counter({
            name: 'messiah_blocks_heatmap',
            help: 'Messiah blocks heatmap',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahReceiptsReUsed = new prom_client_1.Counter({
            name: 'messiah_receipts_reused',
            help: 'Messiah receipts reused',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahBlockReUsed = new prom_client_1.Counter({
            name: 'messiah_block_reused',
            help: 'Messiah block reused',
            labelNames: ['networkId', 'podNumber'],
            registers: [this.register],
        });
        this.messiahOrderMissed = new prom_client_1.Counter({
            name: 'messiah_order_missed',
            help: 'Messiah order missed',
            labelNames: ['networkId', 'podNumber', 'eventName', 'status'],
            registers: [this.register],
        });
        if (this.config.environment != types_1.Environment.tests) {
            this.startServer();
        }
    }
    startServer() {
        if (!this.config.prometheus.enabled) {
            logger_1.logger.info('🍆 Prometheus is disabled');
            return;
        }
        this.server = node_http_1.default.createServer(async (req, res) => {
            try {
                if (req.url === '/metrics') {
                    const metrics = await this.register.metrics();
                    res.setHeader('Content-Type', this.register.contentType);
                    res.end(metrics);
                }
                else if (req.url === '/healthz') {
                    res.setHeader('Content-Type', 'text/plain');
                    if (this.config.featureFlags.healthCheckAlwaysTrue) {
                        this.isHealthy = true;
                    }
                    res.statusCode = this.isHealthy ? 200 : 500;
                    res.end(JSON.stringify({ isHealthy: this.isHealthy }));
                }
                else {
                    res.statusCode = 404;
                    res.end('Not found.');
                }
            }
            catch (error) {
                res.statusCode = 500;
                res.end(error.toString());
            }
        });
        // @TODO, bug below, prometheus.port is an object
        const port = this.alternativePort || this.config.prometheus.port;
        this.server.listen(port, () => {
            logger_1.logger.debug(`Prometheus started on ${port}`);
        });
    }
    stopServer() {
        this.server.close();
    }
    updateTxTimeMetric(eventName, start, end) {
        const txTimeSec = end > 0 && start > 0 && end >= start ? end - start : null;
        if (txTimeSec && txTimeSec > 0) {
            this.txTimeMetrics.set({ eventName }, txTimeSec);
        }
    }
}
exports.Prometheus = Prometheus;
//# sourceMappingURL=prometheus.js.map