"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("../../constants");
const cluster = require("cluster");
const events_1 = require("events");
const types_1 = require("@deepstream/types");
if (cluster.isWorker) {
    process.on('message', (serializedMessage) => {
        const { serverName, message } = JSON.parse(serializedMessage);
        VerticalClusterNode.emitter.emit(constants_1.TOPIC[message.topic], message, serverName);
    });
}
if (cluster.isMaster) {
    cluster.on('message', (worker, serializedMessage, handle) => {
        for (const id in cluster.workers) {
            const fromWorker = cluster.workers[id];
            if (fromWorker !== worker) {
                worker.send(serializedMessage);
            }
        }
    });
}
class VerticalClusterNode extends types_1.DeepstreamPlugin {
    constructor(pluginConfig, services, config) {
        super();
        this.config = config;
        this.description = 'Vertical Cluster Message Bus';
        this.callbacks = new Map();
    }
    send(message, metaData) {
        process.send(JSON.stringify({ message, fromServer: this.config.serverName }));
    }
    sendDirect(serverName, message, metaData) {
        process.send(JSON.stringify({ toServer: serverName, fromServer: this.config.serverName, message }));
    }
    subscribe(stateRegistryTopic, callback) {
        this.callbacks.set(constants_1.TOPIC[stateRegistryTopic], callback);
        VerticalClusterNode.emitter.on(constants_1.TOPIC[stateRegistryTopic], callback);
    }
    async close() {
        for (const [topic, callback] of this.callbacks) {
            VerticalClusterNode.emitter.off(topic, callback);
        }
    }
}
exports.VerticalClusterNode = VerticalClusterNode;
VerticalClusterNode.emitter = new events_1.EventEmitter();
//# sourceMappingURL=vertical-cluster-node.js.map