phase 1 rework
This commit is contained in:
1 parent
211bfd174d
commit
20054198f3
38 files changed
+5001
-1019
No files matched your search
@@ -1,146 +1,291 @@
|
||||
// server.js (Improved Version B)
|
||||
require('dotenv').config();
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const bodyParser = require('body-parser');
|
||||
const http = require('http');
|
||||
const WebSocket = require('ws');
|
||||
const { spawn } = require('child_process');
|
||||
"use strict";
|
||||
|
||||
const express = require('express');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const WebSocket = require('ws');
|
||||
const { spawn } = require('node:child_process');
|
||||
const { config } = require('./lib/config');
|
||||
const { closeDb } = require('./lib/mongo');
|
||||
const { createLineSanitizer } = require('./lib/logging');
|
||||
const { resolveManagedProcess, validName } = require('./controllers/pm2Controller');
|
||||
const indexRouter = require('./routes/index');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const MAX_WS_PAYLOAD = 16 * 1024;
|
||||
const MAX_WS_BUFFER = 64 * 1024;
|
||||
|
||||
// View engine
|
||||
app.set('view engine', 'ejs');
|
||||
app.set('views', path.join(__dirname, 'views'));
|
||||
|
||||
// Middleware
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
app.use(bodyParser.urlencoded({ extended: true }));
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// Routes
|
||||
app.use('/', indexRouter);
|
||||
|
||||
// Error handler
|
||||
app.use((err, req, res, next) => {
|
||||
console.error(err);
|
||||
res.status(500).render('error', {
|
||||
message: 'Internal Server Error',
|
||||
detail: err.message
|
||||
});
|
||||
});
|
||||
|
||||
// -----------------------------
|
||||
// HTTP + WebSocket server
|
||||
// -----------------------------
|
||||
const server = http.createServer(app);
|
||||
const wss = new WebSocket.Server({ server });
|
||||
|
||||
// Heartbeat for detecting dead connections
|
||||
function heartbeat() {
|
||||
this.isAlive = true;
|
||||
function handleHttpError(error, req, res, next) {
|
||||
if (res.headersSent) return next(new Error('The response could not be completed.'));
|
||||
const tooLarge = error?.type === 'entity.too.large' || error?.status === 413;
|
||||
const invalid = error?.type === 'entity.parse.failed' || error?.status === 400;
|
||||
const status = tooLarge ? 413 : invalid ? 400 : 500;
|
||||
const message = tooLarge
|
||||
? 'Request too large. The maximum request size is 32 KiB.'
|
||||
: invalid ? 'Invalid request body.' : 'The request could not be completed. Check the server configuration and try again.';
|
||||
if (req.is?.('application/json') || req.path?.startsWith('/pm2/') || req.path === '/status-data') {
|
||||
return res.status(status).json({ ok: false, error: message });
|
||||
}
|
||||
return res.status(status).render('error', { title: 'Request failed', message, details: null });
|
||||
}
|
||||
|
||||
wss.on('connection', ws => {
|
||||
ws.isAlive = true;
|
||||
ws.on('pong', heartbeat);
|
||||
function createApplication({ settings = config, router = indexRouter } = {}) {
|
||||
const app = express();
|
||||
app.set('view engine', 'ejs');
|
||||
app.set('views', path.join(settings.projectRoot, 'views'));
|
||||
app.locals.global = { captcha_blocked: false };
|
||||
app.use(express.static(path.join(settings.projectRoot, 'public')));
|
||||
app.use(express.urlencoded({ extended: false, limit: '32kb', parameterLimit: 100 }));
|
||||
app.use(express.json({ limit: '32kb' }));
|
||||
app.use('/', router);
|
||||
app.use(handleHttpError);
|
||||
return app;
|
||||
}
|
||||
|
||||
let child = null;
|
||||
// Attach one bounded log subscription; dependencies are injectable for offline tests.
|
||||
function attachLogConnection(ws, {
|
||||
resolveWorker = resolveManagedProcess,
|
||||
spawnProcess = spawn,
|
||||
settings = config,
|
||||
} = {}) {
|
||||
let disposed = false;
|
||||
let generation = 0;
|
||||
let current = null;
|
||||
|
||||
ws.send(JSON.stringify({ type: 'connected', message: 'ws ready' }));
|
||||
function stopCurrent() {
|
||||
const previous = current;
|
||||
current = null;
|
||||
if (previous) {
|
||||
previous.active = false;
|
||||
try { previous.child.kill(); } catch { /* already gone */ }
|
||||
}
|
||||
}
|
||||
|
||||
ws.on('message', msg => {
|
||||
let payload;
|
||||
function dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
generation++;
|
||||
stopCurrent();
|
||||
}
|
||||
|
||||
function disconnect(code, reason) {
|
||||
dispose();
|
||||
try { ws.close(code, reason); } catch { try { ws.terminate(); } catch {} }
|
||||
}
|
||||
|
||||
function send(payload) {
|
||||
if (disposed || ws.readyState !== WebSocket.OPEN) return false;
|
||||
const encoded = JSON.stringify(payload);
|
||||
if ((ws.bufferedAmount || 0) + Buffer.byteLength(encoded) > MAX_WS_BUFFER) {
|
||||
disconnect(1013, 'Log stream cannot keep up. Reconnect to continue.');
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
payload = JSON.parse(msg.toString());
|
||||
ws.send(encoded, error => {
|
||||
if (error) disconnect(1011, 'Log connection failed.');
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
ws.send(JSON.stringify({ type: 'error', error: 'Invalid JSON' }));
|
||||
disconnect(1011, 'Log connection failed.');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMessage(data, isBinary) {
|
||||
if (disposed || ws.readyState !== WebSocket.OPEN) return;
|
||||
if (isBinary) {
|
||||
send({ type: 'error', error: 'Log requests must be JSON text.' });
|
||||
return;
|
||||
}
|
||||
const text = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
|
||||
if (Buffer.byteLength(text) > MAX_WS_PAYLOAD) {
|
||||
disconnect(1009, 'Log request is too large.');
|
||||
return;
|
||||
}
|
||||
let payload;
|
||||
try { payload = JSON.parse(text); } catch {
|
||||
send({ type: 'error', error: 'Invalid JSON request.' });
|
||||
return;
|
||||
}
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
||||
send({ type: 'error', error: 'A JSON object is required.' });
|
||||
return;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// START LOGS
|
||||
// -----------------------------
|
||||
if (payload.type === 'logs') {
|
||||
const name = payload.name || null;
|
||||
|
||||
// Clean previous child
|
||||
if (child) {
|
||||
try { child.kill(); } catch {}
|
||||
child = null;
|
||||
}
|
||||
|
||||
// Correct PM2 argument ordering
|
||||
const args = ['logs', '--raw', '--lines', '200'];
|
||||
if (name) args.splice(1, 0, name);
|
||||
|
||||
try {
|
||||
child = spawn('pm2', args);
|
||||
|
||||
child.stdout.on('data', data => {
|
||||
ws.send(JSON.stringify({ type: 'stdout', data: data.toString() }));
|
||||
});
|
||||
|
||||
child.stderr.on('data', data => {
|
||||
ws.send(JSON.stringify({ type: 'stderr', data: data.toString() }));
|
||||
});
|
||||
|
||||
child.on('close', code => {
|
||||
ws.send(JSON.stringify({ type: 'close', code }));
|
||||
child = null;
|
||||
});
|
||||
|
||||
child.on('error', err => {
|
||||
ws.send(JSON.stringify({ type: 'error', error: err.message }));
|
||||
child = null;
|
||||
});
|
||||
|
||||
ws.send(JSON.stringify({ type: 'info', message: `started logs for ${name || 'all'}` }));
|
||||
|
||||
} catch (err) {
|
||||
ws.send(JSON.stringify({ type: 'error', error: err.message }));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// STOP LOGS
|
||||
// -----------------------------
|
||||
if (payload.type === 'stop-logs') {
|
||||
if (child) {
|
||||
try { child.kill(); } catch {}
|
||||
child = null;
|
||||
}
|
||||
ws.send(JSON.stringify({ type: 'info', message: 'logs stopped' }));
|
||||
generation++;
|
||||
stopCurrent();
|
||||
send({ type: 'info', message: 'Log stream stopped.' });
|
||||
return;
|
||||
}
|
||||
if (payload.type !== 'logs') {
|
||||
send({ type: 'error', error: 'Unknown log request.' });
|
||||
return;
|
||||
}
|
||||
if (!validName(payload.name)) {
|
||||
send({ type: 'error', error: 'Select a valid downloader worker.' });
|
||||
return;
|
||||
}
|
||||
|
||||
ws.send(JSON.stringify({ type: 'error', error: 'Unknown type' }));
|
||||
});
|
||||
const requestGeneration = ++generation;
|
||||
stopCurrent();
|
||||
try {
|
||||
const worker = await resolveWorker(payload.name);
|
||||
if (disposed || generation !== requestGeneration || ws.readyState !== WebSocket.OPEN) return;
|
||||
const id = worker?.pm_id;
|
||||
if (!worker || !/^\d+$/.test(String(id)) || !Number.isSafeInteger(Number(id))) {
|
||||
send({ type: 'error', error: 'The selected downloader worker was not found.' });
|
||||
return;
|
||||
}
|
||||
const child = spawnProcess('pm2', ['logs', String(Number(id)), '--raw', '--lines', '200'], {
|
||||
cwd: settings.projectRoot,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const record = { child, active: true };
|
||||
current = record;
|
||||
const active = () => !disposed && record.active && current === record && generation === requestGeneration;
|
||||
const stdout = createLineSanitizer(line => {
|
||||
if (active()) send({ type: 'stdout', data: line });
|
||||
}, { secrets: [settings.mongoUri] });
|
||||
const stderr = createLineSanitizer(line => {
|
||||
if (active()) send({ type: 'stderr', data: line });
|
||||
}, { secrets: [settings.mongoUri] });
|
||||
|
||||
ws.on('close', () => {
|
||||
if (child) {
|
||||
try { child.kill(); } catch {}
|
||||
child = null;
|
||||
child.on('error', () => {
|
||||
if (!active()) return;
|
||||
stopCurrent();
|
||||
send({ type: 'error', error: 'The worker log stream could not be started.' });
|
||||
});
|
||||
for (const stream of [child.stdout, child.stderr]) {
|
||||
stream.on('error', () => {
|
||||
if (!active()) return;
|
||||
stopCurrent();
|
||||
send({ type: 'error', error: 'The worker log stream was interrupted.' });
|
||||
});
|
||||
}
|
||||
child.stdout.on('data', chunk => { if (active()) stdout.write(chunk); });
|
||||
child.stderr.on('data', chunk => { if (active()) stderr.write(chunk); });
|
||||
child.on('close', code => {
|
||||
if (!active()) return;
|
||||
stdout.end();
|
||||
stderr.end();
|
||||
if (!active()) return;
|
||||
current = null;
|
||||
record.active = false;
|
||||
send({ type: 'close', code: Number.isInteger(code) ? code : null });
|
||||
});
|
||||
send({ type: 'info', message: 'Worker log stream started.' });
|
||||
} catch {
|
||||
if (disposed || generation !== requestGeneration) return;
|
||||
stopCurrent();
|
||||
send({ type: 'error', error: 'The worker supervisor is unavailable.' });
|
||||
}
|
||||
}
|
||||
|
||||
ws.isAlive = true;
|
||||
ws.on('pong', () => { ws.isAlive = true; });
|
||||
ws.on('message', (data, isBinary) => {
|
||||
handleMessage(data, isBinary).catch(() => {
|
||||
stopCurrent();
|
||||
send({ type: 'error', error: 'The log request could not be completed.' });
|
||||
});
|
||||
});
|
||||
});
|
||||
ws.on('close', dispose);
|
||||
ws.on('error', dispose);
|
||||
send({ type: 'connected', message: 'Log connection ready.' });
|
||||
return { dispose };
|
||||
}
|
||||
|
||||
// Ping-pong interval every 30s
|
||||
setInterval(() => {
|
||||
wss.clients.forEach(ws => {
|
||||
if (!ws.isAlive) return ws.terminate();
|
||||
|
||||
ws.isAlive = false;
|
||||
ws.ping(); // triggers 'pong'
|
||||
function createServer({
|
||||
settings = config,
|
||||
router = indexRouter,
|
||||
resolveWorker = resolveManagedProcess,
|
||||
spawnProcess = spawn,
|
||||
createHttpServer = http.createServer,
|
||||
WebSocketServer = WebSocket.Server,
|
||||
scheduleInterval = setInterval,
|
||||
cancelInterval = clearInterval,
|
||||
} = {}) {
|
||||
const app = createApplication({ settings, router });
|
||||
const server = createHttpServer(app);
|
||||
const wss = new WebSocketServer({ server, maxPayload: MAX_WS_PAYLOAD });
|
||||
const connections = new Map();
|
||||
let cleaned = false;
|
||||
let closingWebSocketServer = false;
|
||||
wss.on('connection', ws => {
|
||||
const connection = attachLogConnection(ws, { resolveWorker, spawnProcess, settings });
|
||||
connections.set(ws, connection);
|
||||
ws.once('close', () => connections.delete(ws));
|
||||
});
|
||||
}, 30000);
|
||||
|
||||
// Start server
|
||||
server.listen(PORT, () =>
|
||||
console.log(`Proxer-Downloader running on http://localhost:${PORT}`)
|
||||
);
|
||||
const heartbeat = scheduleInterval(() => {
|
||||
for (const ws of wss.clients) {
|
||||
if (!ws.isAlive || ws.readyState !== WebSocket.OPEN) {
|
||||
connections.get(ws)?.dispose();
|
||||
try { ws.terminate(); } catch {}
|
||||
continue;
|
||||
}
|
||||
ws.isAlive = false;
|
||||
try { ws.ping(); } catch {
|
||||
connections.get(ws)?.dispose();
|
||||
try { ws.terminate(); } catch {}
|
||||
}
|
||||
}
|
||||
}, 30_000);
|
||||
heartbeat.unref?.();
|
||||
|
||||
function cleanup() {
|
||||
if (cleaned) return;
|
||||
cleaned = true;
|
||||
cancelInterval(heartbeat);
|
||||
for (const [ws, connection] of connections) {
|
||||
connection.dispose();
|
||||
try { ws.terminate(); } catch {}
|
||||
}
|
||||
connections.clear();
|
||||
}
|
||||
wss.on('close', cleanup);
|
||||
function closeWebSocketServer() {
|
||||
if (closingWebSocketServer) return;
|
||||
closingWebSocketServer = true;
|
||||
wss.close();
|
||||
}
|
||||
server.on('close', () => { cleanup(); closeWebSocketServer(); });
|
||||
|
||||
function close() {
|
||||
cleanup();
|
||||
closeWebSocketServer();
|
||||
return new Promise(resolve => {
|
||||
if (server.listening) server.close(resolve);
|
||||
else resolve();
|
||||
});
|
||||
}
|
||||
return { app, server, wss, close };
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
const runtime = createServer();
|
||||
runtime.server.on('error', () => {
|
||||
console.error('The HTTP server could not start. Check the configured host and port.');
|
||||
runtime.close();
|
||||
process.exitCode = 1;
|
||||
});
|
||||
runtime.server.listen(config.port, config.host, () => {
|
||||
console.log(`Proxer-Downloader listening on ${config.host}:${config.port}`);
|
||||
});
|
||||
let stopping = false;
|
||||
async function shutdown() {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
try {
|
||||
await runtime.close();
|
||||
await closeDb();
|
||||
} catch {
|
||||
console.error('The server could not close every resource cleanly.');
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
process.once('SIGINT', shutdown);
|
||||
process.once('SIGTERM', shutdown);
|
||||
}
|
||||
|
||||
module.exports = { createApplication, createServer, attachLogConnection, handleHttpError, MAX_WS_PAYLOAD, MAX_WS_BUFFER };
|
||||
Reference in new issue
Block a user