-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
540 lines (475 loc) · 15.9 KB
/
index.ts
File metadata and controls
540 lines (475 loc) · 15.9 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// evolution/packages/shard/src/index.ts
import dotEnv from 'dotenv';
dotEnv.config();
import fs from 'fs';
import os from 'os';
import helmet from 'helmet';
import cors from 'cors';
import http from 'http';
import https from 'https';
import express, { Express } from 'express';
import { Server as SocketIOServer } from 'socket.io';
import { log, logError, isDebug } from '@arken/node/log';
import { catchExceptions } from '@arken/node/process';
import { Service as ShardService } from './shard.service';
import { getTime, decodePayload, ipHashFromSocket } from '@arken/node/util';
import { serialize, deserialize } from '@arken/node/rpc';
import { testMode } from '@arken/evolution-protocol/config';
import { EvolutionMechanic as Mechanic } from '@arken/node/legacy/types';
import type * as Shard from '@arken/evolution-protocol/shard/shard.types';
import { createCallerFactory } from '@arken/evolution-protocol/shard/shard.router';
import osModule from 'os';
import puppeteer, { Browser, Page } from 'puppeteer';
if (isDebug) {
log('Running SHARD in DEBUG mode');
}
function closeServer(server?: http.Server | https.Server) {
return new Promise<void>((resolve) => {
if (!server) return resolve();
server.close(() => resolve());
});
}
function trackAndDestroySockets(server?: http.Server | https.Server) {
const sockets = new Set<any>();
if (!server) return { destroyAll: () => {}, sockets };
server.on('connection', (socket) => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
});
return {
sockets,
destroyAll: () => {
for (const s of sockets) {
try {
s.destroy();
} catch {}
}
sockets.clear();
},
};
}
export class Application {
public server: Express;
public state: {
port: number;
sslPort: number;
spawnPort?: number;
};
public isHttps: boolean;
public http?: http.Server;
public https?: https.Server;
public io?: SocketIOServer;
// NEW: puppeteer handles
private browser?: Browser;
private bridgePage?: Page;
private shuttingDown = false;
private socketTracker?: any;
status: string;
realmStatus: string;
coreStatus: string;
constructor() {
this.server = express();
this.state = {
port: process.env.SHARD_PORT ? parseInt(process.env.SHARD_PORT, 10) : 8080,
sslPort: process.env.SHARD_SSL_PORT ? parseInt(process.env.SHARD_SSL_PORT, 10) : 8443,
};
this.isHttps = process.env.ARKEN_ENV !== 'local';
this.setupMiddleware();
this.setupServer();
this.setupShutdownHooks();
}
private setupMiddleware() {
// @ts-ignore
this.server.set('trust proxy', 1);
// @ts-ignore
this.server.use(helmet());
// @ts-ignore
this.server.use(
cors({
allowedHeaders: [
'Accept',
'Authorization',
'Cache-Control',
'X-Requested-With',
'Content-Type',
'applicationId',
],
})
);
}
private setupServer() {
log('Setting up server', process.env);
if (this.isHttps) {
this.https = https.createServer(
{
key: fs.readFileSync('/etc/letsencrypt/live/hoff.arken.gg/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/hoff.arken.gg/fullchain.pem'),
},
// @ts-ignore
this.server
);
} else {
this.http = http.createServer(this.server);
}
const baseServer = this.isHttps ? this.https : this.http;
this.socketTracker = trackAndDestroySockets(baseServer);
this.io = new SocketIOServer(baseServer, {
pingInterval: 30 * 1000,
pingTimeout: 90 * 1000,
upgradeTimeout: 20 * 1000,
allowUpgrades: true,
cookie: false,
serveClient: false,
allowEIO3: true,
cors: {
origin: '*',
},
});
}
updateStatus(type: string, status: string) {
if (type === 'realm') this.realmStatus = status;
if (type === 'core') this.coreStatus = status;
if (this.realmStatus === 'initialized' && this.coreStatus === 'initialized') this.status = 'initialized';
}
// ---------------------------------------------------------
// SHARD SETUP (unchanged, just moved into a method)
// ---------------------------------------------------------
async setupShard() {
console.log('Evolution.Shard.Application.setupShard');
try {
const service = new ShardService(this);
service.init(); // make sure your Service.init() is called
log('Starting event handler');
this.io.on('connection', async (socket) => {
log('Connection', socket.id);
const hash = ipHashFromSocket(socket);
const spawnPoint = service.clientSpawnPoints[Math.floor(Math.random() * service.clientSpawnPoints.length)];
const client: Shard.Client = {
name: 'Unknown' + Math.floor(Math.random() * 999),
roles: [],
emit: undefined,
ops: [],
ioCallbacks: {},
questDirty: false,
startedRoundAt: null,
lastTouchClientId: null,
lastTouchTime: null,
id: socket.id,
avatar: null,
network: null,
address: null,
device: null,
position: spawnPoint,
upgrades: [],
ui: [],
target: spawnPoint,
clientPosition: spawnPoint,
clientTarget: spawnPoint,
phasedPosition: undefined,
socket,
rotation: null,
xp: 75,
maxHp: 100,
latency: 0,
kills: 0,
killStreak: 0,
deaths: 0,
points: 0,
evolves: 0,
powerups: 0,
rewards: 0,
orbs: 0,
upgradesPending: 2,
upgradeRerolls: 3,
pickups: [],
isSeer: false,
isAdmin: false,
isMod: false,
isBanned: false,
isDisconnected: false,
isDead: true,
isJoining: false,
isSpectating: false,
isStuck: false,
isGod: false,
isRealm: false,
isMaster: false,
isGuest: false,
isInvincible: service.config.isGodParty ? true : false,
isPhased: false,
overrideSpeed: null as any,
overrideCameraSize: null as any,
cameraSize: service.config.cameraSize,
speed: service.config.baseSpeed * service.config.avatarSpeedMultiplier0,
joinedAt: 0,
invincibleUntil: 0,
decayPower: 1,
hash,
lastReportedTime: getTime(),
lastUpdate: 0,
gameMode: service.config.gameMode,
phasedUntil: getTime(),
overrideSpeedUntil: 0,
joinedRoundAt: getTime(),
baseSpeed: 0.8,
character: {
meta: {
[Mechanic.MovementSpeedIncrease]: 0,
[Mechanic.DeathPenaltyAvoid]: 0,
[Mechanic.EnergyDecayIncrease]: 0,
[Mechanic.WinRewardsIncrease]: 0,
[Mechanic.WinRewardsDecrease]: 0,
[Mechanic.IncreaseMovementSpeedOnKill]: 0,
[Mechanic.EvolveMovementBurst]: 0,
[Mechanic.DoublePickupChance]: 0,
[Mechanic.IncreaseHealthOnKill]: 0,
[Mechanic.SpriteFuelIncrease]: 0,
},
},
log: {
kills: [],
deaths: [],
revenge: 0,
resetPosition: 0,
phases: 0,
stuck: 0,
collided: 0,
timeoutDisconnect: 0,
speedProblem: 0,
clientDistanceProblem: 0,
outOfBounds: 0,
ranOutOfHealth: 0,
notReallyTrying: 0,
tooManyKills: 0,
killingThemselves: 0,
sameNetworkDisconnect: 0,
connectedTooSoon: 0,
clientDisconnected: 0,
positionJump: 0,
errors: 0,
pauses: 0,
connects: 0,
path: '',
positions: 0,
spectating: 0,
replay: [],
addressProblem: 0,
recentJoinProblem: 0,
usernameProblem: 0,
maintenanceJoin: 0,
signatureProblem: 0,
signinProblem: 0,
versionProblem: 0,
failedRealmCheck: 0,
},
};
log('Client connected from hash ' + hash);
if (hash && this.status !== 'initialized') {
service.disconnectClient(client, 'app not initialized');
return;
}
if (!testMode && service.config.killSameNetworkClients) {
const sameNetworkClient = service.clients.find((r) => r.hash === client.hash && r.id !== client.id);
if (sameNetworkClient) {
client.log.sameNetworkDisconnect += 1;
service.disconnectClient(client, 'same network');
return;
}
}
service.sockets[client.id] = socket;
service.clientLookup[client.id] = client;
service.clients.push(client);
// @ts-ignore
socket.shardClient = client;
const ctx = { client };
const createCaller = createCallerFactory(service.router);
client.emit = createCaller(ctx);
socket.on('trpc', async (message) => {
await service.handleClientMessage(socket, message);
});
socket.on('trpcResponse', async (message) => {
console.log('[SHARD] trpcResponse message', message);
const pack = typeof message === 'string' ? decodePayload(message) : message;
const { id } = pack;
if (pack.error) {
log(
'Shard client callback - error occurred',
pack,
client.ioCallbacks[id] ? client.ioCallbacks[id].request : ''
);
return;
}
try {
if (client.ioCallbacks[id]) {
clearTimeout(client.ioCallbacks[id].timeout);
client.ioCallbacks[id].resolve({ result: { data: deserialize(pack.result) } });
delete client.ioCallbacks[id];
}
} catch (e) {
log('Shard client trpcResponse error', id, e);
}
});
socket.on('disconnect', () => {
log('Shard client disconnected');
client.log.clientDisconnected += 1;
service.disconnectClient(client, 'client disconnected');
if (client.isRealm) {
service.emitAll.onBroadcast.mutate([`Shard client: bridge disconnected`, 0]);
}
});
});
} catch (e) {
log('init shard failed', e);
}
}
// ---------------------------------------------------------
// PUPPETEER: launch embedded Chrome/Unity page
// ---------------------------------------------------------
private async launchEmbeddedChrome() {
const url = 'http://arken.gg.local:8021/games/evolution'; // your bridge page
log('Launching embedded Chrome page at', url);
this.browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
});
this.bridgePage = await this.browser.newPage();
await this.bridgePage.goto(url, { waitUntil: 'domcontentloaded' });
}
private async closeEmbeddedChrome() {
try {
if (this.bridgePage) {
await this.bridgePage.close().catch(() => undefined);
this.bridgePage = undefined;
}
if (this.browser) {
await this.browser.close().catch(() => undefined);
this.browser = undefined;
}
console.log('Closed embedded Chrome.');
} catch (err) {
logError('Error closing embedded Chrome:', err);
}
}
// ---------------------------------------------------------
// Shutdown handling so Chrome dies with the server
// ---------------------------------------------------------
private setupShutdownHooks() {
const shutdown = async (signal: string) => {
if (this.shuttingDown) return;
this.shuttingDown = true;
log(`Received ${signal}, shutting down shard...`);
// Hard stop if shutdown hangs
const forceTimer = setTimeout(() => {
logError('Forced shutdown after timeout');
// destroy any open sockets to break keep-alives
try {
this.socketTracker?.destroyAll();
} catch {}
process.exit(1);
}, 10_000);
// If the only thing keeping node alive is the timer, let it exit naturally
// (still fine because we call process.exit at end)
// @ts-ignore
forceTimer.unref?.();
try {
// Stop taking new socket.io connections + disconnect clients
if (this.io) {
// Prevent new connections ASAP
this.io.close();
}
} catch (err) {
logError('Error closing socket.io', err);
}
try {
await this.closeEmbeddedChrome();
} catch (err) {
logError('Error during Chrome shutdown', err);
}
try {
// Close the HTTP(S) server and wait for it to actually close
if (this.isHttps) {
await closeServer(this.https);
} else {
await closeServer(this.http);
}
} catch (err) {
logError('Error closing HTTP(S) server', err);
}
clearTimeout(forceTimer);
process.exit(0);
};
process.on('SIGINT', () => void shutdown('SIGINT'));
process.on('SIGTERM', () => void shutdown('SIGTERM'));
// Optional: handle nodemon/ts-node-dev restarts
process.on('SIGUSR2', () => void shutdown('SIGUSR2'));
process.on('uncaughtException', (err) => {
logError('Uncaught exception:', err);
void shutdown('uncaughtException');
});
process.on('unhandledRejection', (reason) => {
logError('Unhandled rejection:', reason);
void shutdown('unhandledRejection');
});
}
// ---------------------------------------------------------
// Monitor (your existing code, unchanged)
// ---------------------------------------------------------
async setupMonitor() {
let logs: boolean[] = [];
const isLinux = osModule.platform() === 'linux';
setInterval(function () {
if (!isLinux) return;
const available = Number(/MemAvailable:[ ]+(\d+)/.exec(fs.readFileSync('/proc/meminfo', 'utf8'))![1]) / 1024;
if (available < 500) {
if (logs.length >= 5) {
const free = osModule.freemem() / 1024 / 1024;
const total = osModule.totalmem() / 1024 / 1024;
logError('SHARD: Free mem', free);
logError('SHARD: Available mem', available);
logError('SHARD: Total mem', total);
process.exit();
}
} else {
logs = [];
}
}, 60 * 1000);
setInterval(function () {
if (!isLinux) return;
const available = Number(/MemAvailable:[ ]+(\d+)/.exec(fs.readFileSync('/proc/meminfo', 'utf8'))![1]) / 1024;
if (available < 500) {
log('SHARD Memory flagged', available);
logs.push(true);
}
}, 10 * 1000);
}
// ---------------------------------------------------------
// Start entrypoint
// ---------------------------------------------------------
public async start() {
log('Starting server...', this.isHttps ? 'HTTPS' : 'HTTP');
catchExceptions();
try {
if (this.isHttps && this.https) {
this.https.listen(this.state.sslPort, async () => {
log(`Server ready and listening on *:${this.state.sslPort} (https)`);
this.state.spawnPort = this.state.sslPort;
this.setupMonitor();
await this.setupShard();
// await this.launchEmbeddedChrome();
});
} else if (this.http) {
this.http.listen(this.state.port, async () => {
log(`Server ready and listening on *:${this.state.port} (http)`);
this.state.spawnPort = this.state.port;
this.setupMonitor();
await this.setupShard();
// await this.launchEmbeddedChrome();
});
}
} catch (error) {
logError('Error starting server:', error);
}
}
}
const app = new Application();
app.start();