@colyseus/tools 0.15.45 → 0.15.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colyseus/tools",
3
- "version": "0.15.45",
3
+ "version": "0.15.47",
4
4
  "description": "Colyseus Tools for Production",
5
5
  "input": "./src/index.ts",
6
6
  "main": "./build/index.js",
@@ -26,6 +26,7 @@
26
26
  "url": "https://github.com/colyseus/colyseus/issues"
27
27
  },
28
28
  "files": [
29
+ "pm2",
29
30
  "html",
30
31
  "build",
31
32
  "LICENSE",
@@ -43,9 +44,11 @@
43
44
  "node-os-utils": "^1.3.7",
44
45
  "cors": "^2.8.5",
45
46
  "dotenv": "^8.2.0",
46
- "express": "^4.16.2",
47
- "@colyseus/core": "^0.15.54",
48
- "@colyseus/ws-transport": "^0.15.2"
47
+ "express": "^4.16.2"
48
+ },
49
+ "peerDependencies": {
50
+ "@colyseus/core": "0.15.x",
51
+ "@colyseus/ws-transport": "0.15.x"
49
52
  },
50
53
  "publishConfig": {
51
54
  "access": "public"
@@ -0,0 +1,312 @@
1
+ /**
2
+ * PM2 Agent for no downtime deployments on Colyseus Cloud.
3
+ *
4
+ * How it works:
5
+ * - New process(es) are spawned (MAX_ACTIVE_PROCESSES/2)
6
+ * - NGINX configuration is updated so new traffic only goes through the new process
7
+ * - Old processes are asynchronously and gracefully stopped.
8
+ * - The rest of the processes are spawned/reactivated.
9
+ */
10
+ const pm2 = require('pm2');
11
+ const fs = require('fs');
12
+ const cst = require('pm2/constants');
13
+ const io = require('@pm2/io');
14
+ const path = require('path');
15
+ const shared = require('./shared');
16
+
17
+ const opts = { env: process.env.NODE_ENV || "production", };
18
+ let config = undefined;
19
+
20
+ io.initModule({
21
+ pid: path.resolve('/var/run/colyseus-agent.pid'),
22
+ widget: {
23
+ type: 'generic',
24
+ logo: 'https://colyseus.io/images/logos/logo-dark-color.png',
25
+ theme : ['#9F1414', '#591313', 'white', 'white'],
26
+ }
27
+ });
28
+
29
+ pm2.connect(function(err) {
30
+ if (err) {
31
+ console.error(err.stack || err);
32
+ process.exit();
33
+ }
34
+ console.log('PM2 post-deploy agent is up and running...');
35
+
36
+ /**
37
+ * Remote actions
38
+ */
39
+ io.action('post-deploy', async function (arg0, reply) {
40
+ const [cwd, ecosystemFilePath] = arg0.split(':');
41
+ console.log("Received 'post-deploy' action!", { cwd, config: ecosystemFilePath });
42
+
43
+ let replied = false;
44
+
45
+ //
46
+ // Override 'reply' to decrement amount of concurrent deployments
47
+ //
48
+ const onReply = function() {
49
+ if (replied) { return; }
50
+ replied = true;
51
+ reply.apply(null, arguments);
52
+ }
53
+
54
+ try {
55
+ config = await shared.getAppConfig(ecosystemFilePath);
56
+ opts.cwd = cwd;
57
+ postDeploy(cwd, onReply);
58
+
59
+ } catch (err) {
60
+ onReply({ success: false, message: err?.message });
61
+ }
62
+ });
63
+ });
64
+
65
+ const restartingAppIds = new Set();
66
+
67
+ function postDeploy(cwd, reply) {
68
+ shared.listApps(function(err, apps) {
69
+ if (err) {
70
+ console.error(err);
71
+ return reply({ success: false, message: err?.message });
72
+ }
73
+
74
+ // first deploy, start all processes
75
+ if (apps.length === 0) {
76
+ return pm2.start(config, {...opts}, (err, result) => {
77
+ reply({ success: !err, message: err?.message });
78
+ updateAndSave(err, result);
79
+ });
80
+ }
81
+
82
+ console.log("apps[0].pm2_env.pm_cwd =>", apps[0].pm2_env.pm_cwd);
83
+ console.log("cwd =>", cwd);
84
+
85
+ //
86
+ // detect if cwd has changed, and restart PM2 if it has
87
+ //
88
+ if (apps[0].pm2_env.pm_cwd !== cwd) {
89
+ console.log("cwd has changed. restarting PM2...");
90
+
91
+ //
92
+ // remove all and start again with new cwd
93
+ //
94
+ return pm2.delete(shared.NAMESPACE, function(err) {
95
+ // start again
96
+ // (TODO: make sure CWD is actually changed after this...)
97
+ pm2.start(config, { ...opts }, (err, result) => {
98
+ reply({ success: !err, message: err?.message });
99
+ updateAndSave(err, result);
100
+ });
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Graceful restart logic:
106
+ * List of PM2 app envs to stop or restart
107
+ */
108
+ const appsToStop = [];
109
+ const appsStopped = [];
110
+ let numAppsStopping = 0;
111
+ let numTotalApps = undefined;
112
+
113
+ apps.forEach((app) => {
114
+ const env = app.pm2_env;
115
+
116
+ /**
117
+ * Asynchronously teardown/stop processes with active connections
118
+ */
119
+ if (env.status === cst.STOPPED_STATUS) {
120
+ appsStopped.push(env);
121
+
122
+ } else if (env.status !== cst.STOPPING_STATUS) {
123
+ appsToStop.push(env);
124
+
125
+ } else if (!restartingAppIds.has(env.pm_id)) {
126
+ numAppsStopping++;
127
+ }
128
+ });
129
+
130
+ /**
131
+ * - Start new process
132
+ * - Update NGINX config to expose only the new process
133
+ * - Stop old processes
134
+ * - Spawn/reactivate the rest of the processes (shared.MAX_ACTIVE_PROCESSES)
135
+ */
136
+ const onFirstAppsStart = (initialApps, err, result) => {
137
+ /**
138
+ * release post-deploy action while proceeding with graceful restart of other processes
139
+ */
140
+ reply({ success: !err, message: err?.message });
141
+
142
+ if (err) { return console.error(err); }
143
+
144
+ let numActiveApps = initialApps.length + restartingAppIds.size;
145
+
146
+ /**
147
+ * - Write NGINX config to expose only the new active process
148
+ * - The old ones processes will go down asynchronously (or will be restarted)
149
+ */
150
+ writeNginxConfig(initialApps);
151
+
152
+ //
153
+ // Asynchronously stop/restart apps with active connections
154
+ // (They make take from minutes up to hours to stop)
155
+ //
156
+ appsToStop.forEach((app_env) => {
157
+ if (numActiveApps < shared.MAX_ACTIVE_PROCESSES) {
158
+ numActiveApps++;
159
+
160
+ restartingAppIds.add(app_env.pm_id);
161
+ pm2.restart(app_env.pm_id, (err, _) => {
162
+ restartingAppIds.delete(app_env.pm_id);
163
+ if (err) { return logIfError(err); }
164
+
165
+ // reset counter stats (restart_time=0)
166
+ pm2.reset(app_env.pm_id, logIfError);
167
+ });
168
+
169
+ } else {
170
+ pm2.stop(app_env.pm_id, logIfError);
171
+ }
172
+ });
173
+
174
+ if (numActiveApps < shared.MAX_ACTIVE_PROCESSES) {
175
+ const missingOnlineApps = shared.MAX_ACTIVE_PROCESSES - numActiveApps;
176
+
177
+ // console.log("Active apps is lower than MAX_ACTIVE_PROCESSES, will SCALE again =>", {
178
+ // missingOnlineApps,
179
+ // numActiveApps,
180
+ // newNumTotalApps: numTotalApps + missingOnlineApps
181
+ // });
182
+
183
+ pm2.scale(apps[0].name, numTotalApps + missingOnlineApps, updateAndSaveIfAllRunning);
184
+ }
185
+ };
186
+
187
+ const numHalfMaxActiveProcesses = Math.ceil(shared.MAX_ACTIVE_PROCESSES / 2);
188
+
189
+ /**
190
+ * Re-use previously stopped apps if available
191
+ */
192
+ if (appsStopped.length >= numHalfMaxActiveProcesses) {
193
+ const initialApps = appsStopped.splice(0, numHalfMaxActiveProcesses);
194
+
195
+ let numSucceeded = 0;
196
+ initialApps.forEach((app_env) => {
197
+ // console.log("pm2.restart => ", app_env.pm_id);
198
+
199
+ restartingAppIds.add(app_env.pm_id);
200
+ pm2.restart(app_env.pm_id, (err) => {
201
+ restartingAppIds.delete(app_env.pm_id);
202
+ if (err) { return replyIfError(err, reply); }
203
+
204
+ // reset counter stats (restart_time=0)
205
+ pm2.reset(app_env.pm_id, logIfError);
206
+
207
+ // TODO: set timeout here to exit if some processes are not restarting
208
+
209
+ numSucceeded++;
210
+ if (numSucceeded === initialApps.length) {
211
+ onFirstAppsStart(initialApps);
212
+ }
213
+ });
214
+ });
215
+
216
+ } else {
217
+ /**
218
+ * Increment to +(MAX/2) processes
219
+ */
220
+ let LAST_NODE_APP_INSTANCE = apps[apps.length - 1].pm2_env.NODE_APP_INSTANCE;
221
+ const initialApps = Array.from({ length: numHalfMaxActiveProcesses }).map((_, i) => {
222
+ const new_app_env = Object.assign({}, apps[0].pm2_env);
223
+ new_app_env.NODE_APP_INSTANCE = ++LAST_NODE_APP_INSTANCE;
224
+ return new_app_env;
225
+ });
226
+
227
+ numTotalApps = apps.length + numHalfMaxActiveProcesses;
228
+
229
+ // Ensure to scale to a number of processes where `numHalfMaxActiveProcesses` can start immediately.
230
+ pm2.scale(apps[0].name, numTotalApps, onFirstAppsStart.bind(undefined, initialApps));
231
+ }
232
+ });
233
+ }
234
+
235
+ function updateAndSave() {
236
+ // console.log("updateAndExit");
237
+ updateAndReloadNginx(() => complete());
238
+ }
239
+
240
+ function updateAndSaveIfAllRunning(err) {
241
+ if (err) { return console.error(err); }
242
+
243
+ updateAndReloadNginx((app_envs) => {
244
+ // console.log("updateAndExitIfAllRunning, app_ids (", app_envs.map(app_env => app_env.NODE_APP_INSTANCE) ,") => ", app_envs.length, "/", shared.MAX_ACTIVE_PROCESSES);
245
+
246
+ //
247
+ // TODO: add timeout to exit here, in case some processes are not starting
248
+ //
249
+ if (app_envs.length === shared.MAX_ACTIVE_PROCESSES) {
250
+ complete();
251
+ }
252
+ });
253
+ }
254
+
255
+ function updateAndReloadNginx(cb) {
256
+ //
257
+ // If you are self-hosting and reading this file, consider using the
258
+ // following in your self-hosted environment:
259
+ //
260
+ // #!/bin/bash
261
+ // # Requires fswatch (`apt install fswatch`)
262
+ // # Reload NGINX when colyseus_servers.conf changes
263
+ // fswatch /etc/nginx/colyseus_servers.conf -m poll_monitor --event=Updated | while read event
264
+ // do
265
+ // service nginx reload
266
+ // done
267
+
268
+ shared.listApps(function(err, apps) {
269
+ if (apps.length === 0) { err = "no apps running."; }
270
+ if (err) { return console.error(err); }
271
+
272
+ const app_envs = apps
273
+ .filter(app => app.pm2_env.status !== cst.STOPPING_STATUS && app.pm2_env.status !== cst.STOPPED_STATUS)
274
+ .map((app) => app.pm2_env);
275
+
276
+ writeNginxConfig(app_envs);
277
+
278
+ cb?.(app_envs);
279
+ });
280
+ }
281
+
282
+ function writeNginxConfig(app_envs) {
283
+ // console.log("writeNginxConfig: ", app_envs.map(app_env => app_env.NODE_APP_INSTANCE));
284
+
285
+ const port = 2567;
286
+ const addresses = [];
287
+
288
+ app_envs.forEach(function(app_env) {
289
+ addresses.push(`unix:${shared.PROCESS_UNIX_SOCK_PATH}${port + app_env.NODE_APP_INSTANCE}.sock`);
290
+ });
291
+
292
+ // write NGINX config
293
+ fs.writeFileSync(shared.NGINX_SERVERS_CONFIG_FILE, addresses.map(address => `server ${address};`).join("\n"), logIfError);
294
+ }
295
+
296
+ function complete() {
297
+ // "pm2 save"
298
+ pm2.dump(logIfError);
299
+ }
300
+
301
+ function logIfError (err) {
302
+ if (err) {
303
+ console.error(err);
304
+ }
305
+ }
306
+
307
+ function replyIfError(err, reply) {
308
+ if (err) {
309
+ console.error(err);
310
+ reply({ success: false, message: err?.message });
311
+ }
312
+ }
package/pm2/shared.js ADDED
@@ -0,0 +1,73 @@
1
+ const pm2 = require('pm2');
2
+ const os = require('os');
3
+
4
+ const NAMESPACE = 'cloud';
5
+ const MAX_ACTIVE_PROCESSES = os.cpus().length;
6
+
7
+ function listApps(callback) {
8
+ pm2.list((err, apps) => {
9
+ if (err) { return callback(err);; }
10
+
11
+ // Filter out @colyseus/tools module (PM2 post-deploy agent)
12
+ apps = apps.filter(app => app.name !== '@colyseus/tools');
13
+
14
+ callback(err, apps);
15
+ });
16
+ }
17
+
18
+ async function getAppConfig(ecosystemFilePath) {
19
+ const module = await import(ecosystemFilePath);
20
+ const config = module.default;
21
+
22
+ /**
23
+ * Tune PM2 app config
24
+ */
25
+ if (config.apps && config.apps.length >= 0) {
26
+ const app = config.apps[0];
27
+
28
+ // app.name = "colyseus-app";
29
+ app.namespace = NAMESPACE;
30
+ app.exec_mode = "fork";
31
+
32
+ app.instances = MAX_ACTIVE_PROCESSES;
33
+
34
+ app.time = true;
35
+ app.wait_ready = true;
36
+ app.watch = false;
37
+
38
+ // default: merge logs into a single file
39
+ if (app.merge_logs === undefined) {
40
+ app.merge_logs = true;
41
+ }
42
+
43
+ // default: wait for 30 minutes before forcibly killing
44
+ // (prevent forcibly killing while rooms are still active)
45
+ if (!app.kill_timeout) {
46
+ app.kill_timeout = 30 * 60 * 1000;
47
+ }
48
+
49
+ // default: retry kill after 1 second
50
+ if (!app.kill_retry_time) {
51
+ app.kill_retry_time = 5000;
52
+ }
53
+ }
54
+
55
+ return config;
56
+ }
57
+
58
+ module.exports = {
59
+ /**
60
+ * Constants
61
+ */
62
+ NGINX_SERVERS_CONFIG_FILE: '/etc/nginx/colyseus_servers.conf',
63
+ PROCESS_UNIX_SOCK_PATH: '/run/colyseus/',
64
+
65
+ MAX_ACTIVE_PROCESSES,
66
+ NAMESPACE,
67
+
68
+ /**
69
+ * Shared methods
70
+ */
71
+ listApps,
72
+ getAppConfig,
73
+ }
package/post-deploy.js CHANGED
@@ -6,27 +6,32 @@ const shared = require('./pm2/shared');
6
6
 
7
7
  const opts = { env: process.env.NODE_ENV || "production", };
8
8
 
9
- const CONFIG_FILE = pm2.cwd + "/" + [
9
+ const CONFIG_FILE = [
10
10
  'ecosystem.config.cjs',
11
11
  'ecosystem.config.js',
12
12
  'pm2.config.cjs',
13
13
  'pm2.config.js',
14
14
  ].find((filename) => fs.existsSync(path.resolve(pm2.cwd, filename)));
15
15
 
16
- let config = undefined;
17
-
16
+ /**
17
+ * TODO: if not provided, auto-detect entry-point & dynamically generate ecosystem config
18
+ */
18
19
  if (!CONFIG_FILE) {
19
20
  throw new Error('missing ecosystem config file. make sure to provide one with a valid "script" entrypoint file path.');
20
21
  }
21
22
 
23
+ const CONFIG_FILE_PATH = `${pm2.cwd}/${CONFIG_FILE}`;
24
+
25
+ let config = undefined;
26
+
22
27
  /**
23
28
  * Try to handle post-deploy via PM2 module first (pm2 install @colyseus/tools)
24
29
  * If not available, fallback to legacy post-deploy script.
25
30
  */
26
- pm2.trigger('@colyseus/tools', 'post-deploy', `${pm2.cwd}:${CONFIG_FILE}`, async function (err, result) {
31
+ pm2.trigger('@colyseus/tools', 'post-deploy', `${pm2.cwd}:${CONFIG_FILE_PATH}`, async function (err, result) {
27
32
  if (err) {
28
33
  console.log("Proceeding with legacy post-deploy script...");
29
- config = await shared.getAppConfig(CONFIG_FILE);
34
+ config = await shared.getAppConfig(CONFIG_FILE_PATH);
30
35
  postDeploy();
31
36
 
32
37
  } else {