node-apparatus
Version:
A mix of common components needed for awesome node experience
59 lines • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DistributedTimeWindow = void 0;
const distributed_window_identity_js_1 = require("./distributed-window-identity.js");
/**
* A window-ing implementation for distributed system that can be used to accumulate elements and drain them in a window of specific size or by absolute(wall clock) time window.
* It can be used to stead a frequency of elements from a mixed/different update rate.
*/
class DistributedTimeWindow {
/**
* Creates a new instance of DistributedTimeWindow.
* @param countWindowSize The size of the counting window. Should be more greater than 0.
* @param timeoutInSeconds The timeout in seconds for the window.
* @param distributedSortedSet The distributed sorted set to manage the identity windows.
* @param distributedAccumulatorResolver The distributed accumulator resolver to resolve the accumulator for each identity window.
* @param windowsFlushCallback The callback to be called when the windows are flushed.
* @throws Error if timeoutInSeconds is less than or equal to 5.
* @remarks Internally it uses setInterval to check the timed windows for expiry.
*/
constructor(countWindowSize, timeoutInSeconds, distributedSortedSet, distributedAccumulatorResolver, windowsFlushCallback) {
this.windowsFlushCallback = windowsFlushCallback;
if (timeoutInSeconds <= 5) {
throw new Error("Param 'timeoutInSeconds' must be greater then 5 second");
}
this.dataContainer = new distributed_window_identity_js_1.DistributedWindowIdentity(countWindowSize, timeoutInSeconds * 1000, distributedSortedSet, distributedAccumulatorResolver);
this.intervalHandle = setInterval(this.tick.bind(this), Math.floor(timeoutInSeconds / 2) * 1000);
}
/**
* Push a new element to be window-ed.
* @param element The new element to be pushed.
*/
async push(element) {
const windows = await this.dataContainer.window(Date.now(), element);
if (windows !== undefined && windows.length > 0) {
this.windowsFlushCallback(windows);
}
}
/**
* Flushes all elements which are accumulated.
* @returns Multiple windows.
*/
async flush() {
return await this.dataContainer.flush();
}
[Symbol.dispose]() {
clearInterval(this.intervalHandle);
}
async [Symbol.asyncDispose]() {
this[Symbol.dispose]();
}
async tick() {
const windows = await this.dataContainer.tickIdentity(Date.now());
if (windows !== undefined && windows.length > 0) {
this.windowsFlushCallback(windows);
}
}
}
exports.DistributedTimeWindow = DistributedTimeWindow;
//# sourceMappingURL=distributed-time-window.js.map