UNPKG

vulcain-corejs

Version:
97 lines (95 loc) 3.64 kB
"use strict"; const actualTime_1 = require("../../../utils/actualTime"); const percentileBucket_1 = require("./percentileBucket"); const fast_stats_1 = require('fast-stats'); class RollingPercentile { constructor(timeInMillisecond, numberOfBuckets) { this.currentBucketIndex = 0; if (timeInMillisecond <= 0 || numberOfBuckets <= 0) throw new Error("Invalid arguments for RollingPercentile. Must be > 0."); this.windowLength = timeInMillisecond; this.numberOfBuckets = numberOfBuckets; this.buckets = []; this.percentileSnapshot = new PercentileSnapshot(); // Pre initialize buckets for (let i = 0; i < numberOfBuckets; i++) { this.buckets[i] = new percentileBucket_1.default(); } this.buckets[0].windowStart = actualTime_1.default.getCurrentTime(); } get bucketSizeInMilliseconds() { return this.windowLength / this.numberOfBuckets; } addValue(value) { this.getCurrentBucket().addValue(value); } getPercentile(percentile) { this.getCurrentBucket(); return this.percentileSnapshot.getPercentile(percentile); } getCurrentBucket() { let currentTime = actualTime_1.default.getCurrentTime(); let currentBucket = this.buckets[this.currentBucketIndex]; if (currentTime < (currentBucket.windowStart + this.bucketSizeInMilliseconds)) { return currentBucket; } this.currentBucketIndex = (this.currentBucketIndex + 1) % this.numberOfBuckets; currentBucket = this.buckets[this.currentBucketIndex]; currentBucket.reset(currentTime); this.percentileSnapshot = new PercentileSnapshot(this.buckets); return currentBucket; } getLength() { let length = 0; for (let bucket of this.buckets) { let values = bucket.values; if (values) length++; } return length; } } exports.RollingPercentile = RollingPercentile; class PercentileSnapshot { constructor(allBuckets = []) { this.stats = new fast_stats_1.Stats(); for (let bucket of allBuckets) { let values = bucket.values; if (values) this.stats.push(values); } this.mean = this.stats.amean() || 0; this.p0 = this.stats.percentile(0) || 0; this.p5 = this.stats.percentile(5) || 0; this.p10 = this.stats.percentile(10) || 0; this.p25 = this.stats.percentile(25) || 0; this.p50 = this.stats.percentile(50) || 0; this.p75 = this.stats.percentile(75) || 0; this.p90 = this.stats.percentile(90) || 0; this.p95 = this.stats.percentile(95) || 0; this.p99 = this.stats.percentile(99) || 0; this.p995 = this.stats.percentile(99.5) || 0; this.p999 = this.stats.percentile(99.9) || 0; this.p100 = this.stats.percentile(100) || 0; } getPercentile(percentile = "mean") { if (percentile === "mean") { return this.mean; } switch (percentile) { case 0: return this.p0; case 5: return this.p5; case 10: return this.p10; case 25: return this.p25; case 50: return this.p50; case 75: return this.p75; case 90: return this.p90; case 95: return this.p95; case 99: return this.p99; case 99.5: return this.p995; case 99.9: return this.p999; case 100: return this.p100; } } } //# sourceMappingURL=rollingPercentile.js.map