const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const { executeJob, processClaimedJob, claimNextJob, RESULT_PREFIX } = require('../queue_worker'); const repository = path.resolve(__dirname, '..'); const cookie = 'fixture_cookie=fixture-value=='; async function offlineCli(t, mode, { filename = 'Fixture Episode' } = {}) { const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-cli-integration-')); const outputDir = path.join(directory, 'output'); const fakeLibrary = path.join(directory, 'lib'); await fs.mkdir(outputDir); await fs.mkdir(fakeLibrary); await fs.copyFile(path.join(repository, 'scripts/proxer-dl-video.py'), path.join(directory, 'proxer-dl-video.py')); await fs.copyFile(path.join(repository, 'scripts/request_validation.py'), path.join(directory, 'request_validation.py')); await fs.writeFile(path.join(fakeLibrary, '__init__.py'), '# Offline fixture package only.\n'); const stub = mode === 'missing-dependency' ? 'raise ImportError("Synthetic missing dependency; fixture-value==")\n' : `import json import os from pathlib import Path import sys CALLS = [] ROOT = Path(__file__).resolve().parent.parent class NetworkError(Exception): pass class NotFoundError(Exception): pass def record(name): CALLS.append(name) (ROOT / "calls.json").write_text(json.dumps(CALLS), encoding="utf-8") def get_embed_url(url, auth_cookie): assert CALLS == [] assert url == "https://proxer.me/watch/42/1/engsub" assert auth_cookie == ("fixture_cookie", "fixture-value==") assert "--token-stdin" in sys.argv assert not any("fixture-value" in argument for argument in sys.argv) assert sys.dont_write_bytecode is True assert os.environ["PYTHONDONTWRITEBYTECODE"] == "1" record("embed") if ${mode === 'embed-resolution' ? 'True' : 'False'}: raise NotFoundError("Synthetic missing embed fixture-value==") return "https://fixture.invalid/embed" def get_mp4_url(embed_url): assert CALLS == ["embed"] assert embed_url == "https://fixture.invalid/embed" record("media") if ${mode === 'media-resolution' ? 'True' : 'False'}: raise NotFoundError("Synthetic missing media fixture-value==") return "https://fixture.invalid/video.mp4?signature=synthetic-secret" def download_mp4(mp4_url, save_path, label=""): assert CALLS == ["embed", "media"] assert mp4_url == "https://fixture.invalid/video.mp4?signature=synthetic-secret" assert label == ${JSON.stringify('Downloading ' + filename)} assert Path(save_path).parent == ROOT / "output" record("download") if ${mode === 'network-error' ? 'True' : 'False'}: raise NetworkError("Synthetic request failure fixture-value== " + mp4_url) Path(save_path).write_bytes(b"synthetic-MP4-payload") `; await fs.writeFile(path.join(fakeLibrary, 'proxer_utils.py'), stub); let child = null; t.after(async () => { if (child) child.kill('SIGTERM'); await fs.rm(directory, { recursive: true, force: true }); }); const settings = { projectRoot: directory, videoScript: path.join(directory, 'proxer-dl-video.py'), outputDir, pythonPath: process.env.TEST_PYTHON || 'python3', }; const job = { _id: 'integration-fixture', filename, url: 'https://www.proxer.me:443/watch/42/1/engsub/#player', token: cookie, }; const result = await executeJob(job, { settings, onChild: process => { child = process; } }); return { directory, outputDir, result, job }; } function resultRecord(output) { const records = output.split(/\r?\n/).filter(line => line.startsWith(RESULT_PREFIX)); assert.equal(records.length, 1, 'exactly one machine-readable result must survive the subprocess protocol'); return JSON.parse(records[0].slice(RESULT_PREFIX.length)); } async function assertNoBytecode(directory) { const entries = await fs.readdir(directory, { withFileTypes: true }); for (const entry of entries) { assert.notEqual(entry.name, '__pycache__'); assert.ok(!entry.name.endsWith('.pyc')); if (entry.isDirectory()) await assertNoBytecode(path.join(directory, entry.name)); } } test('real Node-to-Python subprocess preserves stdin credentials, stream call order and successful completion', { timeout: 10000 }, async t => { const { directory, outputDir, result } = await offlineCli(t, 'success'); assert.equal(result.ok, true, result.output); assert.equal(result.exitCode, 0); assert.deepEqual(resultRecord(result.output), { version: 1, status: 'completed' }); assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), ['embed', 'media', 'download']); assert.equal(await fs.readFile(path.join(outputDir, 'Fixture Episode.mp4'), 'utf8'), 'synthetic-MP4-payload'); assert.doesNotMatch(result.output, /fixture-value|synthetic-secret|fixture\.invalid/); await assertNoBytecode(directory); }); test('real Python stream failure exits nonzero and reaches Node with a sanitized network result', { timeout: 10000 }, async t => { const { directory, outputDir, result } = await offlineCli(t, 'network-error'); assert.equal(result.ok, false); assert.equal(result.exitCode, 1); assert.equal(result.errorCategory, 'network'); assert.equal(result.infrastructureFailure, false); const record = resultRecord(result.output); assert.equal(record.status, 'failed'); assert.equal(record.errorCategory, 'network'); assert.match(record.message, /source could not be reached or the transfer was interrupted/); assert.doesNotMatch(result.output, /fixture-value|synthetic-secret|Synthetic request failure|Traceback|fixture\.invalid/); assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), ['embed', 'media', 'download']); assert.deepEqual(await fs.readdir(outputDir), []); await assertNoBytecode(directory); }); test('real Python dependency failure becomes an infrastructure result without a transfer', { timeout: 10000 }, async t => { const { directory, outputDir, result } = await offlineCli(t, 'missing-dependency'); assert.equal(result.ok, false); assert.equal(result.exitCode, 1); assert.equal(result.errorCategory, 'configuration'); assert.equal(result.infrastructureFailure, true); const record = resultRecord(result.output); assert.equal(record.status, 'failed'); assert.match(record.message, /dependencies could not be loaded/); assert.doesNotMatch(result.output, /fixture-value|Synthetic missing dependency|Traceback/); assert.deepEqual(await fs.readdir(outputDir), []); await assert.rejects(fs.access(path.join(directory, 'calls.json'))); await assertNoBytecode(directory); }); test('real subprocess treats a leading-dash filename as a value rather than a CLI option', { timeout: 10000 }, async t => { const filename = '-Fixture Episode'; const { directory, outputDir, result } = await offlineCli(t, 'success', { filename }); assert.equal(result.ok, true, result.output); assert.equal(result.exitCode, 0); assert.equal(resultRecord(result.output).status, 'completed'); assert.equal(await fs.readFile(path.join(outputDir, `${filename}.mp4`), 'utf8'), 'synthetic-MP4-payload'); await assertNoBytecode(directory); }); test('real resolver failures pause the queue, preserve both episodes, and do not claim the next one', { timeout: 10000 }, async t => { for (const mode of ['embed-resolution', 'media-resolution']) { const { directory, outputDir, result, job } = await offlineCli(t, mode); assert.equal(result.ok, false); assert.equal(result.exitCode, 1); assert.equal(result.errorCategory, 'resolution'); assert.equal(resultRecord(result.output).errorCategory, 'resolution'); assert.doesNotMatch(result.output, /fixture-value|Synthetic missing|Traceback/); assert.deepEqual(await fs.readdir(outputDir), []); assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), mode === 'embed-resolution' ? ['embed'] : ['embed', 'media']); const queue = [{ ...job, processing: true, started_at: new Date() }, { ...job, _id: 'next-episode', filename: 'Fixture Episode 2', url: 'https://proxer.me/watch/42/2/engsub' }]; const original = queue.map(entry => ({ ...entry })); const global = { captcha_blocked: false }; const history = []; let claims = 0; const db = { collection(name) { if (name === 'settings') return { updateOne: async (filter, update) => { Object.assign(global, update.$set); return { acknowledged: true }; }, findOne: async () => ({ ...global }), }; if (name === 'failed') return { insertOne: async record => { assert.equal(global.captcha_blocked, true, 'pause must precede history'); history.push(record); return { acknowledged: true }; } }; assert.equal(name, 'queue'); return { updateOne: async (filter, update) => { const entry = queue.find(candidate => candidate._id === filter._id && candidate.processing === true); assert.ok(entry); for (const field of Object.keys(update.$unset)) delete entry[field]; return { acknowledged: true }; }, deleteOne: async () => { assert.fail('a resolution pause must not delete an episode'); }, findOneAndUpdate: async () => { claims += 1; return queue[1]; }, }; } }; await processClaimedJob(queue[0], { db, execute: async () => result }); assert.deepEqual(global, { captcha_blocked: true, pause_reason: 'resolution' }); assert.equal(queue.length, 2); assert.equal(queue[0].token, cookie); assert.equal(queue[0].url, original[0].url); assert.equal(queue[0].filename, original[0].filename); assert.equal(queue[0].processing, undefined); assert.equal(queue[0].started_at, undefined); assert.deepEqual(queue[1], original[1]); assert.equal(history.length, 1); assert.equal(history[0].error_category, 'resolution'); assert.equal(history[0].token, undefined); assert.equal(await claimNextJob(db), null); assert.equal(claims, 0); await assertNoBytecode(directory); } });