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'); const { createWorkerIdentity, toPublicWorkerIdentity } = require('./lib/workerIdentity'); 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']); 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); } 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'); 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 }); 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; } 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; } } } } 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: '', worker: '' } }); 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)), }; const worker = toPublicWorkerIdentity(job.worker); if (worker) common.worker = worker; 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: '', worker: '' } }); 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(), workerIdentity } = {}) { if (shouldStop() || await downloadsPaused(db) || shouldStop()) return null; const worker = toPublicWorkerIdentity(workerIdentity); const job = await db.collection('queue').findOneAndUpdate( { processing: { $ne: true } }, { $set: { processing: true, started_at: now(), ...(worker ? { worker } : {}) }, ...(!worker ? { $unset: { worker: '' } } : {}) }, { 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: '', worker: '' } }); return null; } return job; } async function main() { const workerIdentity = createWorkerIdentity(); 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, workerIdentity }); 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(); } } 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 };