import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.dirname(path.dirname(fileURLToPath(import.meta.url))); test('servidor inicia encerramentos em paralelo e limita esperas antes de fechar banco', async () => { const source = await fs.readFile(path.join(root, 'scripts', 'servidor.mjs'), 'utf8'); assert.match(source, /recoverPendingOutreach\(db\)/); assert.match(source, /pauseCampaignsAfterRestart\(db\)/); assert.match(source, /recoverReservedCampaignQueue\(db\)/); assert.match(source, /onMessageStatus:\s*\(event\)\s*=>\s*updateOutreachMessageStatus\(db, event\)/); assert.ok(source.indexOf('recoverPendingOutreach(db)') < source.indexOf('const stopScheduler = startOutreachScheduler')); assert.ok(source.indexOf('pauseCampaignsAfterRestart(db)') < source.indexOf('const stopScheduler = startOutreachScheduler')); assert.ok(source.indexOf('recoverReservedCampaignQueue(db)') < source.indexOf('const stopScheduler = startOutreachScheduler')); assert.match(source, /setTimeout\(\(\) => process\.exit\(1\), 30_000\)/); const shutdown = source.slice(source.indexOf('async function shutdown()')); const schedulerStart = shutdown.indexOf('stopScheduler()'); const jobsStart = shutdown.indexOf('jobs.close()'); const whatsappStart = shutdown.indexOf('whatsapp.close()'); const sharedWait = shutdown.indexOf('Promise.allSettled(shutdownTasks)'); assert.ok(schedulerStart >= 0 && schedulerStart < sharedWait); assert.ok(jobsStart >= 0 && jobsStart < sharedWait); assert.ok(whatsappStart >= 0 && whatsappStart < sharedWait); assert.match(shutdown, /Promise\.race\([\s\S]*Promise\.allSettled\(shutdownTasks\)[\s\S]*20_000/); assert.match(shutdown, /encerramento dos recursos excedeu o prazo/); assert.ok(sharedWait < shutdown.indexOf('recoverOrphans(db, log)')); assert.ok(shutdown.indexOf('recoverOrphans(db, log)') < shutdown.indexOf('server.close(resolve)')); assert.ok(shutdown.indexOf('server.close(resolve)') < shutdown.indexOf('db.close()')); assert.match(shutdown, /encerramento HTTP excedeu o prazo/); }); test('UI distingue resultado desconhecido de falha', async () => { const source = await fs.readFile(path.join(root, 'public', 'js', 'app.js'), 'utf8'); assert.match(source, /desconhecido[^\n]+(?:Resultado desconhecido|Confirmação pendente)/); assert.match(source, /aceito[^\n]+Aguardando confirmação/); assert.match(source, /entregue[^\n]+Entregue/); assert.match(source, /refresh-qr/); assert.match(source, /persistencia_incerta[\s\S]+?aviso/); });