Implement metrics

This commit is contained in:
2023-11-15 10:46:48 +01:00
parent 8ad7bbdebb
commit 652be94621
7 changed files with 154 additions and 4 deletions

30
metrics/circularBuffer.js Normal file
View File

@@ -0,0 +1,30 @@
class CircularBuffer {
constructor(size) {
this.buffer = new Array(size);
this.size = size;
this.head = 0;
this.tail = 0;
}
push(item) {
this.buffer[this.head] = item;
this.head = (this.head + 1) % this.size;
if (this.head === this.tail) {
this.tail = (this.tail + 1) % this.size;
}
}
toArray() {
const result = [];
let current = this.tail;
for (let i = 0; i < this.size; i++) {
if (this.buffer[current] !== undefined) {
result.push(this.buffer[current]);
}
current = (current + 1) % this.size;
}
return result;
}
}
module.exports = { CircularBuffer };

24
metrics/metricManager.js Normal file
View File

@@ -0,0 +1,24 @@
const cliProgress = require("cli-progress");
const { Metric } = require("./metrics");
class MetricManager {
constructor() {
this.metricBufferSize = 1000;
this.multibar = new cliProgress.MultiBar(
{
clearOnComplete: false,
barCompleteChar: "\u2588",
barIncompleteChar: "\u2591",
format: " {bar} | {name} | {value}/{total}",
},
cliProgress.Presets.shades_grey
);
}
AddMetrics(name) {
const metric = new Metric(name, this.multibar, this.metricBufferSize);
return metric;
}
}
module.exports = { MetricManager };

39
metrics/metrics.js Normal file
View File

@@ -0,0 +1,39 @@
const { CircularBuffer } = require("./circularBuffer");
class Metric {
constructor(barName, multibar, bufferSize) {
this.multibar = multibar;
this.pbar = multibar.create(0, 0);
this.pbar.update(0, { name: barName });
this.buffer = new CircularBuffer(bufferSize);
this.maxRate = 0;
setInterval(this.UpdateBar.bind(this), 100);
}
AddEvent() {
const timestamp = Date.now();
this.buffer.push({ timestamp, count: 1 });
}
GetRate() {
const entries = this.buffer.toArray();
const currentTime = Date.now();
const interval = entries.length > 1 ? currentTime - entries[0].timestamp : 1;
const totalRX = entries.reduce((sum, entry) => sum + entry.count, 0);
return Math.round((totalRX / interval) * 100000) / 100;
}
UpdateBar() {
const eps = this.GetRate();
if (eps > this.maxRate) {
this.pbar.total = eps;
this.maxRate = eps;
}
this.pbar.update(eps);
this.multibar.update();
}
}
module.exports = { Metric };