phase 2 rework

This commit is contained in:
admin_rb committed 2026-10-23 18:19:44 +02:00
1 parent 20054198f3
commit b397ea9256
44 files changed
+5528 -1377

No files matched your search

+74 -6
View File
@@ -1,6 +1,10 @@
const { spawn } = require('node:child_process');
const path = require('node:path');
const { config } = require('../lib/config');
const { getDb } = require('../lib/mongo');
const WORKER_SEQUENCE_ID = 'worker-name-sequence';
const QUERY_TIMEOUT_MS = 5000;
function runPm2Command(args) {
return new Promise((resolve, reject) => {
@@ -47,6 +51,8 @@ function normalizeProcess(process) {
const env = process.pm2_env || {};
const cpu = process.monit?.cpu;
const memory = process.monit?.memory;
const startedAt = typeof env.pm_uptime === 'number' && Number.isFinite(env.pm_uptime) && env.pm_uptime > 0
? new Date(env.pm_uptime) : null;
return {
name: String(process.name || env.name || '—'),
pid: process.pid || '—',
@@ -55,6 +61,7 @@ function normalizeProcess(process) {
cpu: typeof cpu === 'number' ? `${cpu.toFixed(1)}%` : '—',
memoryMB: typeof memory === 'number' ? `${Math.round(memory / 1024 / 1024)} MB` : '—',
uptime: humanUptime(env.pm_uptime),
startedAtISO: startedAt && Number.isFinite(startedAt.getTime()) ? startedAt.toISOString() : null,
execPath: env.pm_exec_path || '—',
};
}
@@ -63,7 +70,7 @@ function validName(name) {
return typeof name === 'string' && /^[A-Za-z0-9][\w-]{0,63}$/.test(name) && name.toLowerCase() !== 'all';
}
function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
function createPm2Controller({ run = runPm2Command, settings = config, getDb: connect = getDb } = {}) {
function managed(process) {
const executable = process.pm2_env?.pm_exec_path;
return typeof executable === 'string' && path.resolve(executable) === settings.workerScript;
@@ -87,15 +94,77 @@ function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
return { ...normalizeProcess(matches[0]), pm_id: String(id) };
}
async function listManagedProcesses() {
return (await processes()).filter(managed).map(normalizeProcess);
}
function createArguments(name) {
return ['start', settings.workerScript, '--name', name, '--cwd', settings.projectRoot,
'--interpreter', process.execPath, '--kill-timeout', '10000'];
}
async function reserveWorkerName(existing) {
let highest = 0;
for (const worker of existing) {
const match = /^proxer-worker-(\d+)$/.exec(worker.name || worker.pm2_env?.name || '');
if (!match) continue;
const number = Number(match[1]);
if (!Number.isSafeInteger(number) || number >= Number.MAX_SAFE_INTEGER) return null;
highest = Math.max(highest, number);
}
const collection = (await connect()).collection('settings');
const seed = { $max: { value: highest } };
let seeded;
try {
seeded = await collection.updateOne({ _id: WORKER_SEQUENCE_ID }, seed, { upsert: true, maxTimeMS: QUERY_TIMEOUT_MS });
} catch (error) {
// Two first requests can race to create the sequence. The _id index
// selects one winner; the other request can safely seed that same row.
if (error?.code !== 11000) throw error;
seeded = await collection.updateOne({ _id: WORKER_SEQUENCE_ID }, seed, { maxTimeMS: QUERY_TIMEOUT_MS });
}
if (seeded?.acknowledged !== true) throw new Error('Worker number could not be reserved.');
const reserved = await collection.findOneAndUpdate({
_id: WORKER_SEQUENCE_ID, value: { $gte: 0, $lt: Number.MAX_SAFE_INTEGER },
}, { $inc: { value: 1 } }, {
returnDocument: 'after', includeResultMetadata: false, projection: { value: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
});
if (!reserved || !Number.isSafeInteger(reserved.value) || reserved.value < 1) return null;
return `proxer-worker-${reserved.value}`;
}
async function quickAdd(req, res) {
if (req.body && (typeof req.body !== 'object' || Array.isArray(req.body) || Object.keys(req.body).length)) {
return res.status(400).json({ ok: false, error: 'Quick add chooses the worker name and executable automatically.' });
}
let name;
try {
// Inspect every process, including unrelated services, before reserving
// a persistent number. Deleting a worker never reuses its number.
name = await reserveWorkerName(await processes());
if (!name) return res.status(409).json({ ok: false, error: 'A numbered worker name could not be reserved. Use a custom worker name or check the saved worker counter.' });
} catch {
return res.status(503).json({ ok: false, error: 'Quick add requires the worker supervisor and database to be available. Try again after checking the service.' });
}
try {
const { code } = await run(createArguments(name));
return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code, name,
message: code === 0 ? `${name} was created and started.` : `Could not start ${name}. Check the worker list and supervisor before trying again.` });
} catch {
return res.status(503).json({ ok: false, name,
error: `Could not confirm whether ${name} started. Refresh the worker list before trying again.` });
}
}
async function getManage(req, res, next) {
try {
res.render('pm2', { title: 'Proxer Workers', processes: (await processes()).filter(managed).map(normalizeProcess) });
res.render('pm2', { title: 'Proxer Workers', processes: await listManagedProcesses() });
} catch (error) { next(error); }
}
async function listJson(req, res) {
try {
res.json({ ok: true, processes: (await processes()).filter(managed).map(normalizeProcess) });
res.json({ ok: true, processes: await listManagedProcesses() });
} catch {
res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' });
}
@@ -119,8 +188,7 @@ function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
if ((await processes()).some((process) => (process.name || process.pm2_env?.name) === name)) {
return res.status(409).json({ ok: false, error: 'This process name is already in use.' });
}
args = ['start', settings.workerScript, '--name', name, '--cwd', settings.projectRoot,
'--interpreter', process.execPath, '--kill-timeout', '10000'];
args = createArguments(name);
} else {
const worker = await resolveManagedProcess(name);
if (!worker) return res.status(404).json({ ok: false, error: 'The selected downloader worker was not found.' });
@@ -134,7 +202,7 @@ function createPm2Controller({ run = runPm2Command, settings = config } = {}) {
}
}
return { getManage, listJson, postCommand, resolveManagedProcess };
return { getManage, listJson, postCommand, quickAdd, resolveManagedProcess, listManagedProcesses };
}
module.exports = { ...createPm2Controller(), createPm2Controller, normalizeProcess, validName };