import { PlataClusterManager } from "../cluster" export class PlataClusterController { public readonly clusterManager: PlataClusterManager public readonly clusterName: string private msgId = 0 private workersPids: Set = new Set() constructor(clusterManager: PlataClusterManager, name: string) { this.clusterManager = clusterManager this.clusterName = name } public async loadWorkers(): PlataPromise { const result: PlataResult = await new Promise(resolve => { const id = `${process.pid}_${this.msgId++}_GETPID` const cleanUp = () => { process.removeListener('message', onResponse) } const onResponse = (event: Cluster.Actions) => { if (event.action !== `GET-PIDS-CLUSTER-RESULT-${id}`) return ; cleanUp() const e: Extract = event as any return resolve(e.msg) } process.on('message', onResponse) this.clusterManager.send({ action: 'GET-PIDS-CLUSTER', msg: { id, name: this.clusterName } }) }) if (result.errorID !== undefined) { return result } const pids = new Set(result) pids.delete(process.pid) this.workersPids = pids return true } public getWorkersPids(): number[] { return [...this.workersPids] } public setOnDeadWorker(handle: (newPid: number, oldPid: number) => Promise) { const handleMessage = ((event: Cluster.Actions) => { if (event.action !== 'DEAD-WORKER-NOTIFY') return if (event.msg.clusterName !== this.clusterName) return this.workersPids.delete(event.msg.pidDead) this.workersPids.add(event.msg.newPid) return handle(event.msg.newPid, event.msg.pidDead) }).bind(this) process.on('message', handleMessage) } public async sendMsgToPID(pid: number, event: Cluster.UserActions): PlataPromise { if (!this.workersPids.has(pid)) return { errorID: 'PLCLUCONTSNDPID001', msg: `PID ${pid} não existe no cluster` } return this.clusterManager.sendToWorkerPid(pid, event) } public async setOnMessage(handle: (msg: Cluster.UserActions) => Promise) { const handleMessage = ((msg) => { if (msg.action === undefined) return return (handle as any)(msg) }).bind(this) process.on('message', handleMessage) } }