const { spawn } = require('node:child_process'); const path = require('node:path'); const { config } = require('../lib/config'); function runPm2Command(args) { return new Promise((resolve, reject) => { const child = spawn('pm2', args, { cwd: config.projectRoot, stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; let settled = false; function finish(error, code) { if (settled) return; settled = true; clearTimeout(timer); if (error) reject(error); else resolve({ code, stdout, stderr }); } const timer = setTimeout(() => { child.kill(); finish(new Error('PM2 did not respond in time.')); }, 10000); for (const [stream, field] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']]) { stream.on('data', (data) => { if (field === 'stdout') stdout += data.toString(); else stderr += data.toString(); if (stdout.length + stderr.length > 1024 * 1024) { child.kill(); finish(new Error('PM2 response exceeded the supported size.')); } }); } child.on('error', () => finish(new Error('PM2 is unavailable for this account.'))); child.on('close', (code) => finish(null, code)); }); } function humanUptime(timestamp) { if (!timestamp || timestamp <= 0) return '—'; const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)); const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); const minutes = Math.floor((seconds % 3600) / 60); return [days && `${days}d`, hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' ') || `${seconds % 60}s`; } function normalizeProcess(process) { const env = process.pm2_env || {}; const cpu = process.monit?.cpu; const memory = process.monit?.memory; return { name: String(process.name || env.name || '—'), pid: process.pid || '—', pm_id: String(process.pm_id ?? env.pm_id ?? '—'), status: String(env.status || process.status || 'unknown'), cpu: typeof cpu === 'number' ? `${cpu.toFixed(1)}%` : '—', memoryMB: typeof memory === 'number' ? `${Math.round(memory / 1024 / 1024)} MB` : '—', uptime: humanUptime(env.pm_uptime), execPath: env.pm_exec_path || '—', }; } 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 managed(process) { const executable = process.pm2_env?.pm_exec_path; return typeof executable === 'string' && path.resolve(executable) === settings.workerScript; } async function processes() { const response = await run(['jlist']); if (response.code !== 0) throw new Error('PM2 process list is unavailable.'); let parsed; try { parsed = JSON.parse(response.stdout); } catch { throw new Error('PM2 returned an invalid process list.'); } if (!Array.isArray(parsed)) throw new Error('PM2 returned an invalid process list.'); return parsed; } async function resolveManagedProcess(name) { if (!validName(name)) return null; const matches = (await processes()).filter((process) => managed(process) && (process.name || process.pm2_env?.name) === name); if (matches.length !== 1) return null; const id = matches[0].pm_id ?? matches[0].pm2_env?.pm_id; if (!Number.isInteger(id) || id < 0) return null; return { ...normalizeProcess(matches[0]), pm_id: String(id) }; } async function getManage(req, res, next) { try { res.render('pm2', { title: 'Proxer Workers', processes: (await processes()).filter(managed).map(normalizeProcess) }); } catch (error) { next(error); } } async function listJson(req, res) { try { res.json({ ok: true, processes: (await processes()).filter(managed).map(normalizeProcess) }); } catch { res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' }); } } async function postCommand(req, res) { const { cmd, name, scriptPath } = req.body || {}; if (!['start', 'stop', 'restart', 'delete', 'save', 'create'].includes(cmd)) { return res.status(400).json({ ok: false, error: 'Invalid command.' }); } if (cmd === 'save') { return res.status(409).json({ ok: false, error: 'Saving the full PM2 process list is a host-level operation. Run pm2 save as the download user during deployment.' }); } if (!validName(name)) return res.status(400).json({ ok: false, error: 'Invalid worker name.' }); try { let args; if (cmd === 'create') { if (scriptPath !== undefined && scriptPath !== settings.workerScript) { return res.status(400).json({ ok: false, error: 'The worker executable is configured by the server.' }); } 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']; } else { const worker = await resolveManagedProcess(name); if (!worker) return res.status(404).json({ ok: false, error: 'The selected downloader worker was not found.' }); args = [cmd, worker.pm_id]; } const { code } = await run(args); return res.status(code === 0 ? 200 : 502).json({ ok: code === 0, code, message: code === 0 ? 'Worker command completed.' : 'Worker command failed. Check the supervisor on the server.' }); } catch { return res.status(503).json({ ok: false, error: 'The worker supervisor is unavailable.' }); } } return { getManage, listJson, postCommand, resolveManagedProcess }; } module.exports = { ...createPm2Controller(), createPm2Controller, normalizeProcess, validName };