grafana-cloud-graphite
Version:
NodeJS client for Grafana Cloud Graphite API
88 lines • 3.2 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphiteMetrics = void 0;
const httpHandler_1 = require("./httpHandler");
const counter_1 = require("./metricTypes/counter");
const events_1 = __importDefault(require("events"));
const gauge_1 = require("./metricTypes/gauge");
const stats_1 = require("./metricTypes/stats");
class GraphiteMetrics extends events_1.default {
constructor(options) {
super();
this.options = options;
this.metricsStore = new Map();
this.intervalHandlers = new Map();
this.httpHandler = new httpHandler_1.GraphiteHTTP({ ...this.options });
}
registerCounter(name, interval, tags) {
const metrics = new counter_1.GraphiteCounter(this.options.namespace ? `${this.options.namespace}.${name}` : name, interval, tags);
this.registerMetric(metrics, interval);
return metrics;
}
registerStats(name, interval, tags) {
const metrics = new stats_1.GraphiteStats(this.options.namespace ? `${this.options.namespace}.${name}` : name, interval, tags);
this.registerMetric(metrics, interval);
return metrics;
}
async sendMetric(name, interval, value, time, tags) {
const data = {
name: this.options.namespace ? `${this.options.namespace}.${name}` : name,
interval,
value,
time: time ?? Date.now(),
tags,
};
try {
await this.httpHandler.sendMetrics(data);
}
catch (error) {
this.emit("error", error);
}
finally {
return;
}
}
registerGauge(name, interval, tags) {
const metrics = new gauge_1.GraphiteGauge(this.options.namespace ? `${this.options.namespace}.${name}` : name, interval, tags);
this.registerMetric(metrics, interval);
return metrics;
}
stop() {
this.intervalHandlers.forEach((interval) => {
clearInterval(interval);
});
}
registerMetric(metric, interval) {
if (this.metricsStore.has(interval) === false) {
this.metricsStore.set(interval, []);
this.registerIntervalHandler(interval);
}
this.metricsStore.get(interval)?.push(metric);
}
registerIntervalHandler(interval) {
if (this.intervalHandlers.has(interval)) {
return;
}
this.intervalHandlers.set(interval, setInterval(async () => {
const metrics = this.metricsStore.get(interval);
if (!metrics || metrics?.length === 0) {
return;
}
const data = [];
metrics.forEach((metric) => {
data.push(...metric.clear());
});
try {
await this.httpHandler.sendMetrics(data);
}
catch (error) {
this.emit("error", error);
}
}, interval));
}
}
exports.GraphiteMetrics = GraphiteMetrics;
//# sourceMappingURL=metricsHandler.js.map