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

+61
View File
@@ -0,0 +1,61 @@
"use strict";
const { getDb } = require("../lib/mongo");
const { config } = require("../lib/config");
const { STATUS_READ_PROJECTION, toPublicJob } = require("../lib/jobValidation");
const { STATES, QUERY_TIMEOUT_MS, stateQuery, publicGlobal } = require("../lib/statusQuery");
const { readActivity } = require("../lib/activity");
const RECENT_LIMIT = 5;
async function readSummary(db) {
const [totals, record] = await Promise.all([
Promise.all(STATES.map(state => {
const { collection, filter } = stateQuery(state);
return db.collection(collection).countDocuments(filter, { maxTimeMS: QUERY_TIMEOUT_MS });
})),
db.collection("settings").findOne({ _id: "global" }, {
projection: { captcha_blocked: 1, pause_reason: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
}),
]);
return { counts: Object.fromEntries(STATES.map((state, index) => [state, totals[index]])), global: publicGlobal(record) };
}
async function readRecent(db, state) {
const { collection, filter, sort } = stateQuery(state);
const records = await db.collection(collection).find(filter, {
projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS,
}).sort(sort).limit(RECENT_LIMIT).toArray();
return records.map(toPublicJob);
}
function createDashboardController(dependencies = {}) {
const connect = dependencies.getDb || getDb;
const settings = dependencies.config || config;
const activityReader = dependencies.readActivity || readActivity;
async function readDashboard() {
const db = await connect();
const [summary, activity, done, failed] = await Promise.all([
readSummary(db), activityReader(db, { settings }), readRecent(db, "done"), readRecent(db, "failed"),
]);
return { ...summary, activity, recent: { done, failed } };
}
async function dashboard(req, res, next) {
res.set("Cache-Control", "no-store");
try {
return res.render("dashboard", { title: "Dashboard", activePage: "dashboard", ...await readDashboard() });
} catch (error) { return next(error); }
}
async function dashboardData(req, res, next) {
res.set("Cache-Control", "no-store");
try { return res.json(await readDashboard()); }
catch (error) { return next(error); }
}
return { dashboard, dashboardData, readDashboard };
}
module.exports = { ...createDashboardController(), createDashboardController, readSummary, RECENT_LIMIT };
+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 };
+149 -43
View File
@@ -1,81 +1,167 @@
"use strict";
const fs = require("node:fs/promises");
const { getDb } = require("../lib/mongo");
const { config } = require("../lib/config");
const {
ValidationError, STATUS_READ_PROJECTION, buildQueueJobs, toPublicJob, validateOutputTarget,
ValidationError, STATUS_READ_PROJECTION, planQueueJobs, toPublicJob, validateOutputTarget,
} = require("../lib/jobValidation");
const {
STATES, QUERY_TIMEOUT_MS, parseStatusQuery, stateQuery, statusFilter, publicGlobal,
} = require("../lib/statusQuery");
const { readActivity } = require("../lib/activity");
const { createSessionTokenService, SessionTokenError } = require("../lib/sessionToken");
function createQueueController(dependencies = {}) {
const connect = dependencies.getDb || getDb;
const settings = dependencies.config || config;
const now = dependencies.now || (() => new Date());
const activityReader = dependencies.readActivity || readActivity;
const sessionTokens = dependencies.sessionTokens || createSessionTokenService({ getDb: connect, settings, now });
function formModel(body = {}, formError = null, tokenStatus = { available: false, state: "unknown" }) {
const input = body && typeof body === "object" && !Array.isArray(body) ? body : {};
const values = {
mode: input.mode === "video" ? "video" : "series",
id: "", url: "", name: "", language: "engsub", season: "1", episode_from: "", episode_to: "",
};
for (const [key, limit] of Object.entries({ id: 16, url: 2048, name: 255, season: 16, episode_from: 16, episode_to: 16 })) {
if (typeof input[key] !== "string") continue;
let value = input[key];
// Never re-render credentials, including a token accidentally pasted into
// another field. The password input is deliberately absent from values.
if (typeof input.token === "string" && input.token) value = value.split(input.token).join("[redacted]");
values[key] = value.slice(0, limit).replace(/[\u0000-\u001f\u007f-\u009f\uD800-\uDFFF]/gu, "");
}
if (["engsub", "engdub", "gersub", "gerdub"].includes(input.language)) values.language = input.language;
return {
title: "New download", activePage: "download", values, formError, tokenStatus,
maxSeriesEpisodes: settings.maxSeriesEpisodes, outputDir: settings.outputDir, details: null,
};
}
async function safeTokenStatus() {
try { return await sessionTokens.readStatus(); }
catch { return { available: false, state: "unavailable" }; }
}
async function home(req, res) {
res.set("Cache-Control", "no-store");
return res.render("index", formModel({ mode: req.query?.mode }, null, await safeTokenStatus()));
}
async function enqueue(req, res) {
res.set("Cache-Control", "no-store");
try {
const jobs = await buildQueueJobs(req.body, settings, now);
const planned = await planQueueJobs(req.body, settings, now);
const access = await sessionTokens.resolveForEnqueue(req.body.token, { url: planned[0].url });
const jobs = planned.map(job => ({ ...job, token: access.cookie }));
const db = await connect();
if (jobs.length === 1 && req.body.mode === "video") {
await db.collection("queue").insertOne(jobs[0]);
const result = await db.collection("queue").insertOne(jobs[0]);
if (result?.acknowledged !== true) throw new Error("The queue insertion was not acknowledged.");
} else {
await db.collection("queue").bulkWrite(jobs.map(document => ({ insertOne: { document } })));
const result = await db.collection("queue").bulkWrite(jobs.map(document => ({ insertOne: { document } })));
if (result?.isOk?.() !== true || result.insertedCount !== jobs.length) throw new Error("The batch insertion was not confirmed.");
}
return res.redirect("/status");
return res.redirect(`/status?state=queued&added=${jobs.length}`);
} catch (error) {
const invalid = error instanceof ValidationError;
return res.status(invalid ? 400 : 500).render("error", {
title: "Enqueue failed",
message: invalid ? error.message : "The download could not be queued. Check the service configuration and try again.",
if (error instanceof SessionTokenError) {
const status = error.code === "storage" ? { available: false, state: "unavailable" } : await safeTokenStatus();
return res.status(error.httpStatus).render("index", formModel(req.body, error.message, status));
}
if (error instanceof ValidationError) return res.status(400).render("index", formModel(req.body, error.message));
return res.status(500).render("error", {
title: "Enqueue failed", activePage: "download",
message: "The queue submission could not be confirmed. Check the queue before retrying to avoid duplicate downloads, and check the service configuration if the problem continues.",
details: null,
});
}
}
async function readStatus() {
async function readSummary(db) {
const [totals, record] = await Promise.all([
Promise.all(STATES.map(state => {
const { collection, filter } = stateQuery(state);
return db.collection(collection).countDocuments(filter, { maxTimeMS: QUERY_TIMEOUT_MS });
})),
db.collection("settings").findOne({ _id: "global" }, {
projection: { captcha_blocked: 1, pause_reason: 1 }, maxTimeMS: QUERY_TIMEOUT_MS,
}),
]);
return { counts: Object.fromEntries(STATES.map((state, index) => [state, totals[index]])), global: publicGlobal(record) };
}
async function readStatus(query) {
const filters = parseStatusQuery(query);
const db = await connect();
const queries = [
["queue", { processing: { $ne: true } }, { created_at: 1 }],
["queue", { processing: true }, { created_at: 1 }],
["done", {}, { finished_at: -1 }],
["failed", {}, { failed_at: -1 }],
];
const lists = await Promise.all(queries.map(async ([collection, filter, sort]) => {
const records = await db.collection(collection).find(filter, { projection: STATUS_READ_PROJECTION }).sort(sort).toArray();
return records.map(toPublicJob);
}));
const [queued, processing, done, failed] = lists;
// Asynchronous file checks avoid blocking the web process. Pagination follows in Phase 2.
for (const job of [...processing, ...done]) {
try {
const target = await validateOutputTarget(settings.outputDir, job.filename);
const stat = await fs.lstat(target);
job.fileSize = stat.isFile() && !stat.isSymbolicLink() ? stat.size : null;
} catch {
job.fileSize = null;
}
const selected = stateQuery(filters.state);
const filter = statusFilter(filters.state, filters.q);
const [summary, matchingTotal, activity] = await Promise.all([
readSummary(db),
filters.q ? db.collection(selected.collection).countDocuments(filter, { maxTimeMS: QUERY_TIMEOUT_MS }) : null,
activityReader(db, { settings }),
]);
const total = matchingTotal ?? summary.counts[filters.state];
const totalPages = Math.max(1, Math.ceil(total / filters.pageSize));
const page = Math.min(filters.page, totalPages);
const records = await db.collection(selected.collection)
.find(filter, { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS })
.sort(selected.sort).skip((page - 1) * filters.pageSize).limit(filters.pageSize).toArray();
const items = records.map(toPublicJob);
// Only the visible page needs filesystem metadata. A summary request never
// reads queue records, download logs, cookies, or output files.
if (["processing", "done"].includes(filters.state)) {
await Promise.all(items.map(async job => {
try {
const target = await validateOutputTarget(settings.outputDir, job.filename);
const stat = await fs.lstat(target);
job.fileSize = stat.isFile() && !stat.isSymbolicLink() ? stat.size : null;
} catch {
job.fileSize = null;
}
}));
}
const global = await db.collection("settings").findOne({ _id: "global" }, { projection: { captcha_blocked: 1, pause_reason: 1 } });
return {
queued, processing, done, failed,
global: {
captcha_blocked: global?.captcha_blocked === true,
pause_reason: ["authentication", "resolution"].includes(global?.pause_reason) ? global.pause_reason : null,
},
items, ...summary, activity,
pagination: { page, pageSize: filters.pageSize, total, totalPages },
filters: { state: filters.state, q: filters.q },
};
}
function queryError(error, res, json) {
if (!(error instanceof ValidationError)) return false;
if (json) res.status(400).json({ ok: false, error: error.message });
else res.status(400).render("error", { title: "Invalid queue filters", activePage: "queue", message: error.message, details: null });
return true;
}
async function status(req, res, next) {
res.set("Cache-Control", "no-store");
try {
const snapshot = await readStatus();
return res.render("status", { ...snapshot, finished: snapshot.done });
const snapshot = await readStatus(req.query);
const addedText = req.query?.added;
const added = typeof addedText === "string" && /^[1-9]\d{0,4}$/.test(addedText)
&& Number(addedText) <= settings.maxSeriesEpisodes ? Number(addedText) : 0;
return res.render("status", { title: "Queue", activePage: "queue", ...snapshot, added });
} catch (error) {
return next(error);
if (!queryError(error, res, false)) return next(error);
}
}
async function statusData(req, res, next) {
res.set("Cache-Control", "no-store");
try {
res.set("Cache-Control", "no-store");
return res.json(await readStatus());
return res.json(await readStatus(req.query));
} catch (error) {
if (!queryError(error, res, true)) return next(error);
}
}
async function statusSummary(req, res, next) {
res.set("Cache-Control", "no-store");
try {
return res.json(await readSummary(await connect()));
} catch (error) {
return next(error);
}
@@ -83,7 +169,7 @@ function createQueueController(dependencies = {}) {
function clearProcessing(req, res) {
return res.status(409).render("error", {
title: "Active downloads are protected",
title: "Active downloads are protected", activePage: "queue",
message: "Active processing flags cannot be cleared safely while downloads may still be running. Stop the affected worker and verify that its download has ended before performing recovery.",
details: null,
});
@@ -102,7 +188,27 @@ function createQueueController(dependencies = {}) {
}
}
return { enqueue, status, statusData, clearProcessing, clearCaptcha };
async function clearState(req, res, next, legacyState = undefined) {
res.set("Cache-Control", "no-store");
const state = legacyState ?? req.body?.state;
if (typeof state !== "string" || !STATES.includes(state)) {
return res.status(400).render("error", {
title: "Choose a queue state", activePage: "queue",
message: "Select Waiting, Completed, or Failed attempts before clearing records.", details: null,
});
}
if (state === "processing") return clearProcessing(req, res);
try {
const { collection, filter } = stateQuery(state);
const db = await connect();
// Search text and pagination never broaden this to active claims.
const result = await db.collection(collection).deleteMany(filter);
if (result?.acknowledged !== true) throw new Error("The clear operation was not acknowledged.");
return res.redirect(`/status?state=${state}`);
} catch (error) { return next(error); }
}
return { home, enqueue, status, statusData, statusSummary, clearState, clearProcessing, clearCaptcha };
}
module.exports = { ...createQueueController(), createQueueController };