hamok
Version:
Lightweight Distributed Object Storage on RAFT consensus algorithm
71 lines (70 loc) • 2.07 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WaitingQueue = void 0;
const logger_1 = require("./logger");
const logger = (0, logger_1.createLogger)('WaitingQueue');
class WaitingQueue {
timeoutInMs;
onCompleted;
_queue = [];
_timer;
_completed = false;
constructor(timeoutInMs, onCompleted, timeoutReason) {
this.timeoutInMs = timeoutInMs;
this.onCompleted = onCompleted;
this._timer = setTimeout(() => {
this._timer = undefined;
this.clear(timeoutReason ?? 'Waiting Timeout');
}, this.timeoutInMs);
logger.trace('WaitingQueue created with timeout %d', this.timeoutInMs);
}
get completed() {
return this._completed;
}
wait(supplier) {
return new Promise((resolve, reject) => {
this._queue.push({
action: () => {
supplier()
.then(resolve)
.catch(reject);
},
reject,
});
});
}
add(action) {
this._queue.push({ action });
}
flush() {
if (this._completed)
return;
this._completed = true;
if (this._timer) {
clearTimeout(this._timer);
this._timer = undefined;
}
for (const item of this._queue) {
logger.trace('WaitingQueue item is executed');
item.action();
}
this._queue = [];
this.onCompleted?.();
}
clear(rejectReason) {
if (this._completed)
return;
this._completed = true;
if (this._timer) {
clearTimeout(this._timer);
this._timer = undefined;
}
for (const item of this._queue) {
logger.trace('WaitingQueue item is rejected: %s', rejectReason);
item.reject?.(rejectReason ?? 'Queue is cleared');
}
this._queue = [];
this.onCompleted?.();
}
}
exports.WaitingQueue = WaitingQueue;