"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.P2pWorker = void 0;
const cluster_1 = __importDefault(require("cluster"));
require("source-map-support/register");
const logger_1 = __importDefault(require("../logger"));
const modules_1 = require("../modules");
const config_1 = require("../services/config");
const event_1 = require("../services/event");
const p2p_1 = require("../services/p2p");
const storage_1 = require("../services/storage");
require("../utils/polyfills");
const services = [];
const P2pWorker = async () => {
    process.on('unhandledRejection', (error) => {
        console.error('Unhandled Rejection at:', error.stack || error);
        stop();
    });
    process.on('SIGTERM', stop);
    process.on('SIGINT', stop);
    services.push(storage_1.Storage, event_1.Event);
    const { CHAIN: chain, NETWORK: network } = process.env;
    modules_1.Modules.loadConfigured({ chain, network }); // loads all if no chain and network specified
    // start a particular chain and network, or all of them
    if (chain && network) {
        const chainConfig = config_1.Config.chainConfig({ chain, network });
        const p2pClass = p2p_1.P2P.get(chain, network);
        const worker = new p2pClass({
            chain,
            network,
            chainConfig
        });
        services.push(worker);
    }
    else {
        services.push(p2p_1.P2P);
    }
    for (const service of services) {
        try {
            await service.start();
        }
        catch (e) {
            logger_1.default.error('P2P Worker died: %o', e.stack || e.message || e);
        }
    }
};
exports.P2pWorker = P2pWorker;
let stopping = false;
const stop = async () => {
    if (stopping) {
        logger_1.default.warn('Force stopping P2P Worker');
        process.exit(1);
    }
    stopping = true;
    setTimeout(() => {
        logger_1.default.warn('P2P Worker did not shut down gracefully after 30 seconds, exiting');
        process.exit(1);
    }, 30 * 1000).unref();
    logger_1.default.info(`Shutting down P2P pid ${process.pid}`);
    for (const service of services.reverse()) {
        await service.stop();
    }
    if (!cluster_1.default.isPrimary) {
        process.removeAllListeners();
    }
};
if (require.main === module) {
    (0, exports.P2pWorker)();
}
//# sourceMappingURL=p2p.js.map