1
0
forked from sent/waves

Peformance 4

This commit is contained in:
sent 2025-05-19 19:17:40 -07:00
parent 41b65cbf24
commit 119776dc29

141
index.mjs
View File

@ -1,9 +1,11 @@
import cluster from "cluster"; import cluster from "cluster";
import os from "os"; import os from "os";
import net from "net"; import net from "net";
import fs from "fs";
import { spawnSync } from "child_process";
import path from "path";
import express from "express"; import express from "express";
import { createServer } from "http"; import { createServer } from "http";
import path from "path";
import compression from "compression"; import compression from "compression";
import WebSocket from "ws"; import WebSocket from "ws";
import { baremuxPath } from "@mercuryworkshop/bare-mux/node"; import { baremuxPath } from "@mercuryworkshop/bare-mux/node";
@ -13,60 +15,85 @@ import { uvPath } from "@titaniumnetwork-dev/ultraviolet";
import wisp from "wisp-server-node"; import wisp from "wisp-server-node";
import NodeCache from "node-cache"; import NodeCache from "node-cache";
const cache = new NodeCache({ stdTTL: 345600, checkperiod: 3600 }); const surgeConfigPath = path.resolve("surge.config.json");
const isSurgedRun = process.argv.includes("--surged");
function applySurgeAndRestartIfNeeded() {
if (isSurgedRun) {
try {
const config = JSON.parse(fs.readFileSync(surgeConfigPath, "utf-8"));
process.env.UV_THREADPOOL_SIZE = String(config.uvThreadpoolSize);
} catch {
}
return;
}
console.log('[~] Running Surge...');
const result = spawnSync("node", ["./others/surge.mjs"], { stdio: "inherit" });
if (result.error) {
console.error('[!] Surger failed:', result.error);
process.exit(1);
}
const config = JSON.parse(fs.readFileSync(surgeConfigPath, "utf-8"));
const nodeArgs = config.nodeFlags.concat([path.resolve("index.mjs"), "--surged"]);
const env = { ...process.env, UV_THREADPOOL_SIZE: String(config.uvThreadpoolSize), ALREADY_SURGED: "true" };
console.log(`[~] Relaunching with Node flags: ${config.nodeFlags.join(' ')}`);
const relaunch = spawnSync(process.execPath, nodeArgs, { stdio: 'inherit', env });
process.exit(relaunch.status || 0);
}
applySurgeAndRestartIfNeeded();
if (global.gc) {
setInterval(() => global.gc(), 15000);
}
import './others/scaler.mjs';
import './others/warmup.mjs';
const cache = new NodeCache({ stdTTL: 345600, checkperiod: 3600, useClones: false });
const port = parseInt(process.env.PORT || "3000", 10); const port = parseInt(process.env.PORT || "3000", 10);
cluster.schedulingPolicy = cluster.SCHED_RR; cluster.schedulingPolicy = cluster.SCHED_RR;
function logInfo(message) { function logInfo(message) { console.info(`[~] ${message}`); }
console.info(`[~] ${message}`); function logSuccess(message) { console.info(`[+] ${message}`); }
}
function logSuccess(message) {
console.info(`[+] ${message}`);
}
function logError(error) { function logError(error) {
const msg = error instanceof Error ? error.message : error; const msg = error instanceof Error ? error.message : error;
console.error(`[!] ${msg}`); console.error(`[!] ${msg}`);
} }
process.on("uncaughtException", (err) => logError(`Unhandled Exception: ${err}`)); process.on("uncaughtException", err => logError(`Unhandled Exception: ${err}`));
process.on("unhandledRejection", (reason) => logError(`Unhandled Promise Rejection: ${reason}`)); process.on("unhandledRejection", reason => logError(`Unhandled Rejection: ${reason}`));
if (cluster.isPrimary) { if (cluster.isPrimary) {
const numCPUs = os.cpus().length; const numCPUs = os.cpus().length;
logInfo(`Master started. Forking ${numCPUs} workers...`); logInfo(`Master started. Forking ${numCPUs} workers...`);
for (let i = 0; i < numCPUs; i++) cluster.fork();
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker, code, signal) => { cluster.on("exit", (worker, code, signal) => {
logError(`Worker ${worker.process.pid} terminated (code: ${code}, signal: ${signal}). Restarting...`); logError(`Worker ${worker.process.pid} exited (code=${code}, signal=${signal}). Restarting...`);
cluster.fork(); cluster.fork();
}); });
let currentWorker = 0; let current = 0;
const server = net.createServer({ pauseOnConnect: true }, (connection) => { const server = net.createServer({ pauseOnConnect: true }, conn => {
const workerIds = Object.keys(cluster.workers); const workers = Object.values(cluster.workers);
if (workerIds.length === 0) { if (!workers.length) return conn.destroy();
connection.destroy(); const worker = workers[current++ % workers.length];
return; worker.send("sticky-session:connection", conn);
}
const worker = cluster.workers[workerIds[currentWorker % workerIds.length]];
currentWorker++;
if (worker) worker.send("sticky-session:connection", connection);
}); });
server.on("error", (err) => logError(`Server error: ${err}`)); server.on("error", err => logError(`Server error: ${err}`));
server.listen(port, () => logSuccess(`Server running on port ${port}.`)); server.listen(port, () => logSuccess(`Server listening on port ${port}`));
} else { } else {
process.env.UV_THREADPOOL_SIZE = String(os.cpus().length * 2);
const __dirname = process.cwd(); const __dirname = process.cwd();
const publicPath = path.join(__dirname, "public"); const publicPath = path.join(__dirname, "public");
const app = express(); const app = express();
app.use(compression({ level: 9, threshold: 128, memLevel: 9 })); app.use(compression({ level: 9, threshold: 128, memLevel: 9 }));
app.use((req, res, next) => { app.use((req, res, next) => {
const key = req.originalUrl; const key = req.originalUrl;
if (cache.has(key)) { if (cache.has(key)) {
@ -74,7 +101,7 @@ if (cluster.isPrimary) {
return res.send(cache.get(key)); return res.send(cache.get(key));
} }
res.sendResponse = res.send; res.sendResponse = res.send;
res.send = (body) => { res.send = body => {
cache.set(key, body); cache.set(key, body);
res.setHeader("X-Cache", "MISS"); res.setHeader("X-Cache", "MISS");
res.sendResponse(body); res.sendResponse(body);
@ -90,7 +117,7 @@ if (cluster.isPrimary) {
app.use("/wah/", express.static(uvPath, staticOpts)); app.use("/wah/", express.static(uvPath, staticOpts));
app.use(express.json()); app.use(express.json());
const sendHtml = (file) => (req, res) => res.sendFile(path.join(publicPath, file)); const sendHtml = file => (req, res) => res.sendFile(path.join(publicPath, file));
app.get('/', sendHtml('$.html')); app.get('/', sendHtml('$.html'));
app.get('/g', sendHtml('!.html')); app.get('/g', sendHtml('!.html'));
app.get('/a', sendHtml('!!.html')); app.get('/a', sendHtml('!!.html'));
@ -101,51 +128,41 @@ if (cluster.isPrimary) {
server.keepAliveTimeout = 0; server.keepAliveTimeout = 0;
server.headersTimeout = 0; server.headersTimeout = 0;
const pingWSS = new WebSocket.Server({ noServer: true, maxPayload: 1048576 }); const pingWSS = new WebSocket.Server({ noServer: true, maxPayload: 4 * 1024 * 1024, perMessageDeflate: false });
pingWSS.on("connection", (ws, req) => { pingWSS.on("connection", (ws, req) => {
const remoteAddress = req.socket.remoteAddress || "unknown"; const remote = req.socket.remoteAddress || 'unknown';
let latencies = []; let lat = [];
const interval = setInterval(() => { const pingInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));
const ts = Date.now();
ws.send(JSON.stringify({ type: 'ping', timestamp: ts }));
}
}, 1000); }, 1000);
ws.on('message', (message) => { ws.on('message', msg => {
try { try {
const data = JSON.parse(message); const data = JSON.parse(msg);
if (data.type === 'pong' && data.timestamp) { if (data.type === 'pong' && data.timestamp) {
const latency = Date.now() - data.timestamp; const delta = Date.now() - data.timestamp;
latencies.push(latency); lat.push(delta);
if (latencies.length > 5) latencies.shift(); if (lat.length > 5) lat.shift();
ws.send(JSON.stringify({ type: 'latency', latency })); ws.send(JSON.stringify({ type: 'latency', latency: delta }));
}
} catch (err) {
logError(`Ping handling error: ${err}`);
} }
} catch (e) { logError(`Ping error: ${e}`); }
}); });
ws.on('close', () => { ws.on('close', () => {
clearInterval(interval); clearInterval(pingInterval);
const avg = latencies.length ? (latencies.reduce((a, b) => a + b) / latencies.length).toFixed(2) : 0; const avg = lat.length ? (lat.reduce((a,b)=>a+b)/lat.length).toFixed(2) : 0;
logInfo(`Connection from ${remoteAddress} closed. Avg latency: ${avg}ms.`); logInfo(`WS ${remote} closed. Avg latency ${avg}ms`);
}); });
}); });
server.on('upgrade', (req, socket, head) => { server.on('upgrade', (req, sock, head) => {
if (req.url === '/w/ping') { if (req.url === '/w/ping') pingWSS.handleUpgrade(req, sock, head, ws => pingWSS.emit('connection', ws, req));
pingWSS.handleUpgrade(req, socket, head, (ws) => pingWSS.emit('connection', ws, req)); else if (req.url.startsWith('/w/')) wisp.routeRequest(req, sock, head);
} else if (req.url.startsWith('/w/')) { else sock.end();
wisp.routeRequest(req, socket, head);
} else {
socket.end();
}
}); });
server.on('error', (err) => logError(`Worker server error: ${err}`)); server.on('error', err => logError(`Worker server error: ${err}`));
server.listen(0, () => logSuccess(`Worker ${process.pid} ready`));
server.listen(0, () => logSuccess(`Worker ${process.pid} ready and listening.`));
process.on('message', (msg, conn) => { process.on('message', (msg, conn) => {
if (msg === 'sticky-session:connection' && conn) { if (msg === 'sticky-session:connection' && conn) {