-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (102 loc) · 3.39 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fast_unique_id_1 = require("fast-unique-id");
class CPC {
constructor() {
this.response = {};
this.handler = { M: {}, W: {} };
process.on('message', msg => {
if (msg.t !== 'cpc')
return;
switch (msg.d) {
case 'M':
if (!this.response[msg.i])
return;
this.response[msg.i](...msg.a);
delete this.response[msg.i];
break;
case 'W':
if (this.handler[msg.d][msg.m])
this.handler[msg.d][msg.m](msg.r, (...args) => (function send() {
process.send({
t: 'cpc',
d: msg.d,
i: msg.i,
a: args
}, (err) => {
if (err)
setTimeout(send, 500);
});
})());
break;
}
});
}
tunnel(worker) {
worker.on('message', (msg) => {
if (msg.t !== 'cpc')
return;
switch (msg.d) {
case 'M':
if (this.handler[msg.d][msg.m])
this.handler[msg.d][msg.m](msg.r, (...args) => (function send() {
worker.send({
t: 'cpc',
d: msg.d,
i: msg.i,
a: args
}, null, (err) => {
if (err)
setTimeout(send, 500);
});
})());
break;
case 'W':
if (!this.response[msg.i])
return;
this.response[msg.i](...msg.a);
delete this.response[msg.i];
break;
}
});
worker['sendJob'] = (method, req, res) => this.sendJob(method, req, res, worker, 'W');
return worker;
}
sendJob(method, req, res, destination = process, to = 'M') {
if (res) {
const id = fast_unique_id_1.fast();
destination.send({
t: 'cpc',
d: to,
m: method,
i: id,
r: req
}, (err) => {
if (err)
setTimeout(() => this.sendJob(method, req, res, destination, to), 500);
else
this.response[id] = res;
});
}
else
destination.send({
t: 'cpc',
d: to,
m: method,
r: req
}, (err) => {
if (err)
setTimeout(() => this.sendJob(method, req, res, destination, to), 500);
});
}
onWorker(method, handler) {
this.handler['M'][method] = handler;
return this;
}
onMaster(method, handler) {
this.handler['W'][method] = handler;
return this;
}
}
exports.default = CPC;
//# sourceMappingURL=index.js.map