'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const { createConfig } = require('../lib/config'); const { createPm2Controller, normalizeProcess } = require('../controllers/pm2Controller'); const settings = createConfig({ MONGO_URI: 'mongodb://fixture.invalid/unused' }); const SEQUENCE_ID = 'worker-name-sequence'; function response() { return { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; return this; }, }; } function processRecord(name, managed = true, id = 0) { return { name, pid: 1000 + id, pm_id: id, pm2_env: { name, status: 'online', pm_exec_path: managed ? settings.workerScript : '/unrelated/server.js', pm_uptime: Date.UTC(2026, 9, 23, 10), TOKEN: 'PRIVATE_PM2_ENV', } }; } function database(initial) { const state = { value: initial, calls: [], initializationRace: false, acknowledged: true }; const collection = { async updateOne(filter, update, options) { state.calls.push({ method: 'updateOne', filter, update, options }); assert.deepEqual(filter, { _id: SEQUENCE_ID }); assert.equal(options.maxTimeMS, 5000); assert.deepEqual(Object.keys(update), ['$max']); if (state.value === undefined || state.value < update.$max.value) state.value = update.$max.value; if (state.initializationRace && options.upsert) { state.initializationRace = false; const error = new Error('PRIVATE_MONGO_ERROR'); error.code = 11000; throw error; } return { acknowledged: state.acknowledged }; }, async findOneAndUpdate(filter, update, options) { state.calls.push({ method: 'findOneAndUpdate', filter, update, options }); assert.deepEqual(filter, { _id: SEQUENCE_ID, value: { $gte: 0, $lt: Number.MAX_SAFE_INTEGER } }); assert.deepEqual(update, { $inc: { value: 1 } }); assert.equal(options.returnDocument, 'after'); assert.equal(options.includeResultMetadata, false); assert.equal(options.maxTimeMS, 5000); assert.deepEqual(options.projection, { value: 1 }); if (typeof state.value !== 'number' || state.value < 0 || state.value >= Number.MAX_SAFE_INTEGER) return null; return { _id: SEQUENCE_ID, value: ++state.value }; }, }; const db = { collection(name) { assert.equal(name, 'settings'); return collection; } }; return { db, state, collection }; } function supervisor(existing = [], db = database(), commandResult = {}) { const calls = []; const run = async args => { calls.push([...args]); if (args[0] === 'jlist') return { code: 0, stdout: JSON.stringify(existing) }; return { code: 0, stdout: 'PRIVATE_PM2_OUTPUT', ...commandResult }; }; return { controller: createPm2Controller({ settings, run, getDb: async () => db.db }), calls, db, run }; } test('quick add chooses the next number above managed and unrelated PM2 names', async () => { const f = supervisor([ processRecord('proxer-worker-2'), processRecord('proxer-worker-012', false), processRecord('unrelated-worker-999', false), processRecord('proxer-worker-latest', false), ]); const res = response(); await f.controller.quickAdd({ body: {} }, res); assert.equal(res.statusCode, 200); assert.equal(res.body.name, 'proxer-worker-13'); assert.equal(res.body.ok, true); assert.deepEqual(f.calls, [['jlist'], ['start', settings.workerScript, '--name', 'proxer-worker-13', '--cwd', settings.projectRoot, '--interpreter', process.execPath, '--kill-timeout', '10000']]); assert.equal(f.db.state.calls[0].update.$max.value, 12); assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_|stdout|pm2_env/); }); test('quick add starts at one and keeps increasing after process deletion and controller restart', async () => { const db = database(); for (const expected of [1, 2, 3]) { const f = supervisor([], db); const res = response(); await f.controller.quickAdd({}, res); assert.equal(res.body.name, `proxer-worker-${expected}`); } assert.equal(db.state.value, 3); }); test('concurrent quick-add requests across controllers reserve distinct persistent numbers', async () => { const db = database(); const requests = Array.from({ length: 8 }, () => supervisor([processRecord('proxer-worker-5')], db)); const results = await Promise.all(requests.map(async f => { const res = response(); await f.controller.quickAdd({}, res); assert.equal(res.statusCode, 200); return res.body.name; })); assert.equal(new Set(results).size, 8); assert.deepEqual(results.map(name => Number(name.split('-').at(-1))).sort((a, b) => a - b), [6, 7, 8, 9, 10, 11, 12, 13]); assert.equal(db.state.value, 13); }); test('a duplicate-key initialization race retries seeding without another upsert', async () => { const db = database(); db.state.initializationRace = true; const f = supervisor([processRecord('proxer-worker-7')], db); const res = response(); await f.controller.quickAdd({}, res); assert.equal(res.body.name, 'proxer-worker-8'); assert.equal(db.state.calls.length, 3); assert.equal(db.state.calls[0].options.upsert, true); assert.equal(db.state.calls[1].options.upsert, undefined); }); test('quick add does not accept a client-selected name, command or script', async () => { const f = supervisor(); for (const body of [{ name: 'all' }, { scriptPath: '/unrelated.js' }, { cmd: 'delete' }, [], 'bad']) { const res = response(); await f.controller.quickAdd({ body }, res); assert.equal(res.statusCode, 400); } assert.equal(f.calls.length, 0); assert.equal(f.db.state.calls.length, 0); }); test('failed starts consume their reserved number and expose no supervisor output', async () => { const f = supervisor([], database(), { code: 1 }); const failed = response(); await f.controller.quickAdd({}, failed); assert.equal(failed.statusCode, 502); assert.equal(failed.body.ok, false); assert.equal(failed.body.name, 'proxer-worker-1'); const next = supervisor([], f.db); const created = response(); await next.controller.quickAdd({}, created); assert.equal(created.body.name, 'proxer-worker-2'); assert.doesNotMatch(JSON.stringify(failed.body), /PRIVATE_/); }); test('unconfirmed starts keep their reserved number and request refresh before retrying', async () => { const db = database(); const controller = createPm2Controller({ settings, getDb: async () => db.db, run: async args => { if (args[0] === 'jlist') return { code: 0, stdout: '[]' }; throw new Error('PRIVATE_PM2_FAILURE'); }, }); const res = response(); await controller.quickAdd({}, res); assert.equal(res.statusCode, 503); assert.equal(res.body.name, 'proxer-worker-1'); assert.match(res.body.error, /Refresh the worker list/); assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_/); assert.equal(db.state.value, 1); }); test('database failures and unacknowledged reservations never start a process', async () => { for (const mode of ['connect', 'seed', 'reserve', 'acknowledge']) { const db = database(); if (mode === 'acknowledge') db.state.acknowledged = false; if (mode === 'seed') db.collection.updateOne = async () => { throw new Error('PRIVATE_DATABASE_FAILURE'); }; if (mode === 'reserve') db.collection.findOneAndUpdate = async () => { throw new Error('PRIVATE_DATABASE_FAILURE'); }; const calls = []; const controller = createPm2Controller({ settings, getDb: async () => { if (mode === 'connect') throw new Error('PRIVATE_DATABASE_FAILURE'); return db.db; }, run: async args => { calls.push(args); return { code: 0, stdout: '[]' }; }, }); const res = response(); await controller.quickAdd({}, res); assert.equal(res.statusCode, 503, mode); assert.deepEqual(calls, [['jlist']], mode); assert.doesNotMatch(JSON.stringify(res.body), /PRIVATE_/); } }); test('unsafe, exhausted and corrupt saved counters cannot create guessed or duplicate names', async () => { for (const value of [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER + 1, 'corrupt-counter', 0.5]) { const f = supervisor([], database(value)); const res = response(); await f.controller.quickAdd({}, res); assert.equal(res.statusCode, 409); assert.deepEqual(f.calls, [['jlist']]); } const f = supervisor([processRecord('proxer-worker-9007199254740992', false)]); const res = response(); await f.controller.quickAdd({}, res); assert.equal(res.statusCode, 409); assert.equal(f.db.state.calls.length, 0); assert.deepEqual(f.calls, [['jlist']]); }); test('managed worker inventory includes validated absolute start time and excludes environments', async () => { const f = supervisor([processRecord('proxer-worker-1'), processRecord('unrelated', false, 4)]); const workers = await f.controller.listManagedProcesses(); assert.equal(workers.length, 1); assert.equal(workers[0].startedAtISO, '2026-10-23T10:00:00.000Z'); assert.doesNotMatch(JSON.stringify(workers), /PRIVATE_|pm2_env/); for (const value of [undefined, null, 0, -1, Infinity, '178234', 1e20]) { const record = processRecord('proxer-worker-1'); record.pm2_env.pm_uptime = value; assert.equal(normalizeProcess(record).startedAtISO, null); } });