624 lines
29 KiB
JavaScript
624 lines
29 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { EventEmitter } = require('node:events');
|
|
const { PassThrough } = require('node:stream');
|
|
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 { LOG_LIMIT } = require('../lib/logging');
|
|
const { createWorkerIdentity } = require('../lib/workerIdentity');
|
|
|
|
const now = new Date('2026-01-01T12:00:00.000Z');
|
|
const successfulResult = `${RESULT_PREFIX}${JSON.stringify({ version: 1, status: 'completed' })}\n`;
|
|
const makeJob = (changes = {}) => ({
|
|
_id: 'fixture-job', filename: 'Fixture Episode', url: 'https://proxer.me/watch/42/1/engsub',
|
|
token: 'fixture_cookie=fixture-secret==', created_at: now, processing: true, ...changes,
|
|
});
|
|
const workerIdentity = createWorkerIdentity({
|
|
env: { name: 'proxer-worker-7' }, pid: 12345, host: 'download-host', now: () => now,
|
|
uuid: () => '7b3c9e3a-8b0b-41c6-988c-8e9e01dbbf4a',
|
|
});
|
|
|
|
async function temporarySettings(t) {
|
|
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-worker-'));
|
|
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
|
return {
|
|
outputDir, pythonPath: '/fixture/python', videoScript: '/fixture/proxer-dl-video.py',
|
|
projectRoot: '/fixture/project',
|
|
};
|
|
}
|
|
|
|
function fakeSpawner({ run, synchronousError } = {}) {
|
|
const calls = [];
|
|
const backgroundErrors = [];
|
|
function spawnFn(executable, args, options) {
|
|
calls.push({ executable, args, options });
|
|
if (synchronousError) throw synchronousError;
|
|
const child = new EventEmitter();
|
|
child.stdin = new PassThrough();
|
|
child.stdout = new PassThrough();
|
|
child.stderr = new PassThrough();
|
|
child.input = '';
|
|
child.stdin.on('data', chunk => { child.input += chunk.toString('utf8'); });
|
|
calls.at(-1).child = child;
|
|
setImmediate(async () => {
|
|
try {
|
|
await run(child);
|
|
} catch (error) {
|
|
backgroundErrors.push(error);
|
|
child.emit('error', error);
|
|
}
|
|
});
|
|
return child;
|
|
}
|
|
return { spawnFn, calls, backgroundErrors };
|
|
}
|
|
|
|
async function executeFixture(t, {
|
|
job = makeJob(), stdout = successfulResult, stderr = '', exitCode = 0, signal = null,
|
|
output = 'synthetic video bytes', beforeClose, synchronousError,
|
|
} = {}) {
|
|
const settings = await temporarySettings(t);
|
|
const destination = path.join(settings.outputDir, `${job.filename}.mp4`);
|
|
const callbacks = [];
|
|
const spawner = fakeSpawner({ synchronousError, run: async child => {
|
|
if (output !== null) await fs.writeFile(destination, output);
|
|
for (const chunk of Array.isArray(stdout) ? stdout : [stdout]) child.stdout.write(chunk);
|
|
if (stderr) child.stderr.write(stderr);
|
|
if (beforeClose) await beforeClose({ child, settings, destination });
|
|
child.emit('close', exitCode, signal);
|
|
} });
|
|
const result = await executeJob(job, {
|
|
settings, spawnFn: spawner.spawnFn, onChild: child => callbacks.push(child),
|
|
});
|
|
assert.deepEqual(spawner.backgroundErrors, [], 'fake child setup must not fail');
|
|
return { result, settings, destination, callbacks, ...spawner };
|
|
}
|
|
|
|
test('successful execution requires exit zero, one completed result, and a nonempty file', async t => {
|
|
const run = await executeFixture(t);
|
|
assert.equal(run.result.ok, true);
|
|
assert.equal(run.result.exitCode, 0);
|
|
assert.equal(run.calls.length, 1);
|
|
assert.deepEqual(run.callbacks, [run.calls[0].child, null]);
|
|
assert.equal(await fs.readFile(run.destination, 'utf8'), 'synthetic video bytes');
|
|
});
|
|
|
|
test('worker sends credentials through stdin, enables bytecode protection, and uses configured paths', async t => {
|
|
const job = makeJob({ url: 'https://www.proxer.me:443/watch/42/1/engsub/#player' });
|
|
const run = await executeFixture(t, { job });
|
|
const invocation = run.calls[0];
|
|
assert.equal(invocation.executable, run.settings.pythonPath);
|
|
assert.deepEqual(invocation.args, [
|
|
'-B', run.settings.videoScript, '-u', 'https://proxer.me/watch/42/1/engsub',
|
|
`--filename=${job.filename}`, '--token-stdin', `--output=${run.settings.outputDir}`,
|
|
]);
|
|
assert.ok(!invocation.args.join(' ').includes(job.token));
|
|
assert.ok(!invocation.args.join(' ').includes('fixture-secret'));
|
|
assert.equal(invocation.child.input, job.token + '\n');
|
|
assert.equal(invocation.options.cwd, run.settings.projectRoot);
|
|
assert.equal(invocation.options.env.PYTHONDONTWRITEBYTECODE, '1');
|
|
assert.equal(invocation.options.env.PYTHONUNBUFFERED, '1');
|
|
assert.deepEqual(invocation.options.stdio, ['pipe', 'pipe', 'pipe']);
|
|
});
|
|
|
|
test('a nonzero exit cannot become success even with a completed result and output file', async t => {
|
|
const { result } = await executeFixture(t, { exitCode: 1 });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.exitCode, 1);
|
|
assert.equal(result.errorCategory, 'unknown');
|
|
});
|
|
|
|
test('missing, failed, duplicate, malformed and unsupported results cannot become success', async t => {
|
|
const cases = [
|
|
['missing', 'ordinary progress output\n'],
|
|
['failed', `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"network"}\n`],
|
|
['duplicate', successfulResult + successfulResult],
|
|
['malformed', `${RESULT_PREFIX}{not json}\n`],
|
|
['unsupported version', `${RESULT_PREFIX}{"version":2,"status":"completed"}\n`],
|
|
['unsupported state', `${RESULT_PREFIX}{"version":1,"status":"unknown"}\n`],
|
|
['malformed duplicate', successfulResult + `${RESULT_PREFIX}{not json}\n`],
|
|
];
|
|
for (const [label, stdout] of cases) {
|
|
const { result } = await executeFixture(t, { stdout });
|
|
assert.equal(result.ok, false, label);
|
|
}
|
|
});
|
|
|
|
test('oversized result records invalidate a preceding completed result', async t => {
|
|
const stdout = successfulResult + RESULT_PREFIX + JSON.stringify({
|
|
version: 1, status: 'failed', message: 'x'.repeat(9000),
|
|
}) + '\n';
|
|
const { result } = await executeFixture(t, { stdout });
|
|
assert.equal(result.ok, false);
|
|
});
|
|
|
|
test('a completed result on stderr is only a log and does not count as successful execution', async t => {
|
|
const { result } = await executeFixture(t, { stdout: '', stderr: successfulResult });
|
|
assert.equal(result.ok, false);
|
|
});
|
|
|
|
test('structured failure category is used without treating arbitrary log keywords as authentication', async t => {
|
|
const failed = `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"network"}\n`;
|
|
const { result } = await executeFixture(t, {
|
|
stdout: 'Filename contains token 403 blocked captcha\n' + failed, exitCode: 1,
|
|
});
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'network');
|
|
const authentication = await executeFixture(t, {
|
|
stdout: `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"authentication"}\n`, exitCode: 1,
|
|
});
|
|
assert.equal(authentication.result.errorCategory, 'authentication');
|
|
});
|
|
|
|
test('an unresolved-link result retains its resolution category', async t => {
|
|
const { result } = await executeFixture(t, {
|
|
stdout: `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"resolution"}\n`,
|
|
exitCode: 1, output: null,
|
|
});
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'resolution');
|
|
assert.equal(result.infrastructureFailure, false);
|
|
});
|
|
|
|
test('missing, empty and symlink output files are rejected after otherwise successful child exit', async t => {
|
|
for (const output of [null, '']) {
|
|
const { result } = await executeFixture(t, { output });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'storage');
|
|
assert.equal(result.infrastructureFailure, true);
|
|
}
|
|
const symlink = await executeFixture(t, { output: null, beforeClose: async ({ settings, destination }) => {
|
|
const target = path.join(settings.outputDir, 'another-file.mp4');
|
|
await fs.writeFile(target, 'synthetic bytes');
|
|
await fs.symlink(target, destination);
|
|
} });
|
|
assert.equal(symlink.result.ok, false);
|
|
assert.equal(symlink.result.errorCategory, 'storage');
|
|
assert.equal(symlink.result.infrastructureFailure, true);
|
|
});
|
|
|
|
test('a synchronous spawn exception is reported as a start failure', async t => {
|
|
const { result } = await executeFixture(t, { synchronousError: new Error('fixture spawn failure') });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'spawn');
|
|
assert.equal(result.infrastructureFailure, true);
|
|
assert.equal(result.exitCode, null);
|
|
});
|
|
|
|
test('an asynchronous child error settles once and is reported as a start failure', async t => {
|
|
const settings = await temporarySettings(t);
|
|
const callbacks = [];
|
|
const spawner = fakeSpawner({ run: async child => {
|
|
child.emit('error', Object.assign(new Error('fixture missing executable'), { code: 'ENOENT' }));
|
|
child.emit('close', 0, null);
|
|
} });
|
|
const result = await executeJob(makeJob(), {
|
|
settings, spawnFn: spawner.spawnFn, onChild: child => callbacks.push(child),
|
|
});
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'spawn');
|
|
assert.equal(result.infrastructureFailure, true);
|
|
assert.deepEqual(callbacks, [spawner.calls[0].child, null]);
|
|
});
|
|
|
|
test('an error from a live child cannot complete execution or release its claim before close', async t => {
|
|
const settings = await temporarySettings(t);
|
|
const { db, operations } = recordingDatabase();
|
|
const callbacks = [];
|
|
let signalError, allowClose;
|
|
const errorObserved = new Promise(resolve => { signalError = resolve; });
|
|
const closeAllowed = new Promise(resolve => { allowClose = resolve; });
|
|
const spawner = fakeSpawner({ run: async child => {
|
|
child.pid = 12345;
|
|
child.emit('spawn');
|
|
child.emit('error', Object.assign(new Error('fixture kill denied'), { code: 'EPERM' }));
|
|
signalError();
|
|
await closeAllowed;
|
|
child.emit('close', null, 'SIGTERM');
|
|
} });
|
|
let settled = false;
|
|
const outcome = processClaimedJob(makeJob(), { db,
|
|
execute: job => executeJob(job, { settings, spawnFn: spawner.spawnFn, onChild: child => callbacks.push(child) }),
|
|
}).then(result => { settled = true; return { result }; }, error => { settled = true; return { error }; });
|
|
await errorObserved;
|
|
await new Promise(resolve => setImmediate(resolve));
|
|
try {
|
|
assert.equal(settled, false);
|
|
assert.deepEqual(operations, []);
|
|
assert.deepEqual(callbacks, [spawner.calls[0].child]);
|
|
} finally {
|
|
allowClose();
|
|
}
|
|
const completed = await outcome;
|
|
assert.match(completed.error.message, /infrastructure is unavailable.*remains queued/);
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['queue.updateOne']);
|
|
assert.deepEqual(callbacks, [spawner.calls[0].child, null]);
|
|
});
|
|
|
|
test('signal termination cannot become success', async t => {
|
|
const { result } = await executeFixture(t, { exitCode: null, signal: 'SIGTERM' });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.exitCode, null);
|
|
});
|
|
|
|
test('a stop requested during asynchronous output validation prevents spawning', async t => {
|
|
const settings = await temporarySettings(t);
|
|
let stopping = false;
|
|
let spawns = 0;
|
|
const execution = executeJob(makeJob(), {
|
|
settings, shouldStop: () => stopping,
|
|
spawnFn: () => { spawns += 1; throw new Error('must not spawn after stop'); },
|
|
});
|
|
// executeJob has reached its asynchronous path validation before the stop arrives.
|
|
stopping = true;
|
|
const result = await execution;
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'interrupted');
|
|
assert.equal(spawns, 0);
|
|
});
|
|
|
|
test('the final pause gate releases a never-started claim without history or deletion', async t => {
|
|
const settings = await temporarySettings(t);
|
|
const { db, operations } = recordingDatabase();
|
|
let spawns = 0;
|
|
const result = await processClaimedJob(makeJob(), { db,
|
|
execute: job => executeJob(job, {
|
|
settings, canStart: async () => false,
|
|
spawnFn: () => { spawns += 1; throw new Error('must not start while paused'); },
|
|
}),
|
|
});
|
|
assert.equal(result.errorCategory, 'paused');
|
|
assert.equal(spawns, 0);
|
|
assert.deepEqual(operations, [{ collection: 'queue', method: 'updateOne',
|
|
args: [{ _id: 'fixture-job', processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
|
}]);
|
|
});
|
|
|
|
test('a failed final pause read holds the claim and starts no subprocess', async t => {
|
|
const settings = await temporarySettings(t);
|
|
const { db, operations } = recordingDatabase();
|
|
let spawns = 0;
|
|
await assert.rejects(processClaimedJob(makeJob(), { db,
|
|
execute: job => executeJob(job, {
|
|
settings, canStart: async () => { throw new Error('synthetic pause read failure'); },
|
|
spawnFn: () => { spawns += 1; throw new Error('must not start without pause state'); },
|
|
}),
|
|
}), /synthetic pause read failure/);
|
|
assert.equal(spawns, 0);
|
|
assert.deepEqual(operations, []);
|
|
});
|
|
|
|
test('a terminated transfer during worker shutdown is interrupted rather than a failed download', async t => {
|
|
const settings = await temporarySettings(t);
|
|
let stopping = false;
|
|
const spawner = fakeSpawner({ run: async child => {
|
|
stopping = true;
|
|
child.emit('close', null, 'SIGTERM');
|
|
} });
|
|
const result = await executeJob(makeJob(), {
|
|
settings, spawnFn: spawner.spawnFn, shouldStop: () => stopping,
|
|
});
|
|
assert.equal(spawner.calls.length, 1);
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'interrupted');
|
|
assert.equal(result.infrastructureFailure, undefined);
|
|
});
|
|
|
|
test('a missing output directory is an infrastructure failure and does not spawn', async t => {
|
|
const settings = await temporarySettings(t);
|
|
settings.outputDir = path.join(settings.outputDir, 'missing-mount');
|
|
let spawns = 0;
|
|
const result = await executeJob(makeJob(), {
|
|
settings, spawnFn: () => { spawns += 1; throw new Error('must not spawn without storage'); },
|
|
});
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'storage');
|
|
assert.equal(result.infrastructureFailure, true);
|
|
assert.equal(spawns, 0);
|
|
});
|
|
|
|
test('configuration and storage failure markers identify unavailable worker infrastructure', async t => {
|
|
for (const errorCategory of ['configuration', 'storage']) {
|
|
const { result } = await executeFixture(t, {
|
|
exitCode: 1,
|
|
stdout: `${RESULT_PREFIX}${JSON.stringify({ version: 1, status: 'failed', errorCategory })}\n`,
|
|
output: null,
|
|
});
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, errorCategory);
|
|
assert.equal(result.infrastructureFailure, true);
|
|
}
|
|
});
|
|
|
|
test('split output chunks preserve the result and redact complete secrets before bounding the log tail', async t => {
|
|
const job = makeJob();
|
|
const resultBytes = Buffer.from(successfulResult);
|
|
const stdout = [
|
|
('x'.repeat(1024) + '\n').repeat(48),
|
|
'credential fixture_', 'cookie=fixture-', 'secret==\n',
|
|
'https://media.example/file.mp4?sign', 'ature=hidden-signature\n',
|
|
resultBytes.subarray(0, 7), resultBytes.subarray(7, 18), resultBytes.subarray(18),
|
|
];
|
|
const { result } = await executeFixture(t, { job, stdout });
|
|
assert.equal(result.ok, true);
|
|
assert.doesNotMatch(result.output, /fixture-secret|fixture_cookie|hidden-signature/);
|
|
assert.ok(result.output.length <= LOG_LIMIT + 100);
|
|
assert.match(result.output, /earlier log output omitted/);
|
|
});
|
|
|
|
test('oversized raw tails cannot expose partial credentials after later URL redactions shrink logs', async t => {
|
|
const job = makeJob({ token: 'fixture_cookie=private-prefix-' + 'Q'.repeat(4000) + '-KEEP_PRIVATE' });
|
|
// Previously the raw 32 KiB tail began inside this cookie. Redacting the later
|
|
// long URLs then exposed the unmatched cookie suffix in the final short log.
|
|
const payload = 'x'.repeat(9000) + job.token + '\n'
|
|
+ ('https://media.example/' + 'u'.repeat(6000) + '?signature=fixture\n').repeat(5);
|
|
for (const channel of ['stdout', 'stderr']) {
|
|
const options = channel === 'stdout'
|
|
? { stdout: [payload.slice(0, LOG_LIMIT), payload.slice(LOG_LIMIT), successfulResult] }
|
|
: { stdout: successfulResult, stderr: payload };
|
|
const { result } = await executeFixture(t, { job, ...options });
|
|
assert.equal(result.ok, true, channel);
|
|
assert.doesNotMatch(result.output, /KEEP_PRIVATE|Q{32}|fixture_cookie|signature=fixture/, channel);
|
|
assert.match(result.output, /oversized log line omitted/, channel);
|
|
assert.ok(result.output.length <= LOG_LIMIT + 100, channel);
|
|
}
|
|
});
|
|
|
|
test('invalid queued input and unsafe existing targets are rejected before spawning a child', async t => {
|
|
const settings = await temporarySettings(t);
|
|
let spawns = 0;
|
|
const spawnFn = () => { spawns += 1; throw new Error('must not spawn'); };
|
|
for (const change of [
|
|
{ url: 'https://example.test/video' }, { filename: '../escape' },
|
|
{ token: 'missing-separator' }, { token: 'session=' }, { token: 'session=bad;cookie=other' },
|
|
]) {
|
|
const result = await executeJob(makeJob(change), { settings, spawnFn });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'validation');
|
|
}
|
|
await fs.symlink(path.join(settings.outputDir, 'missing-target'), path.join(settings.outputDir, 'Fixture Episode.mp4'));
|
|
const linked = await executeJob(makeJob(), { settings, spawnFn });
|
|
assert.equal(linked.errorCategory, 'validation');
|
|
assert.equal(spawns, 0);
|
|
});
|
|
|
|
function recordingDatabase(failureAt) {
|
|
const operations = [];
|
|
const db = { collection(name) {
|
|
return Object.fromEntries(['insertOne', 'deleteOne', 'updateOne'].map(method => [method, async (...args) => {
|
|
operations.push({ collection: name, method, args });
|
|
if (`${name}.${method}` === failureAt) throw new Error('synthetic persistence failure');
|
|
return { acknowledged: true, deletedCount: 1, modifiedCount: 1 };
|
|
}]));
|
|
} };
|
|
return { db, operations };
|
|
}
|
|
|
|
test('successful claimed jobs persist history before deleting only their held queue record', async () => {
|
|
const { db, operations } = recordingDatabase();
|
|
const job = makeJob();
|
|
let suppliedJob;
|
|
const result = await processClaimedJob(job, { db, now: () => now, execute: async candidate => {
|
|
suppliedJob = candidate;
|
|
return { ok: true, exitCode: 0, output: 'Completed; credential fixture-secret==' };
|
|
} });
|
|
assert.equal(suppliedJob, job);
|
|
assert.equal(result.ok, true);
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['done.insertOne', 'queue.deleteOne']);
|
|
const history = operations[0].args[0];
|
|
assert.equal(history.job_id, job._id);
|
|
assert.equal(history.finished_at, now);
|
|
assert.equal(history.token, undefined);
|
|
assert.doesNotMatch(history.output_log, /fixture-secret/);
|
|
assert.deepEqual(operations[1].args, [{ _id: job._id, processing: true }]);
|
|
});
|
|
|
|
test('history persistence failure leaves the claimed job held', async () => {
|
|
for (const success of [true, false]) {
|
|
const collection = success ? 'done' : 'failed';
|
|
const { db, operations } = recordingDatabase(`${collection}.insertOne`);
|
|
await assert.rejects(processClaimedJob(makeJob(), {
|
|
db, execute: async () => ({ ok: success, exitCode: success ? 0 : 1, errorCategory: 'network', output: 'fixture' }),
|
|
}), /synthetic persistence failure/);
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), [`${collection}.insertOne`]);
|
|
}
|
|
});
|
|
|
|
test('ordinary failures move to failed history without globally blocking other jobs', async () => {
|
|
const { db, operations } = recordingDatabase();
|
|
await processClaimedJob(makeJob(), { db, now: () => now, execute: async () => ({
|
|
ok: false, exitCode: 1, errorCategory: 'network', output: 'Network failed',
|
|
}) });
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['failed.insertOne', 'queue.deleteOne']);
|
|
assert.equal(operations[0].args[0].error_category, 'network');
|
|
assert.equal(operations[0].args[0].failed_at, now);
|
|
assert.equal(operations[0].args[0].exit_code, 1);
|
|
});
|
|
|
|
test('authentication and resolution pause the pool before history and preserve the queued request', async () => {
|
|
for (const errorCategory of ['authentication', 'resolution']) {
|
|
const { db, operations } = recordingDatabase();
|
|
const job = makeJob();
|
|
await processClaimedJob(job, { db, execute: async () => ({
|
|
ok: false, exitCode: 1, errorCategory, output: 'Source needs verification fixture-secret==',
|
|
}) });
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), [
|
|
'settings.updateOne', 'failed.insertOne', 'queue.updateOne',
|
|
]);
|
|
assert.deepEqual(operations[0].args, [
|
|
{ _id: 'global' }, { $set: { captcha_blocked: true, pause_reason: errorCategory } }, { upsert: true },
|
|
]);
|
|
assert.equal(operations[1].args[0].error_category, errorCategory);
|
|
assert.doesNotMatch(operations[1].args[0].output_log, /fixture-secret/);
|
|
assert.equal(operations[1].args[0].token, undefined);
|
|
assert.deepEqual(operations[2].args, [
|
|
{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } },
|
|
]);
|
|
assert.equal(job.token, 'fixture_cookie=fixture-secret==');
|
|
}
|
|
});
|
|
|
|
test('failure to persist the authentication block does not release the job', async () => {
|
|
const { db, operations } = recordingDatabase('settings.updateOne');
|
|
await assert.rejects(processClaimedJob(makeJob(), { db, execute: async () => ({
|
|
ok: false, exitCode: 1, errorCategory: 'authentication', output: 'Access requires attention',
|
|
}) }), /synthetic persistence failure/);
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['settings.updateOne']);
|
|
});
|
|
|
|
test('history or claim-release failure after a resolution pause cannot delete the request', async () => {
|
|
for (const failureAt of ['failed.insertOne', 'queue.updateOne']) {
|
|
const { db, operations } = recordingDatabase(failureAt);
|
|
await assert.rejects(processClaimedJob(makeJob(), { db, execute: async () => ({
|
|
ok: false, exitCode: 1, errorCategory: 'resolution', output: 'Check the source',
|
|
}) }), /synthetic persistence failure/);
|
|
assert.equal(operations[0].collection, 'settings');
|
|
assert.equal(operations[0].args[1].$set.captcha_blocked, true);
|
|
assert.equal(operations.at(-1).collection + '.' + operations.at(-1).method, failureAt);
|
|
assert.ok(operations.every(entry => entry.method !== 'deleteOne'));
|
|
}
|
|
});
|
|
|
|
test('unacknowledged attention writes halt without consuming the request', async () => {
|
|
for (const unacknowledgedAt of ['settings.updateOne', 'failed.insertOne', 'queue.updateOne']) {
|
|
const fixture = recordingDatabase();
|
|
const db = { collection(name) {
|
|
const original = fixture.db.collection(name);
|
|
return Object.fromEntries(Object.entries(original).map(([method, operation]) => [method, async (...args) => {
|
|
const result = await operation(...args);
|
|
return name + '.' + method === unacknowledgedAt ? { acknowledged: false } : result;
|
|
}]));
|
|
} };
|
|
await assert.rejects(processClaimedJob(makeJob(), { db, execute: async () => ({
|
|
ok: false, exitCode: 1, errorCategory: 'resolution', output: 'Check the source',
|
|
}) }), /could not be confirmed/);
|
|
assert.equal(fixture.operations.at(-1).collection + '.' + fixture.operations.at(-1).method, unacknowledgedAt);
|
|
assert.ok(fixture.operations.every(entry => entry.method !== 'deleteOne'));
|
|
}
|
|
});
|
|
|
|
function claimDatabase({ pauseReads = [false, false], readFailureAt = -1, afterClaim = () => {} } = {}) {
|
|
const operations = [];
|
|
const claims = [];
|
|
let readCount = 0;
|
|
const job = makeJob();
|
|
const db = { collection(name) {
|
|
if (name === 'settings') return { findOne: async () => {
|
|
operations.push('pause.read');
|
|
const current = readCount++;
|
|
if (current === readFailureAt) throw new Error('synthetic pause read failure');
|
|
return { captcha_blocked: pauseReads[current] ?? pauseReads.at(-1) };
|
|
} };
|
|
assert.equal(name, 'queue');
|
|
return {
|
|
findOneAndUpdate: async (...args) => { operations.push('queue.claim'); claims.push(args); afterClaim(); return job; },
|
|
updateOne: async (filter, update) => {
|
|
operations.push('queue.release');
|
|
assert.deepEqual(filter, { _id: job._id, processing: true });
|
|
assert.deepEqual(update, { $unset: { processing: '', started_at: '', worker: '' } });
|
|
return { acknowledged: true };
|
|
},
|
|
};
|
|
} };
|
|
return { db, operations, job, claims };
|
|
}
|
|
|
|
test('a worker identity is recorded in the atomic claim alongside its start time', async () => {
|
|
const fixture = claimDatabase();
|
|
await claimNextJob(fixture.db, { workerIdentity: { ...workerIdentity, token: 'must-not-be-copied' }, now: () => now });
|
|
assert.deepEqual(fixture.claims, [[
|
|
{ processing: { $ne: true } },
|
|
{ $set: { processing: true, started_at: now, worker: workerIdentity } },
|
|
{ sort: { created_at: 1 }, returnDocument: 'after' },
|
|
]]);
|
|
});
|
|
|
|
test('a claim without valid identity cannot retain stale worker telemetry from an earlier attempt', async () => {
|
|
const fixture = claimDatabase();
|
|
await claimNextJob(fixture.db, { workerIdentity: { ...workerIdentity, pid: '12345' }, now: () => now });
|
|
assert.deepEqual(fixture.claims[0][1], {
|
|
$set: { processing: true, started_at: now }, $unset: { worker: '' },
|
|
});
|
|
});
|
|
|
|
test('history retains only validated worker metadata without changing claim transitions', async () => {
|
|
for (const ok of [true, false]) {
|
|
const { db, operations } = recordingDatabase();
|
|
await processClaimedJob(makeJob({ worker: { ...workerIdentity, token: 'private-worker-data' } }), {
|
|
db, execute: async () => ({ ok, exitCode: ok ? 0 : 1, errorCategory: 'resolution', output: 'fixture' }),
|
|
});
|
|
const history = operations.find(entry => entry.method === 'insertOne').args[0];
|
|
assert.deepEqual(history.worker, workerIdentity);
|
|
assert.doesNotMatch(JSON.stringify(history), /private-worker-data/);
|
|
if (!ok) assert.deepEqual(operations.at(-1).args[1], { $unset: { processing: '', started_at: '', worker: '' } });
|
|
}
|
|
});
|
|
|
|
test('a paused pool does not claim a new job', async () => {
|
|
const fixture = claimDatabase({ pauseReads: [true] });
|
|
assert.equal(await claimNextJob(fixture.db), null);
|
|
assert.deepEqual(fixture.operations, ['pause.read']);
|
|
});
|
|
|
|
test('a pause arriving during claim acquisition releases only the never-started claim', async () => {
|
|
const fixture = claimDatabase({ pauseReads: [false, true] });
|
|
assert.equal(await claimNextJob(fixture.db), null);
|
|
assert.deepEqual(fixture.operations, ['pause.read', 'queue.claim', 'pause.read', 'queue.release']);
|
|
});
|
|
|
|
test('claim pause-read failure fails closed and leaves an acquired claim held', async () => {
|
|
for (const readFailureAt of [0, 1]) {
|
|
const fixture = claimDatabase({ readFailureAt });
|
|
await assert.rejects(claimNextJob(fixture.db), /synthetic pause read failure/);
|
|
assert.ok(!fixture.operations.includes('queue.release'));
|
|
assert.equal(fixture.operations.includes('queue.claim'), readFailureAt === 1);
|
|
}
|
|
});
|
|
|
|
test('a stop during claim acquisition releases it, while an open pool admits the job', async () => {
|
|
let stopping = false;
|
|
const stopped = claimDatabase({ afterClaim: () => { stopping = true; } });
|
|
assert.equal(await claimNextJob(stopped.db, { shouldStop: () => stopping }), null);
|
|
assert.equal(stopped.operations.at(-1), 'queue.release');
|
|
const open = claimDatabase();
|
|
assert.equal(await claimNextJob(open.db), open.job);
|
|
assert.deepEqual(open.operations, ['pause.read', 'queue.claim', 'pause.read']);
|
|
});
|
|
|
|
test('processClaimedJob uses its default executor when no execute override is supplied', async () => {
|
|
const { db, operations } = recordingDatabase();
|
|
const result = await processClaimedJob(makeJob({ url: 'invalid-source' }), { db });
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.errorCategory, 'validation');
|
|
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['failed.insertOne', 'queue.deleteOne']);
|
|
});
|
|
|
|
test('interrupted jobs release only their own claim without creating history or blocking the pool', async () => {
|
|
const { db, operations } = recordingDatabase();
|
|
const job = makeJob();
|
|
const result = await processClaimedJob(job, { db, execute: async () => ({
|
|
ok: false, exitCode: null, errorCategory: 'interrupted', output: 'Worker is stopping',
|
|
}) });
|
|
assert.equal(result.errorCategory, 'interrupted');
|
|
assert.deepEqual(operations, [{
|
|
collection: 'queue', method: 'updateOne',
|
|
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
|
}]);
|
|
});
|
|
|
|
test('infrastructure failures preserve the request, release its claim, and reject to halt the worker', async () => {
|
|
for (const errorCategory of ['spawn', 'storage', 'configuration']) {
|
|
const { db, operations } = recordingDatabase();
|
|
const job = makeJob();
|
|
await assert.rejects(processClaimedJob(job, { db, execute: async () => ({
|
|
ok: false, exitCode: null, errorCategory, infrastructureFailure: true, output: 'Unavailable',
|
|
}) }), /infrastructure is unavailable.*remains queued/);
|
|
assert.deepEqual(operations, [{
|
|
collection: 'queue', method: 'updateOne',
|
|
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '', worker: '' } }],
|
|
}]);
|
|
}
|
|
});
|