From d9b1d31e7310f7f554f1740f93e4ccd5b5db90f5 Mon Sep 17 00:00:00 2001 From: Brandon Millman Date: Tue, 6 Feb 2018 15:15:24 -0800 Subject: Organize async task queues by network --- packages/testnet-faucets/src/ts/dispatch_queue.ts | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 packages/testnet-faucets/src/ts/dispatch_queue.ts (limited to 'packages/testnet-faucets/src/ts/dispatch_queue.ts') diff --git a/packages/testnet-faucets/src/ts/dispatch_queue.ts b/packages/testnet-faucets/src/ts/dispatch_queue.ts new file mode 100644 index 000000000..94d094203 --- /dev/null +++ b/packages/testnet-faucets/src/ts/dispatch_queue.ts @@ -0,0 +1,47 @@ +import { intervalUtils } from '@0xproject/utils'; +import * as _ from 'lodash'; + +const MAX_QUEUE_SIZE = 500; +const DEFAULT_QUEUE_INTERVAL_MS = 1000; + +export class DispatchQueue { + private _queueIntervalMs: number; + private _queue: Array<() => Promise>; + private _queueIntervalIdIfExists?: NodeJS.Timer; + constructor() { + this._queueIntervalMs = DEFAULT_QUEUE_INTERVAL_MS; + this._queue = []; + this._start(); + } + public add(task: () => Promise): boolean { + if (this.isFull()) { + return false; + } + this._queue.push(task); + 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 task = this._queue.shift(); + if (_.isUndefined(task)) { + return Promise.resolve(); + } + await task(); + }, + this._queueIntervalMs, + _.noop, + ); + } +} -- cgit v1.2.3