@mediarithmics/plugins-nodejs-sdk
Version:
This is the mediarithmics nodejs to help plugin developers bootstrapping their plugin without having to deal with most of the plugin boilerplate
88 lines • 3.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatsClient = exports.MetricsType = void 0;
const hot_shots_1 = require("hot-shots");
var MetricsType;
(function (MetricsType) {
MetricsType["GAUGE"] = "gauge";
MetricsType["INCREMENT"] = "increment";
})(MetricsType || (exports.MetricsType = MetricsType = {}));
/**
* Send stats to datadog
*/
class StatsClient {
constructor(timerInMs, environment) {
this.metrics = new Map();
this.client = new hot_shots_1.StatsD({
protocol: environment === 'production' ? 'uds' : undefined,
});
if (!this.interval) {
this.interval = setInterval(() => this.sendStats(), timerInMs);
}
}
/**
* @example
* ```
* private this.statsClient: StatsClient
* constructor() {
* this.statsClient = StatsClient.init({ environment: process.env.NODE_ENV });
* }
* ```
*/
static init({ timerInMs = 10 * 60 * 1000, environment = process.env.NODE_ENV, logger }) {
logger === null || logger === void 0 ? void 0 : logger.info(`StatsClient - environment is ${environment ? environment : 'undefined'} mode - Timer is ${timerInMs} - Initialization.`);
return this.instance || (this.instance = new StatsClient(timerInMs, environment));
}
/**
* Increment some metrics
* @example
* ```
* this.statClient.addOrUpdateMetrics({metrics: {processed_users: { type: MetricsType.GAUGE, value: 4, tags: {datamart_id: '4521'}}, users_with_mobile_id_count: {type: MetricsType.INCREMENT, value: 1, tags: {datamart_id: '4521'}}}})
* this.statClient.addOrUpdateMetrics({metrics: {apiCallsError: { type: MetricsType.GAUGE, value: 10, tags: {statusCode: '500'}}}})
* ```
*/
addOrUpdateMetrics({ metrics }) {
Object.entries(metrics).forEach(([metricName, options]) => {
const customKey = metricName + '/' + JSON.stringify(options.tags);
if (this.metrics.has(customKey)) {
const metricOptions = this.metrics.get(customKey);
this.metrics.set(customKey, {
metricName,
type: metricOptions.type,
value: metricOptions.value + options.value,
tags: { ...options.tags },
});
}
else {
this.metrics.set(customKey, {
metricName,
type: options.type,
value: options.value,
tags: options.tags,
});
}
});
}
sendStats() {
[...this.metrics.entries()].forEach(([customKey, options]) => {
if (options.type === MetricsType.GAUGE) {
this.client.gauge(options.metricName, options.value, { ...options.tags });
}
else {
this.client.increment(options.metricName, options.value, { ...options.tags });
this.resetIncrementMetric(customKey, options.metricName);
}
});
}
resetIncrementMetric(customKey, metricName) {
const metricOptions = this.metrics.get(customKey);
this.metrics.set(customKey, {
metricName,
type: metricOptions.type,
value: 0,
tags: { ...metricOptions.tags },
});
}
}
exports.StatsClient = StatsClient;
//# sourceMappingURL=StatsClient.js.map