/
CnCServer.js
160 lines (135 loc) · 5.58 KB
/
CnCServer.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
'use strict';
const ws = require('ws');
const {assert} = require('chai');
const URL = require('./URL');
const log = require('./logger')({hostname: 'background', MODULE: 'CnCServer'});
const {WS_CLOSE_NORMAL, WS_CLOSE_POLICY_VIOLATION} = require('./webSocketCodes');
const CnCServerConnection = require('./CnCServerConnection');
class CnCServer {
constructor({httpServer}) {
assert.isOk(httpServer, 'Invalid argument `httpServer`');
this.httpServer = httpServer;
this.wsServer = null;
this.activeConnection = null;
this.activeInstanceId = null;
this.runScriptCount = 0;
this._rejectPendingRunScript = new Set();
this._resolveWaitForActiveConnection = [];
this.lastRunScriptBegin = NaN;
this.lastRunScriptEnd = NaN;
Object.seal(this);
}
async start() {
this.wsServer = new ws.Server({
server: this.httpServer,
path: '/openrunner-cnc',
});
this.wsServer.on('connection', (webSocket, httpRequest) => this.handleNewConnection(webSocket, httpRequest));
this.wsServer.on('error', err => log.error({err}, 'WebSocket Server error'));
}
async stop() {
this._rejectAllPendingRunScript(Error('The server is stopping'));
this.destroyActiveConnection(WS_CLOSE_NORMAL, 'Bye!');
this.activeConnection = null;
if (this.wsServer) {
this.wsServer.close();
}
this.wsServer = null;
}
_rejectAllPendingRunScript(err) {
const rejects = [...this._rejectPendingRunScript];
this._rejectPendingRunScript.clear();
rejects.forEach(reject => reject(err));
}
handleNewConnection(webSocket, httpRequest) {
try {
const {connection: {remoteAddress, remoteFamily, remotePort}} = httpRequest;
const oldInstanceId = this.activeInstanceId;
log.info(
{remoteAddress, remoteFamily, remotePort, url: httpRequest.url, oldInstanceId},
'Incoming WebSocket connection'
);
const url = new URL(`ws://localhost${httpRequest.url}`);
const instanceId = url.searchParams.get('instanceId');
if (oldInstanceId !== instanceId) {
log.warn({oldInstanceId, instanceId}, 'The browser has (re)started');
this._rejectAllPendingRunScript(Error('The browser has restarted unexpectedly'));
this.destroyActiveConnection(
WS_CLOSE_POLICY_VIOLATION,
'Closing old connection because a new connection with a new instanceId has been made'
);
this.activeConnection = new CnCServerConnection();
this.activeInstanceId = instanceId;
}
// currently only a single connection per server is supported, we could extend this later by creating multiple
// instances of CnCServerConnection, and indexing them by the instanceId sent by the client.
this.activeConnection.setActiveWebSocket(webSocket, httpRequest);
this._resolveWaitForActiveConnection.forEach(resolve => resolve());
this._resolveWaitForActiveConnection = [];
}
catch (err) {
log.error({err}, 'Error during event handler WebSocket Server => connect');
}
}
async runScript({scriptContent, stackFileName}) {
assert.isOk(this.activeConnection, 'There is no active connection from the web browser');
++this.runScriptCount;
this.lastRunScriptBegin = Date.now();
let rejectPending;
try {
return await Promise.race([
new Promise((resolve, reject) => {
rejectPending = reject;
this._rejectPendingRunScript.add(rejectPending);
}),
this.activeConnection.runScript({scriptContent, stackFileName}),
]);
}
finally {
this._rejectPendingRunScript.delete(rejectPending);
this.lastRunScriptEnd = Date.now();
}
}
async reportCodeCoverage() {
assert.isOk(this.activeConnection, 'There is no active connection from the web browser');
return await this.activeConnection.call('reportCodeCoverage');
}
async waitForActiveConnection() {
if (this.activeConnection && this.activeConnection.hasActiveConnection) {
return;
}
await new Promise((resolve) => {
this._resolveWaitForActiveConnection.push(resolve);
});
}
closeActiveWebSocket(wsCode, reason) {
const {activeConnection} = this;
if (!activeConnection) {
return false;
}
return activeConnection.closeActiveWebSocket(wsCode, reason);
}
destroyActiveConnection(wsCode, reason) {
const {activeConnection} = this;
if (!activeConnection) {
return false;
}
this._rejectAllPendingRunScript(Error(reason));
this.activeConnection = null;
activeConnection.destroy(wsCode, reason);
return true;
}
get hasActiveConnection() {
return Boolean(this.activeConnection && this.activeConnection.hasActiveConnection);
}
get lastSuccessfulPing() {
return this.activeConnection ? this.activeConnection.lastSuccessfulPing : NaN;
}
get isRunningScript() {
return Boolean(this.activeConnection && this.activeConnection.isRunningScript);
}
get lastReportedVersion() {
return this.activeConnection && this.activeConnection.lastReportedVersion;
}
}
module.exports = CnCServer;