-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.ts
111 lines (92 loc) · 2.23 KB
/
node.ts
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
103
104
105
106
107
108
109
110
111
import { ConfluxNode, type ConfluxConfig } from "./conflux";
class NodeManager {
private node: ConfluxNode | null = null;
private isStarted: boolean = false;
constructor() {
this.setupMessageHandlers();
this.setupErrorHandlers();
this.setupSignalHandlers();
}
private setupMessageHandlers = () => {
process.on("message", this.handleMessage);
};
private setupErrorHandlers = () => {
process.on("uncaughtException", this.handleError);
};
private setupSignalHandlers = () => {
process.on("SIGTERM", () => {
this.exit(0);
});
process.on("SIGINT", () => {
this.exit(0);
});
};
private handleMessage = (message: {
type: string;
config?: ConfluxConfig;
}) => {
if (!process.send) return;
switch (message.type) {
case "start":
this.handleStart(message.config);
break;
case "stop":
this.handleStop();
break;
default:
this.sendError(`Unknown message type: ${message.type}`);
}
};
private handleStart = (config?: ConfluxConfig) => {
if (!config) {
this.sendError("No configuration provided for start");
return;
}
if (this.isStarted) {
this.sendError("Node is already started");
return;
}
if (!this.node) {
this.node = new ConfluxNode();
}
this.node.startNode(config, (err) => {
if (err) {
this.sendError(err.message);
} else {
this.isStarted = true;
this.sendMessage("started");
}
});
};
private handleStop = () => {
if (!this.node) {
this.sendMessage("stopped");
this.exit(0);
return;
}
this.node.stopNode((err) => {
if (err) {
this.sendError(err.message);
} else {
this.isStarted = false;
this.node = null;
this.sendMessage("stopped");
this.exit(0);
}
});
};
private handleError = (err: Error) => {
this.sendError(err.message);
this.exit(1);
};
private sendMessage = (type: string) => {
process.send?.({ type });
};
private sendError = (error: string) => {
process.send?.({ type: "error", error });
};
private exit = (code: number) => {
process.exit(code);
};
}
new NodeManager();