"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FullClusteredWorker = 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 api_1 = require("../services/api");
const event_1 = require("../services/event");
const p2p_1 = require("../services/p2p");
const storage_1 = require("../services/storage");
const worker_1 = require("../services/worker");
const parseArgv_1 = __importDefault(require("../utils/parseArgv"));
require("../utils/polyfills");
const args = (0, parseArgv_1.default)([], [{ arg: 'DEBUG', type: 'bool' }]);
const services = [];
const FullClusteredWorker = 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);
    if (cluster_1.default.isPrimary) {
        services.push(p2p_1.P2P);
        if (args.DEBUG) {
            services.push(api_1.Api);
        }
        else {
            services.push(worker_1.Worker);
        }
    }
    else {
        services.push(api_1.Api);
    }
    modules_1.Modules.loadConfigured();
    for (const service of services) {
        await service.start();
    }
};
exports.FullClusteredWorker = FullClusteredWorker;
let stopping = false;
const stop = async () => {
    if (stopping) {
        logger_1.default.error('Force stopping all workers');
        process.exit(1);
    }
    stopping = true;
    setTimeout(() => {
        logger_1.default.error('All workers did not shut down gracefully after 30 seconds, exiting');
        process.exit(1);
    }, 30 * 1000).unref();
    logger_1.default.info(`Shutting down ${cluster_1.default.isPrimary ? 'primary' : 'worker'} process ${process.pid}`);
    for (const service of services.reverse()) {
        await service.stop();
    }
    if (!cluster_1.default.isPrimary) {
        process.removeAllListeners();
    }
};
if (require.main === module) {
    (0, exports.FullClusteredWorker)();
}
//# sourceMappingURL=all.js.map