VirtualPR/backend/scripts/wastra-careful-resume.js

167 lines
5.1 KiB
JavaScript

/**
* Careful Wastra resume after a closed/throttled session.
* - Waits until /api/v1/groups stays open for WASTRA_STABLE_OPEN_MS
* - Requeues only failed manual sends (never mass-requeue)
* - Then requeues failed create_group tasks one at a time with long gaps
*
* Usage: node scripts/wastra-careful-resume.js
*/
import mongoose from 'mongoose';
import { env } from '../src/config/env.js';
import { WhatsAppTask } from '../src/models/WhatsAppTask.js';
import { getWastraSessionHealth, WASTRA_STABLE_OPEN_MS } from '../src/services/wastra.js';
// Do not start a second WhatsApp worker — virtualpr PM2 already runs concurrency 1.
const MANUAL_IDS = [
'6b0444e87b0d38d1a2df7da9', // already done earlier; skipped if not failed
'6b0444ea7b0d38d1a2df7dba',
];
const GROUP_STEP_MS = 90 * 1000;
const POLL_MS = 15 * 1000;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function waitUntilStable() {
let openSince = null;
for (;;) {
const health = await getWastraSessionHealth();
const now = Date.now();
if (!health.open) {
openSince = null;
console.log(`[resume] Wastra ${health.status}: ${health.error || 'closed'}; waiting`);
await sleep(POLL_MS);
continue;
}
if (!openSince) {
openSince = now;
console.log(`[resume] Wastra open; need ${Math.ceil(WASTRA_STABLE_OPEN_MS / 1000)}s stable`);
}
const elapsed = now - openSince;
if (elapsed >= WASTRA_STABLE_OPEN_MS) {
console.log('[resume] Wastra stable open');
return;
}
console.log(`[resume] open for ${Math.floor(elapsed / 1000)}s / ${Math.ceil(WASTRA_STABLE_OPEN_MS / 1000)}s`);
await sleep(POLL_MS);
}
}
async function requeueTask(id) {
const task = await WhatsAppTask.findById(id);
if (!task) {
console.log(`[resume] missing task ${id}`);
return null;
}
if (task.status === 'done') {
console.log(`[resume] already done ${id} (${task.phone || task.kind})`);
return task;
}
task.status = 'pending';
task.attempts = 0;
task.lockedAt = null;
task.lastError = '';
task.runAt = new Date();
await task.save();
console.log(`[resume] requeued ${id} kind=${task.kind} flag=${task.flag || ''} phone=${task.phone || ''}`);
return task;
}
async function waitForDone(id, timeoutMs = 10 * 60 * 1000) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const task = await WhatsAppTask.findById(id).select('status lastError phone kind');
if (!task) return null;
if (task.status === 'done') {
console.log(`[resume] done ${id}`);
return task;
}
if (task.status === 'failed' || task.status === 'cancelled') {
console.log(`[resume] stopped ${id} status=${task.status} error=${task.lastError}`);
return task;
}
await sleep(5000);
}
throw new Error(`Timed out waiting for ${id}`);
}
async function main() {
await mongoose.connect(env.MONGODB_URI);
// Park non-manual open work so manuals go first without a backlog fight.
const parked = await WhatsAppTask.updateMany(
{
status: { $in: ['pending', 'running'] },
dedupeKey: { $not: /^manual:/ },
},
{
$set: {
status: 'pending',
lockedAt: null,
runAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
lastError: 'Parked until careful Wastra resume finishes manuals',
},
},
);
console.log(`[resume] parked ${parked.modifiedCount} non-manual open tasks`);
await waitUntilStable();
for (const id of MANUAL_IDS) {
const task = await requeueTask(id);
if (!task || task.status === 'done') continue;
await waitForDone(id);
await sleep(GROUP_STEP_MS);
}
const failedCreates = await WhatsAppTask.find({
status: 'failed',
kind: 'create_group',
updatedAt: { $gte: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000) },
lastError: /number is close|502|429|409/i,
}).sort({ updatedAt: 1 }).select('_id cohort');
console.log(`[resume] create_group to retry slowly: ${failedCreates.length}`);
for (const row of failedCreates) {
const health = await getWastraSessionHealth();
if (!health.open) {
console.log('[resume] session closed mid-run; stopping group retries');
break;
}
await requeueTask(row._id);
await waitForDone(row._id, 15 * 60 * 1000);
await sleep(GROUP_STEP_MS);
}
// Release parked membership tasks gradually (spread runAt).
const parkedTasks = await WhatsAppTask.find({
status: 'pending',
lastError: 'Parked until careful Wastra resume finishes manuals',
}).sort({ sequence: 1 }).select('_id');
let cursor = Date.now() + GROUP_STEP_MS;
for (const row of parkedTasks) {
await WhatsAppTask.updateOne(
{ _id: row._id },
{
$set: {
runAt: new Date(cursor),
lastError: '',
attempts: 0,
},
},
);
cursor += GROUP_STEP_MS;
}
console.log(`[resume] released ${parkedTasks.length} parked tasks with ${GROUP_STEP_MS / 1000}s spacing`);
console.log('[resume] finished; worker continues draining slowly');
await sleep(5000);
await mongoose.disconnect();
process.exit(0);
}
main().catch((err) => {
console.error('[resume] failed', err);
process.exit(1);
});