File size: 2,482 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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 };