-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·31 lines (27 loc) · 961 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'use strict'
const cluster = require('cluster')
const { MASTER_ERRORS, WORKER_ERRORS } = require('./lib/errors.js')
const { MASTER_MESSAGES_RUN, WORKER_MESSAGES_RUN } = require('./messages')
const runMasterMessage = (worker, msg) => {
const { message, data } = msg
const exec = MASTER_MESSAGES_RUN[message]
if (!exec) throw new Error(MASTER_ERRORS.NO_MESSAGE(message))
exec(worker, data)
}
const runWorkerMessage = (msg) => {
const worker = cluster.worker
const { message, data } = msg
const exec = WORKER_MESSAGES_RUN[message]
if (!exec) throw new Error(WORKER_ERRORS.NO_MESSAGE(message))
exec(worker, data)
}
const setupCluster = () => {
// Manage messages in master and workers
if (cluster.isMaster) {
cluster.on('message', runMasterMessage)
} else if (cluster.isWorker) {
const worker = cluster.worker
worker.on('message', runWorkerMessage)
}
}
module.exports = { runMasterMessage, runWorkerMessage, setupCluster }