UNPKG

gcf-helper

Version:
67 lines (66 loc) 1.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class MetricsHandler { constructor(gcfHelper) { this.gcfHelper = gcfHelper; this.buffer = []; this.timeout = null; } increment(metricName, value = 1, labels = {}) { const metric = { type: "counter", metric: metricName, value, labels, }; this.buffer.push(metric); this.flushOrSpawn(); } set(metricName, value = 0, labels = {}) { const metric = { type: "gauge", metric: metricName, value, labels, }; this.buffer.push(metric); this.flushOrSpawn(); } kill() { if (this.timeout) { clearTimeout(this.timeout); } } flushOrSpawn() { const ftms = this.gcfHelper.functionOptions.metricsFlushTimeoutMs; if (!ftms || ftms < 0) { this.flush(); // promise ignored return; } // timeout already running if (this.timeout !== null) { return; } this.timeout = setTimeout(() => { this.flush(); // promise ignored this.timeout = null; }, ftms); } async flush() { // expects await this.gcfHelper.ensureMetricsReady() to be called first try { if (!this.buffer.length) { return; } const readBuffer = Buffer.from(JSON.stringify(this.buffer)); this.buffer = []; await this.gcfHelper.functionOptions .pubSubClient.topic(this.gcfHelper.functionOptions.metricsTopic) .publish(readBuffer); } catch (error) { console.log(`Failed to publish metrics to pubsub topic: ${error.message}.`); } } } exports.default = MetricsHandler;