"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Worker = exports.WorkerService = void 0;
const cluster_1 = __importDefault(require("cluster"));
const events_1 = require("events");
const config_1 = __importDefault(require("../config"));
const Loggify_1 = require("../decorators/Loggify");
const logger_1 = __importDefault(require("../logger"));
const parseArgv_1 = __importDefault(require("../utils/parseArgv"));
const args = (0, parseArgv_1.default)([], [{ arg: 'DEBUG', type: 'bool' }]);
let WorkerService = class WorkerService extends events_1.EventEmitter {
    constructor() {
        super(...arguments);
        this.workers = new Array();
        this.shuttingDown = false;
    }
    async start() {
        if (cluster_1.default.isPrimary) {
            logger_1.default.verbose(`Master ${process.pid} is running`);
            if (!args.DEBUG) {
                for (let worker = 0; worker < config_1.default.numWorkers; worker++) {
                    this.startWorker(worker, 0);
                }
            }
            const startedPromises = this.workers.map(worker => worker.started);
            return Promise.all(startedPromises);
        }
        else {
            logger_1.default.verbose(`Worker ${process.pid} started`);
            return;
        }
    }
    async stop() {
        this.shuttingDown = true;
        // Disconnect all workers gracefully
        for (const workerData of this.workers) {
            if (workerData.worker.isConnected()) {
                workerData.worker.disconnect();
            }
        }
    }
    startWorker(workerId, restartCount = 0) {
        const isRestart = restartCount > 0;
        if (this.shuttingDown) {
            if (isRestart) {
                logger_1.default.info(`Not restarting worker ${workerId} - service is shutting down`);
            }
            return;
        }
        const newWorker = cluster_1.default.fork();
        if (isRestart) {
            logger_1.default.warn(`Restarting worker ${workerId} (restart #${restartCount})`);
        }
        else {
            logger_1.default.verbose(`Starting worker ${workerId}`);
        }
        newWorker.on('message', (msg) => {
            this.emit(msg.id, msg);
        });
        newWorker.on('exit', (code, signal) => {
            const exitReason = code !== 0 || signal ? 'crashed' : 'stopped gracefully';
            logger_1.default[code == 0 ? 'info' : 'error'](`Worker ${newWorker.process.pid} ${exitReason} (code: ${code}, signal: ${signal})`);
            const workerIndex = this.workers.findIndex(w => w.worker === newWorker);
            if (workerIndex > -1) {
                const workerData = this.workers[workerIndex];
                this.workers.splice(workerIndex, 1);
                if ((code !== 0 || signal) && !this.shuttingDown) {
                    logger_1.default.info(`Scheduling worker ${workerData.workerId} restart in 5 seconds...`);
                    setTimeout(() => {
                        this.startWorker(workerData.workerId, workerData.restartCount + 1);
                    }, 5 * 1000);
                }
            }
        });
        const started = new Promise(resolve => {
            newWorker.on('listening', () => {
                logger_1.default.info(`Worker ${workerId} successfully ${isRestart ? 're' : ''}started (pid: ${newWorker.process.pid})`);
                resolve();
            });
        });
        this.workers.push({
            worker: newWorker,
            active: false,
            started,
            workerId,
            restartCount
        });
    }
    sendTask(task, argument, done) {
        const worker = this.workers.shift();
        if (worker) {
            this.workers.push(worker);
            const id = (Date.now() * Math.random()).toString();
            this.once(id, function (result) {
                done(result.error);
            });
            worker.worker.send({ task, argument, id });
        }
    }
    workerCount() {
        return this.workers.length;
    }
};
exports.WorkerService = WorkerService;
exports.WorkerService = WorkerService = __decorate([
    Loggify_1.LoggifyClass
], WorkerService);
exports.Worker = new WorkerService();
//# sourceMappingURL=worker.js.map