aboutsummaryrefslogtreecommitdiffstats
path: root/packages/testnet-faucets/src/ts/dispatch_queue.ts
blob: 2dbeeba7a7d9e56ef0fa2b6031fd59d36fc1f97e (plain) (blame)
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
import { intervalUtils, logUtils } from '@0xproject/utils';
import * as _ from 'lodash';

import { errorReporter } from './error_reporter';

const MAX_QUEUE_SIZE = 500;
const DEFAULT_QUEUE_INTERVAL_MS = 1000;

export class DispatchQueue {
    private _queueIntervalMs: number;
    private _queue: Array<() => Promise<void>>;
    private _queueIntervalIdIfExists?: NodeJS.Timer;
    constructor() {
        this._queueIntervalMs = DEFAULT_QUEUE_INTERVAL_MS;
        this._queue = [];
        this._start();
    }
    public add(taskAsync: () => Promise<void>): boolean {
        if (this.isFull()) {
            return false;
        }
        this._queue.push(taskAsync);
        return true;
    }
    public size(): number {
        return this._queue.length;
    }
    public isFull(): boolean {
        return this.size() >= MAX_QUEUE_SIZE;
    }
    public stop() {
        if (!_.isUndefined(this._queueIntervalIdIfExists)) {
            intervalUtils.clearAsyncExcludingInterval(this._queueIntervalIdIfExists);
        }
    }
    private _start() {
        this._queueIntervalIdIfExists = intervalUtils.setAsyncExcludingInterval(
            async () => {
                const taskAsync = this._queue.shift();
                if (_.isUndefined(taskAsync)) {
                    return Promise.resolve();
                }
                await taskAsync();
            },
            this._queueIntervalMs,
            (err: Error) => {
                logUtils.log(`Unexpected err: ${err} - ${JSON.stringify(err)}`);
                // tslint:disable-next-line:no-floating-promises
                errorReporter.reportAsync(err);
            },
        );
    }
}