This repository has been archived by the owner on Nov 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
62 lines (60 loc) · 1.58 KB
/
worker.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
const { randomId } = require("./common");
class Worker {
constructor(transport) {
this.transport = transport;
this.transport.on("message", data => this.handleData(data));
this.transport.on("connect", () => this.handleConnect());
this.transport.on("error", error => this.onError(error));
this.functions = new Map();
this.retries = 10;
}
register({ path, fn }) {
this.functions.set(path, fn);
}
getFn(path) {
return this.functions.get(path);
}
connect() {
this.transport.connect();
}
onError(error) {
const { code } = error;
if (code == "ECONNREFUSED") {
if (!this.retries)
throw new Error("Out of retries, cannot connect to the server.");
this.retries--;
setTimeout(() => this.connect(), 100);
}
}
handleConnect() {
this.retries = 10;
const id = randomId(32);
const paths = [...this.functions.keys()];
this.send(
{
instruction: "registerWorker",
details: { paths },
},
id
);
}
handleData(data) {
const { instruction, details, id } = data;
if (instruction == "call") this.handleCallInstruction(details, id);
}
async handleCallInstruction(details, id) {
const { path, args } = details;
const fn = this.getFn(path);
const result = await fn(...args);
this.sendResult(result, id);
}
async sendResult(result, id) {
result = await result;
const data = { instruction: "result", details: { result } };
this.send(data, id);
}
send(data, id) {
this.transport.send({ ...data, id });
}
}
module.exports.Worker = Worker;