phase 1 rework

This commit is contained in:
admin_rb committed 2026-10-23 16:38:55 +02:00
1 parent 211bfd174d
commit 20054198f3
38 files changed
+5001 -1019

No files matched your search

+283 -139
View File
@@ -1,153 +1,297 @@
// proxer-queue-worker.js
const { exec } = require("child_process");
const { spawn } = require("child_process");
const { MongoClient } = require("mongodb");
const path = require("path");
require("dotenv").config();
const { spawn } = require('node:child_process');
const fs = require('node:fs/promises');
const { StringDecoder } = require('node:string_decoder');
const { config } = require('./lib/config');
const { getDb, closeDb } = require('./lib/mongo');
const { ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget, cookieToken } = require('./lib/jobValidation');
const { LOG_LIMIT, sanitizeLog, createLineSanitizer } = require('./lib/logging');
// ========================
// CONFIG
// ========================
const MONGO_URI = process.env.MONGO_URI;
const DB_NAME = process.env.MONGO_DB || "downloads";
const OUTPUT_DIR = process.env.OUTPUT_DIR || "/mnt/media/WIP";
const RESULT_PREFIX = 'PROXER_RESULT ';
const ERROR_CATEGORIES = new Set(['validation', 'authentication', 'resolution', 'network', 'source', 'storage', 'configuration', 'unknown']);
const ATTENTION_CATEGORIES = new Set(['authentication', 'resolution']);
const client = new MongoClient(MONGO_URI);
let queueCol, doneCol, failedCol;
// ========================
// HELPER
// ========================
async function isBlocked() {
const settings = await queueCol.db
.collection("settings")
.findOne({ _id: "global" });
return settings?.captcha_blocked === true;
function jobSecrets(job) {
const token = typeof job.token === 'string' ? job.token : '';
const separator = token.indexOf('=');
return [token, separator >= 0 ? token.slice(separator + 1) : ''].filter(Boolean);
}
// ========================
// RUN A JOB
// ========================
async function runJob(job) {
try {
const cmd = [
process.env.VENV_PYTHON,
path.join(__dirname, "scripts/proxer-dl-video.py"),
"-u",
job.url,
"-f",
job.filename,
"-t",
job.token,
"-o",
OUTPUT_DIR,
];
function collectChild(proc, secrets, onChild = () => {}) {
return new Promise((resolve) => {
let output = '';
let resultCount = 0;
let result = null;
let line = '';
let oversizedLine = false;
let settled = false;
let outputTruncated = false;
let spawned = Number.isInteger(proc.pid) && proc.pid > 0;
let childError = false;
const decoder = new StringDecoder('utf8');
const proc = spawn(cmd[0], cmd.slice(1));
function append(chunk) {
const combined = output + chunk;
outputTruncated ||= combined.length > LOG_LIMIT;
output = combined.slice(-LOG_LIMIT);
}
// Redact complete lines before retaining a bounded tail. Cutting raw text
// first could retain an unrecognisable suffix of a credential or signed URL.
const stdoutLog = createLineSanitizer(append, { secrets });
const stderrLog = createLineSanitizer(append, { secrets });
let output = "";
proc.stdout.on("data", (d) => (output += d.toString()));
proc.stderr.on("data", (d) => (output += d.toString()));
const exitCode = await new Promise((resolve) => proc.on("close", resolve));
// ========== CAPTCHA / ERROR DETECTION ==========
const suspicious =
output.toLowerCase().includes("captcha") ||
output.toLowerCase().includes("403") ||
output.toLowerCase().includes("blocked") ||
output.toLowerCase().includes("token") ||
output.toLowerCase().includes("forbidden") ||
// proxer_utils.py - get_embed_url()
output.toLowerCase().includes("failed to fetch episode page") ||
output.toLowerCase().includes("embed code not found in page content") ||
// proxer_utils.py - get_mp4_url()
output.toLowerCase().includes("failed to fetch embed page") ||
output.toLowerCase().includes("mp4 url not found in embed page") ||
// proxer_utils.py - download_mp4()
output.toLowerCase().includes("failed to start download");
if (suspicious) {
console.log("⛔ CAPTCHA or fatal error detected, notifying system");
console.log(output);
await failedCol.insertOne({
filename: job.filename,
failed_at: new Date(),
output_log: output,
});
// Unset the processing flag so the job isn't stuck
await queueCol.updateOne(
{ _id: job._id },
{ $unset: { processing: "" } }
);
return true; // signals worker to halt globally
function parseLine() {
if (!oversizedLine && line.startsWith(RESULT_PREFIX)) {
resultCount += 1;
try {
const candidate = JSON.parse(line.slice(RESULT_PREFIX.length));
if (candidate && candidate.version === 1 && ['completed', 'failed'].includes(candidate.status)) {
result = candidate;
} else result = null;
} catch { result = null; }
}
line = '';
oversizedLine = false;
}
// Success
await doneCol.insertOne({
filename: job.filename,
finished_at: new Date(),
output_log: output,
});
await queueCol.deleteOne({ _id: job._id });
return false;
} catch (err) {
console.error("Worker crash:", err);
return true;
}
}
// ========================
// MAIN LOOP
// ========================
async function main() {
console.log("Worker started. Watching queue...");
try {
await client.connect();
const db = client.db(DB_NAME);
queueCol = db.collection("queue");
doneCol = db.collection("done");
failedCol = db.collection("failed");
while (true) {
if (await isBlocked()) {
console.log("⛔ CAPTCHA BLOCK — Worker paused");
await new Promise((r) => setTimeout(r, 5000));
continue;
}
const job = await queueCol.findOneAndUpdate(
{ processing: { $ne: true } }, // prevents grabbing others
{ $set: { processing: true } },
{ sort: { created_at: 1 }, returnDocument: "after" }
);
if (job && job.token) {
const failed = await runJob(job);
if (failed === true) {
await queueCol.db
.collection("settings")
.updateOne(
{ _id: "global" },
{ $set: { captcha_blocked: true } },
{ upsert: true }
);
function consume(text) {
for (const char of text) {
if (char === '\n' || char === '\r') parseLine();
else if (!oversizedLine) {
line += char;
if (line.length > 8192) {
if (line.startsWith(RESULT_PREFIX)) { resultCount += 1; result = null; }
line = '';
oversizedLine = true;
}
}
} else {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
} catch (err) {
console.error("Worker error:", err);
function finish(exitCode, signal, spawnError = false) {
if (settled) return;
settled = true;
consume(decoder.end());
parseLine();
stdoutLog.end();
stderrLog.end();
onChild(null);
resolve({ exitCode, signal, spawnError, result: resultCount === 1 ? result : null,
output: (outputTruncated ? '[earlier log output omitted]\n' : '') + output });
}
proc.stdout.on('data', (data) => {
const text = decoder.write(data);
stdoutLog.write(data);
consume(text);
});
proc.stderr.on('data', (data) => stderrLog.write(data));
proc.once('spawn', () => { spawned = true; });
proc.on('error', () => {
childError = true;
// A failed kill can emit error while the child is still alive. Only an
// actual spawn failure has no process whose close event must be awaited.
if (!spawned && !(Number.isInteger(proc.pid) && proc.pid > 0)) finish(null, null, true);
});
proc.on('close', (code, signal) => finish(code, signal, childError));
// A failed spawn can close stdin before the credential is sent.
if (proc.stdin) proc.stdin.on('error', () => {});
onChild(proc);
});
}
async function executeJob(job, {
settings = config, spawnFn = spawn, onChild,
shouldStop = () => false, canStart = async () => true,
} = {}) {
let source, outputFile;
const secrets = jobSecrets(job);
try {
source = normalizeWatchUrl(job.url);
normalizeFilename(job.filename);
if (typeof job.token !== 'string' || job.token.indexOf('=') < 1) throw new Error('Invalid cookie.');
const separator = job.token.indexOf('=');
cookieToken(job.token.slice(separator + 1), job.token.slice(0, separator + 1));
} catch {
return { ok: false, errorCategory: 'validation', exitCode: null,
output: 'The queued source, credentials, filename, or output directory is invalid.' };
}
try {
outputFile = await validateOutputTarget(settings.outputDir, job.filename);
} catch (error) {
return { ok: false, errorCategory: error instanceof ValidationError ? 'validation' : 'storage',
infrastructureFailure: !(error instanceof ValidationError), exitCode: null,
output: 'The output destination is unavailable or is not a safe regular-file target.' };
}
if (shouldStop()) return { ok: false, errorCategory: 'interrupted', exitCode: null, output: 'Worker stopped before starting this job.' };
// Another worker can pause the pool while output validation is awaiting I/O.
// A failed pause read propagates: do not start or release an uncertain claim.
if (!await canStart()) return { ok: false, errorCategory: 'paused', exitCode: null,
output: 'Downloads were paused before this transfer started.' };
if (shouldStop()) return { ok: false, errorCategory: 'interrupted', exitCode: null, output: 'Worker stopped before starting this job.' };
let completed;
try {
const proc = spawnFn(settings.pythonPath, [
'-B', settings.videoScript, '-u', source.url, `--filename=${job.filename}`,
'--token-stdin', `--output=${settings.outputDir}`,
], {
cwd: settings.projectRoot,
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONUNBUFFERED: '1' },
stdio: ['pipe', 'pipe', 'pipe'],
});
const completion = collectChild(proc, secrets, onChild);
proc.stdin.end(job.token + '\n');
completed = await completion;
} catch {
return { ok: false, errorCategory: 'spawn', infrastructureFailure: true, exitCode: null,
output: 'The Python download process could not be started. Check VENV_PYTHON.' };
}
const { exitCode, signal, result, output, spawnError } = completed;
if (spawnError) return { ok: false, exitCode, errorCategory: 'spawn', infrastructureFailure: true,
output: 'The Python download process could not be started. Check VENV_PYTHON.' };
if (exitCode !== 0 || signal || !result || result.status !== 'completed') {
if (shouldStop()) return { ok: false, exitCode, errorCategory: 'interrupted', output: 'Worker stopped; the transfer ended and can be restarted.' };
const errorCategory = result && result.status === 'failed' && ERROR_CATEGORIES.has(result.errorCategory)
? result.errorCategory : 'unknown';
return { ok: false, exitCode, errorCategory, infrastructureFailure: ['configuration', 'storage'].includes(errorCategory),
output: output || 'The download ended without a successful result.' };
}
try {
// Recheck after child exit: do not accept a symlink, missing or empty artifact.
const verifiedFile = await validateOutputTarget(settings.outputDir, job.filename);
const stat = await fs.lstat(verifiedFile);
if (verifiedFile !== outputFile || !stat.isFile() || stat.size <= 0) throw new Error('Invalid output.');
} catch {
return { ok: false, exitCode, errorCategory: 'storage', infrastructureFailure: true,
output: sanitizeLog(output + '\nThe expected nonempty output file was not produced.', secrets) };
}
return { ok: true, exitCode, output };
}
async function processClaimedJob(job, { db, execute = executeJob, now = () => new Date() } = {}) {
const result = await execute(job);
if (['interrupted', 'paused'].includes(result.errorCategory) || result.infrastructureFailure) {
// The runner has either not spawned a child or observed its termination.
// Preserve the complete request for a later worker start; never consume the
// queue because an interpreter, dependency or media mount is unavailable.
await db.collection('queue').updateOne({ _id: job._id, processing: true },
{ $unset: { processing: '', started_at: '' } });
if (result.infrastructureFailure) throw new Error('Worker infrastructure is unavailable. The job remains queued.');
return result;
}
const common = {
job_id: job._id,
filename: job.filename,
url: job.url,
created_at: job.created_at,
output_log: sanitizeLog(result.output, jobSecrets(job)),
};
if (result.ok) {
// History must be durable before removing the queue record. Full atomic job
// state and recovery are a later migration; leave a claim held on DB errors.
await db.collection('done').insertOne({ ...common, finished_at: now() });
await db.collection('queue').deleteOne({ _id: job._id, processing: true });
return result;
}
const needsAttention = ATTENTION_CATEGORIES.has(result.errorCategory);
if (needsAttention) {
// Stop further admissions before any history write can delay or fail. A
// missing source marker can be a challenge without an HTTP error status.
const pause = await db.collection('settings').updateOne({ _id: 'global' },
{ $set: { captcha_blocked: true, pause_reason: result.errorCategory } }, { upsert: true });
if (pause?.acknowledged !== true) throw new Error('The download pause could not be confirmed. The claim remains held.');
}
const failedAttempt = await db.collection('failed').insertOne({ ...common, failed_at: now(),
error_category: result.errorCategory, exit_code: result.exitCode });
if (needsAttention) {
if (failedAttempt?.acknowledged !== true) throw new Error('The failed attempt could not be confirmed. The claim remains held.');
// Preserve the original request and credential for a deliberate retry. The
// attempt stays visible in history, while the job remains queued and paused.
const release = await db.collection('queue').updateOne({ _id: job._id, processing: true },
{ $unset: { processing: '', started_at: '' } });
if (release?.acknowledged !== true) throw new Error('The claim release could not be confirmed. Check the paused queue before resuming.');
} else {
// Ordinary failures become history rather than looping or pausing all jobs.
// Automatic retries arrive with the explicit attempt model in Phase 4.
await db.collection('queue').deleteOne({ _id: job._id, processing: true });
}
return result;
}
async function downloadsPaused(db) {
const global = await db.collection('settings').findOne({ _id: 'global' },
{ projection: { captcha_blocked: 1 } });
return global?.captcha_blocked === true;
}
async function claimNextJob(db, { shouldStop = () => false, now = () => new Date() } = {}) {
if (shouldStop() || await downloadsPaused(db) || shouldStop()) return null;
const job = await db.collection('queue').findOneAndUpdate(
{ processing: { $ne: true } },
{ $set: { processing: true, started_at: now() } },
{ sort: { created_at: 1 }, returnDocument: 'after' },
);
if (!job) return null;
if (await downloadsPaused(db) || shouldStop()) {
// A concurrent worker paused after our initial read. No child has started.
await db.collection('queue').updateOne({ _id: job._id, processing: true },
{ $unset: { processing: '', started_at: '' } });
return null;
}
return job;
}
async function main() {
const db = await getDb();
let stopping = false;
let child = null;
function stop() {
stopping = true;
if (child) child.kill('SIGTERM');
}
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log('Worker started. Watching queue.');
try {
while (!stopping) {
const job = await claimNextJob(db, { shouldStop: () => stopping });
if (!job) { if (!stopping) await delay(1000); continue; }
const result = await processClaimedJob(job, { db,
execute: (request) => executeJob(request, {
shouldStop: () => stopping,
canStart: async () => !await downloadsPaused(db),
onChild: (proc) => {
child = proc;
if (stopping && child) child.kill('SIGTERM');
},
}),
});
if (ATTENTION_CATEGORIES.has(result.errorCategory)) {
console.warn(result.errorCategory === 'resolution'
? 'Downloads paused: the video link could not be resolved. Check the source page before resuming.'
: 'Downloads paused: the source rejected access. Complete verification before resuming.');
}
}
} finally {
process.removeListener('SIGINT', stop);
process.removeListener('SIGTERM', stop);
await closeDb();
}
}
main();
if (require.main === module) {
main().catch(() => {
console.error('Worker stopped after a database or configuration error. Check the deployment and reconcile any held claims before restarting.');
process.exitCode = 1;
});
}
module.exports = { RESULT_PREFIX, collectChild, executeJob, processClaimedJob, claimNextJob, main };