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

+322
View File
@@ -0,0 +1,322 @@
"use strict";
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 { createWorkerIdentity, toPublicWorkerIdentity } = require("../lib/workerIdentity");
const {
readActivity, createInventoryReader, readActiveFileSize,
ACTIVE_JOB_LIMIT, WORKER_LIMIT, ACTIVITY_READ_PROJECTION,
} = require("../lib/activity");
const { createDashboardController, RECENT_LIMIT } = require("../controllers/dashboardController");
const { STATUS_READ_PROJECTION } = require("../lib/jobValidation");
const { QUERY_TIMEOUT_MS } = require("../lib/statusQuery");
const HOST = "download-host";
const START = "2026-01-01T12:00:00.000Z";
const CLAIM = "2026-01-01T12:01:00.000Z";
const RUN_ID = "7b3c9e3a-8b0b-41c6-988c-8e9e01dbbf4a";
const identity = (changes = {}) => ({
name: "proxer-worker-1", pid: 1234, host: HOST, run_id: RUN_ID, started_at: START, ...changes,
});
const processRecord = (changes = {}) => ({
name: "proxer-worker-1", pid: 1234, pm_id: "1", status: "online", startedAtISO: START, ...changes,
});
const activeRecord = (changes = {}) => ({
_id: "job-1", filename: "ExampleS001E001_engsub", processing: true, created_at: START,
started_at: CLAIM, url: "https://proxer.me/watch/42/1/engsub", worker: identity(), ...changes,
});
function activityDatabase(records = [], failure) {
const reads = [];
const db = { collection(name) {
assert.equal(name, "queue");
return { find(filter, options) {
const read = { filter, options };
reads.push(read);
const cursor = {
sort(value) { read.sort = value; return cursor; },
limit(value) { read.limit = value; return cursor; },
async toArray() { if (failure) throw failure; return records.slice(0, read.limit); },
};
return cursor;
} };
} };
return { db, reads };
}
async function activityFixture(records, processes = [processRecord()], options = {}) {
const fixture = activityDatabase(records);
const fileChecks = [];
const result = await readActivity(fixture.db, {
host: HOST, listWorkers: async () => processes,
readFileSize: async job => { fileChecks.push(job._id); return 123; }, ...options,
});
return { ...fixture, result, fileChecks };
}
test("worker identity is immutable, names are safe, and each actual process run has a unique ID", () => {
const explicit = createWorkerIdentity({
env: { PROXER_WORKER_NAME: "proxer-worker-9", name: "proxer-worker-1" },
pid: 1234, host: HOST, uuid: () => RUN_ID, now: () => new Date(START),
});
assert.equal(Object.isFrozen(explicit), true);
assert.throws(() => { explicit.pid = 5; }, TypeError);
assert.deepEqual(explicit, identity({ name: "proxer-worker-9" }));
const unsafe = createWorkerIdentity({
env: { PROXER_WORKER_NAME: "<script>private</script>", name: "bad name" },
pid: 1234, host: HOST, uuid: () => RUN_ID, now: () => new Date(START),
});
assert.equal(unsafe.name, "worker-1234");
const actual = createWorkerIdentity({ env: {} });
assert.equal(actual.pid, process.pid);
assert.equal(actual.host, os.hostname());
assert.equal(actual.name, `worker-${process.pid}`);
assert.notEqual(actual.run_id, createWorkerIdentity({ env: {} }).run_id);
});
test("worker identity DTO drops extra fields and rejects incomplete or unsafe legacy metadata", () => {
assert.deepEqual(toPublicWorkerIdentity({ ...identity(), token: "secret", env: { PRIVATE: "value" } }), identity());
for (const value of [
null, [], {}, { name: "proxer-worker-1", pid: 1234 },
identity({ pid: "1234" }), identity({ pid: 0 }), identity({ pid: NaN }),
identity({ name: "<script>" }), identity({ host: "https://host/secret" }),
identity({ run_id: "not-a-run-id" }), identity({ started_at: "2026-02-31T12:00:00.000Z" }),
]) assert.equal(toPublicWorkerIdentity(value), null);
});
test("activity connects a verified local claim to its managed worker and includes idle and stopped workers", async () => {
const { result } = await activityFixture([activeRecord()], [
processRecord({ name: "renamed-worker" }),
processRecord({ pm_id: "2", pid: 2345, name: "proxer-worker-2" }),
processRecord({ pm_id: "3", pid: 0, name: "proxer-worker-3", status: "stopped" }),
]);
assert.equal(result.available, true);
assert.equal(result.workers.length, 3);
assert.equal(result.workers[0].name, "renamed-worker");
assert.equal(result.workers[0].jobs[0]._id, "job-1");
assert.deepEqual(result.workers[0].jobs[0].worker, identity());
assert.equal(result.workers[0].jobs[0].fileSize, 123);
assert.deepEqual(result.workers[1].jobs, []);
assert.equal(result.workers[1].activityUnknown, false);
assert.equal(result.workers[2].status, "stopped");
assert.equal(result.workers[2].pid, null);
assert.deepEqual(result.unassigned, []);
});
test("pre-update active jobs stay unassigned and do not falsely imply that known workers are idle", async () => {
const { result } = await activityFixture([
activeRecord({ worker: undefined }), activeRecord({ _id: "job-2", worker: { name: "proxer-worker-1", pid: 1234 } }),
]);
assert.deepEqual(result.workers[0].jobs, []);
assert.equal(result.workers[0].activityUnknown, true);
assert.equal(result.unassigned.length, 2);
for (const job of result.unassigned) {
assert.equal(job.worker, null);
assert.equal(job.assignmentReason, "unknown-worker");
}
});
test("PID reuse, other hosts, missing launch time, and ambiguous inventory never attach a claim to a current worker", async () => {
const cases = [
["stale-worker", activeRecord(), [processRecord({ startedAtISO: "2026-01-01T12:02:00.000Z" })]],
["remote-worker", activeRecord({ worker: identity({ host: "other-host" }) }), [processRecord()]],
["unverified-worker", activeRecord(), [processRecord({ startedAtISO: null })]],
["unverified-worker", activeRecord({ started_at: "2026-01-01T11:59:00.000Z" }), [processRecord()]],
["ambiguous-worker", activeRecord(), [processRecord(), processRecord({ pm_id: "2", name: "another-worker" })]],
["worker-not-running", activeRecord(), [processRecord({ pid: 4321 })]],
["worker-not-running", activeRecord(), [processRecord({ status: "stopped" })]],
];
for (const [reason, job, processes] of cases) {
const { result } = await activityFixture([job], processes);
assert.ok(result.workers.every(worker => worker.jobs.length === 0), reason);
assert.equal(result.unassigned[0].assignmentReason, reason);
}
});
test("unavailable PM2 preserves active jobs and their saved identity while a database read failure propagates", async () => {
const unavailable = async () => { throw new Error("private supervisor failure"); };
const { result } = await activityFixture([activeRecord()], [], { listWorkers: unavailable });
assert.equal(result.available, false);
assert.deepEqual(result.workers, []);
assert.equal(result.unassigned[0].assignmentReason, "supervisor-unavailable");
assert.deepEqual(result.unassigned[0].worker, identity());
assert.doesNotMatch(JSON.stringify(result), /private supervisor failure/);
const failure = new Error("database unavailable");
const broken = activityDatabase([], failure);
await assert.rejects(readActivity(broken.db, { listWorkers: unavailable }), error => error === failure);
});
test("active reads and filesystem checks are bounded and truncation cannot mark unobserved workers idle", async () => {
const records = Array.from({ length: ACTIVE_JOB_LIMIT + 10 }, (_, index) => activeRecord({ _id: `job-${index}` }));
const { result, reads, fileChecks } = await activityFixture(records);
assert.deepEqual(reads, [{
filter: { processing: true }, options: { projection: ACTIVITY_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS },
sort: { created_at: 1, _id: 1 }, limit: ACTIVE_JOB_LIMIT + 1,
}]);
assert.equal(result.truncated, true);
assert.equal(result.workers[0].activityUnknown, true);
assert.equal(result.workers[0].jobs.length, ACTIVE_JOB_LIMIT);
assert.equal(fileChecks.length, ACTIVE_JOB_LIMIT);
});
test("worker inventory is bounded while duplicates outside the visible page remain ambiguous", async () => {
const processes = Array.from({ length: WORKER_LIMIT + 1 }, (_, index) => processRecord({
pm_id: String(index + 1), name: `proxer-worker-${index + 1}`, pid: 1234 + index,
}));
processes.push(processRecord({ pm_id: "99", name: "duplicate-beyond-page", pid: 1234 }));
const { result } = await activityFixture([activeRecord()], processes);
assert.equal(result.workers.length, WORKER_LIMIT);
assert.equal(result.workersTruncated, true);
assert.equal(result.unassigned[0].assignmentReason, "ambiguous-worker");
assert.ok(result.workers.every(worker => worker.activityUnknown));
});
test("activity DTOs remove credentials, signed URLs, raw supervisor metadata, and unknown worker fields", async () => {
const { result } = await activityFixture([activeRecord({
token: "session=private-cookie-value",
url: "https://media.example/file.mp4?signature=private-signature",
output_log: "credential private-cookie-value https://media.example/file.mp4?signature=private-signature",
worker: { ...identity(), env: { PRIVATE: "private-env" }, token: "private-worker-token" },
})], [processRecord({ execPath: "/private-host-path", pm2_env: { SECRET: "private-pm2-env" } })]);
const publicText = JSON.stringify(result);
assert.doesNotMatch(publicText, /private-cookie-value|private-signature|private-env|private-worker-token|private-host-path|private-pm2-env/);
assert.equal(result.workers[0].jobs[0].url, "Source URL unavailable");
assert.equal(result.workers[0].jobs[0].token, undefined);
});
test("inventory caching shares concurrent PM2 reads and expires after ten seconds", async () => {
let clock = 0;
let calls = 0;
let finish;
const gate = new Promise(resolve => { finish = resolve; });
const readInventory = createInventoryReader(async () => { calls += 1; await gate; return [processRecord()]; }, { now: () => clock });
const first = readInventory();
const second = readInventory();
assert.equal(calls, 1);
finish();
assert.equal((await first).available, true);
assert.equal((await second).available, true);
await readInventory();
assert.equal(calls, 1);
clock = 10000;
await readInventory();
assert.equal(calls, 2);
});
test("a supervisor failure is briefly cached but can recover at the next inventory refresh", async () => {
let clock = 0;
let fail = true;
let calls = 0;
const readInventory = createInventoryReader(async () => {
calls += 1;
if (fail) throw new Error("unavailable");
return [processRecord()];
}, { now: () => clock });
assert.equal((await readInventory()).available, false);
fail = false;
assert.equal((await readInventory()).available, false);
assert.equal(calls, 1);
clock = 10000;
assert.equal((await readInventory()).available, true);
assert.equal(calls, 2);
});
test("active filesize lookup never follows links or unsafe filenames", async t => {
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-activity-"));
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
await fs.writeFile(path.join(outputDir, "regular.mp4"), "fixture");
await fs.symlink(path.join(outputDir, "regular.mp4"), path.join(outputDir, "link.mp4"));
assert.equal(await readActiveFileSize({ filename: "regular" }, { outputDir }), 7);
for (const filename of ["link", "missing", "../regular"]) {
assert.equal(await readActiveFileSize({ filename }, { outputDir }), null);
}
});
function dashboardDatabase({ failure } = {}) {
const reads = [];
const db = { collection(name) {
return {
async countDocuments(filter, options) {
reads.push({ type: "count", name, filter, options });
if (failure) throw failure;
return name === "queue" ? (filter.processing === true ? 2 : 3) : 8;
},
async findOne(filter, options) {
reads.push({ type: "global", name, filter, options });
return { captcha_blocked: true, pause_reason: "resolution", private: "private-global" };
},
find(filter, options) {
const read = { type: "recent", name, filter, options };
reads.push(read);
const cursor = {
sort(value) { read.sort = value; return cursor; },
limit(value) { read.limit = value; return cursor; },
async toArray() {
return Array.from({ length: 8 }, (_, index) => ({
_id: `${name}-${index}`, filename: `Episode ${index}`, token: "cookie=private-history-cookie",
output_log: "legacy private-history-cookie", [name === "done" ? "finished_at" : "failed_at"]: CLAIM,
})).slice(0, read.limit);
},
};
return cursor;
},
};
} };
return { db, reads };
}
test("dashboard returns bounded recent history, counts, pause state, and activity without exposing raw records", async () => {
const fixture = dashboardDatabase();
const activity = { workers: [], unassigned: [], truncated: false, workersTruncated: false, available: true };
const settings = { outputDir: "/fixture/output" };
const controller = createDashboardController({
getDb: async () => fixture.db, config: settings,
readActivity: async (db, options) => { assert.equal(db, fixture.db); assert.equal(options.settings, settings); return activity; },
});
const result = await controller.readDashboard();
assert.deepEqual(result.counts, { queued: 3, processing: 2, done: 8, failed: 8 });
assert.deepEqual(result.global, { captcha_blocked: true, pause_reason: "resolution" });
assert.equal(result.activity, activity);
for (const state of ["done", "failed"]) {
assert.equal(result.recent[state].length, RECENT_LIMIT);
assert.equal(result.recent[state][0].fileSize, undefined);
}
assert.doesNotMatch(JSON.stringify(result), /private-history-cookie|private-global/);
const recentReads = fixture.reads.filter(read => read.type === "recent");
assert.equal(recentReads.length, 2);
for (const read of recentReads) {
assert.deepEqual(read.options, { projection: STATUS_READ_PROJECTION, maxTimeMS: QUERY_TIMEOUT_MS });
assert.equal(read.limit, RECENT_LIMIT);
assert.deepEqual(read.sort, { [read.name === "done" ? "finished_at" : "failed_at"]: -1, _id: -1 });
}
const countReads = fixture.reads.filter(read => read.type === "count");
assert.equal(countReads.length, 4);
assert.ok(countReads.every(read => read.options.maxTimeMS === QUERY_TIMEOUT_MS));
});
test("dashboard page and JSON disable caching, and database errors reach the generic error handler", async () => {
const fixture = dashboardDatabase();
const controller = createDashboardController({ getDb: async () => fixture.db, readActivity: async () => ({ workers: [] }) });
for (const [method, render] of [["dashboard", true], ["dashboardData", false]]) {
const headers = {};
let payload, template;
const response = {
set(name, value) { headers[name] = value; return response; },
render(name, value) { template = name; payload = value; return response; },
json(value) { payload = value; return response; },
};
await controller[method]({}, response, error => { throw error; });
assert.equal(headers["Cache-Control"], "no-store");
if (render) { assert.equal(template, "dashboard"); assert.equal(payload.activePage, "dashboard"); }
else assert.equal(payload.counts.processing, 2);
}
const failure = new Error("private database detail");
const broken = dashboardDatabase({ failure });
const unavailable = createDashboardController({ getDb: async () => broken.db, readActivity: async () => ({ workers: [] }) });
let received;
await unavailable.dashboardData({}, { set() {}, json() { assert.fail("Must not report an empty dashboard on failure"); } }, error => { received = error; });
assert.equal(received, failure);
});