forked from pyraxo/haru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (43 loc) · 1.25 KB
/
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const fs = require('fs')
const path = require('path')
const pm2 = require('pm2')
global.Promise = require('bluebird')
require('longjohn')
require('dotenv-safe').config({
path: path.join(__dirname, '.env'),
allowEmptyValues: true
})
!fs.existsSync('./logs') && fs.mkdirSync('./logs')
const procCount = parseInt(process.env['CLIENT_PROCESSES'], 10)
process.on('unhandledRejection', (r, p) =>
r && console.error('Unhandled rejection:', p, 'reason:', r.message)
)
pm2.launchBus((err, bus) => {
if (err) console.error(err)
bus.on('process:msg', packet => {
const data = packet.raw
const payload = {
op: data.op,
d: data.d,
origin: packet.process.pm_id % procCount,
code: data.code
}
if (data.dest === -1) {
// warning: this assumes id count starts from 0
// recommended to query pm2 via connect+list first
for (let i = 0; i < procCount; i++) {
pm2.sendDataToProcessId(i, {
type: 'process:msg',
data: payload,
topic: 'broadcast'
}, err => err && console.error(err))
}
} else {
pm2.sendDataToProcessId(data.dest, {
type: 'process:msg',
data: payload,
topic: 'relay'
}, err => err && console.error(err))
}
})
})