const { config } = require("../config/env"); const { nextJob, updateJob, event } = require("./jobs"); const { processJob } = require("./worker"); const { serializeError } = require("../utils/errors"); const { logger } = require("../monitoring/logger"); class Queue { constructor(botApi, progress) { this.botApi = botApi; this.progress = progress; this.active = 0; this.paused = false; this.timer = null; this.idleResolvers = []; } start() { this.timer = setInterval(() => this.tick(), 1500); this.timer.unref(); this.tick(); } pause() { this.paused = true; } resume() { this.paused = false; this.tick(); } async tick() { if (this.paused) return; while (this.active < config.queue.maxConcurrentJobs) { const job = nextJob(); if (!job) break; this.active += 1; this.run(job).finally(() => { this.active -= 1; this.resolveIdle(); this.tick(); }); } } async run(job) { try { await processJob(job, this.botApi, (targetJob, value, stage, message) => { updateJob(targetJob.id, { progress: value, status: stage, stage }); this.progress(targetJob.id, value, stage, message).catch((error) => logger.warn({ error: error.message }, "Progress update failed")); }); } catch (error) { const serialized = serializeError(error); event(job.id, "error", serialized.message, serialized); const attempts = job.attempts + 1; const retry = attempts < job.maxAttempts; updateJob(job.id, { status: retry ? "retrying" : "failed", stage: retry ? "waiting-retry" : "failed", attempts, error: serialized.message }); try { await this.botApi.sendMessage(job.chatId, retry ? `Retrying after error: ${serialized.message}` : `Processing failed: ${serialized.message}`); } catch (sendError) { logger.warn({ error: sendError.message }, "Could not send failure message"); } } } waitForIdle(timeoutMs) { if (this.active === 0) return Promise.resolve(); return new Promise((resolve) => { const timer = setTimeout(resolve, timeoutMs); this.idleResolvers.push(() => { clearTimeout(timer); resolve(); }); }); } resolveIdle() { if (this.active !== 0) return; for (const resolve of this.idleResolvers.splice(0)) resolve(); } } module.exports = { Queue };