-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathfastboot-app-server.js
More file actions
244 lines (204 loc) · 6.34 KB
/
fastboot-app-server.js
File metadata and controls
244 lines (204 loc) · 6.34 KB
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"use strict";
const assert = require('assert');
const cluster = require('cluster');
const os = require('os');
const path = require('path');
const serialize = require('./utils/serialization').serialize;
class FastBootAppServer {
constructor(options) {
options = options || {};
this.distPath = options.distPath;
this.downloader = options.downloader;
this.notifier = options.notifier;
this.cache = options.cache;
this.ui = options.ui;
this.gzip = options.gzip;
this.host = options.host;
this.port = options.port;
this.username = options.username;
this.password = options.password;
this.httpServer = options.httpServer;
this.buildSandboxGlobals = options.buildSandboxGlobals;
this.chunkedResponse = options.chunkedResponse;
this.log = options.log;
this.workerPath = options.workerPath;
if (!this.ui) {
let UI = require('./ui');
this.ui = new UI();
}
this.propagateUI();
this.workerCount = options.workerCount ||
(process.env.NODE_ENV === 'test' ? 1 : null) ||
os.cpus().length;
this._clusterInitialized = false;
assert(this.distPath || this.downloader, "FastBootAppServer must be provided with either a distPath or a downloader option.");
assert(!(this.distPath && this.downloader), "FastBootAppServer must be provided with either a distPath or a downloader option, but not both.");
}
start() {
return this.initializeApp()
.then(() => this.subscribeToNotifier())
.then(() => this.forkWorkers())
.then(() => {
if (this.initializationError) {
this.broadcast({ event: 'error', error: this.initializationError.stack });
}
})
.catch(err => {
this.ui.writeLine(err.stack);
})
.finally(() => {
this._clusterInitialized = true;
});
}
stop() {
this.broadcast({ event: 'shutdown' });
}
propagateUI() {
if (this.downloader) { this.downloader.ui = this.ui; }
if (this.notifier) { this.notifier.ui = this.ui; }
if (this.cache) { this.cache.ui = this.ui; }
if (this.httpServer) { this.httpServer.ui = this.ui; }
}
initializeApp() {
// If there's a downloader, it returns a promise for downloading the app
if (this.downloader) {
return this.downloadApp()
.catch(err => {
this.ui.writeLine('Error downloading app');
this.ui.writeLine(err.stack);
this.initializationError = err;
});
}
this.ui.writeLine(`using distPath; path=${this.distPath}`);
return Promise.resolve();
}
downloadApp() {
this.ui.writeLine('downloading app');
return this.downloader.download()
.then(distPath => {
this.distPath = distPath;
})
.catch(err => {
if (err.name.match(/AppNotFound/)) {
this.ui.writeError('app not downloaded');
} else {
throw err;
}
});
}
subscribeToNotifier() {
if (this.notifier) {
this.ui.writeLine('subscribing to update notifications');
return this.notifier.subscribe(() => {
this.ui.writeLine('reloading server');
this.initializeApp()
.then(() => this.reload());
})
.catch(err => {
this.ui.writeLine('Error subscribing');
this.ui.writeLine(err.stack);
this.initializationError = err;
});
}
}
/**
* send message to worker
*
* @method broadcast
* @param {Object} message
*/
broadcast(message) {
let workers = cluster.workers;
for (let id in workers) {
workers[id].send(message);
}
}
reload() {
this.broadcast({ event: 'reload', distPath: this.distPath });
}
forkWorkers() {
let promises = [];
// https://nodejs.org/api/cluster.html#cluster_cluster_setupprimary_settings
// Note: cluster.setupPrimary in v16.0.0
cluster.setupMaster(this.clusterSetupPrimary());
for (let i = 0; i < this.workerCount; i++) {
promises.push(this.forkWorker());
}
return Promise.all(promises);
}
forkWorker() {
let worker = cluster.fork(this.buildWorkerEnv());
this.ui.writeLine(`Worker ${worker.process.pid} forked`);
let firstBootResolve;
let firstBootReject;
const firstBootPromise = new Promise((resolve, reject) => {
firstBootResolve = resolve;
firstBootReject = reject;
});
if (this._clusterInitialized) {
firstBootResolve();
}
worker.on('online', () => {
this.ui.writeLine(`Worker ${worker.process.pid} online.`);
});
worker.on('message', (message) => {
if (message.event === 'http-online') {
this.ui.writeLine(`Worker ${worker.process.pid} healthy.`);
firstBootResolve();
}
});
worker.on('exit', (code, signal) => {
let error;
if (signal) {
error = new Error(`Worker ${worker.process.pid} killed by signal: ${signal}`);
} else if (code !== 0) {
error = new Error(`Worker ${worker.process.pid} exited with error code: ${code}`);
} else {
error = new Error(`Worker ${worker.process.pid} exited gracefully. It should only exit when told to do so.`);
}
if (!this._clusterInitialized) {
// Do not respawn for a failed first launch.
firstBootReject(error);
} else {
// Do respawn if you've ever successfully been initialized.
this.ui.writeLine(error);
this.forkWorker();
}
});
return firstBootPromise;
}
buildWorkerEnv() {
let env = {};
if (this.distPath) {
env.FASTBOOT_DIST_PATH = this.distPath;
}
return env;
}
/**
* Extension point to allow configuring the default fork configuration.
*
* @method clusterSetupPrimary
* @returns {Object}
* @public
*/
clusterSetupPrimary() {
const workerOptions = {
distPath: this.distPath || process.env.FASTBOOT_DIST_PATH,
cache: this.cache,
gzip: this.gzip,
host: this.host,
port: this.port,
username: this.username,
password: this.password,
httpServer: this.httpServer,
buildSandboxGlobals: this.buildSandboxGlobals,
chunkedResponse: this.chunkedResponse,
};
const workerPath = this.workerPath || path.join(__dirname, './worker-start.js');
return {
exec: workerPath,
args: [serialize(workerOptions)]
};
}
}
module.exports = FastBootAppServer;