File size: 1,568 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Logger } from 'pino';

type FunctionNoArgs = () => Promise<any>;

/**
 * Run a job (function) after a delay,
 * but make sure we run exactly ONE job at the same time
 */
export class SingleDelayedJobRunner {
  private timeout: NodeJS.Timeout;
  private logger: Logger;

  constructor(
    private name: string,
    private timeoutMs: number,
    logger: Logger,
    private warningOverride: boolean = false,
  ) {
    this.logger = logger.child({
      job: name,
      class: SingleDelayedJobRunner.name,
    });
  }

  get scheduled(): boolean {
    return !!this.timeout;
  }

  schedule(fn: FunctionNoArgs): boolean {
    if (this.scheduled) {
      const msg = `Job has been started before, do not schedule it again`;
      this.log(this.warningOverride, msg);
      return false;
    }

    this.timeout = setTimeout(() => {
      this.logger.debug(`Running job...`);
      fn()
        .catch((error) => {
          this.logger.error(`Job failed: ${error}`);
          this.logger.error(error.stack);
        })
        .finally(() => {
          this.timeout = null;
          this.logger.debug(`Job finished`);
        });
    }, this.timeoutMs);
    this.logger.info(`Job scheduled with timeout ${this.timeoutMs} ms`);
    return true;
  }

  cancel() {
    if (!this.timeout) {
      return;
    }
    clearTimeout(this.timeout);
    this.timeout = null;
    this.logger.info(`Job cancelled`);
  }

  private log(warning: boolean, msg: string) {
    if (warning) {
      this.logger.warn(msg);
    } else {
      this.logger.info(msg);
    }
  }
}