UNPKG

@lokalise/fastify-extras

Version:

Opinionated set of fastify plugins, commonly used in Lokalise

76 lines 3.24 kB
/** * TransactionObservabilityManager implementation that uses Prometheus counter * to track the number of started, failed and success transactions. */ export class PrometheusCounterTransactionManager { metricName; metricDescription; supportedCustomLabels; counter; transactionNameByKey = new Map(); customLabelsByKey = new Map(); constructor(metricName, metricDescription, appMetrics, customLabels) { this.metricName = metricName; this.metricDescription = metricDescription; this.supportedCustomLabels = new Set(customLabels) ?? new Set(); this.counter = this.registerMetric(appMetrics, customLabels); } start(transactionName, uniqueTransactionKey) { this.transactionNameByKey.set(uniqueTransactionKey, transactionName); this.counter?.inc({ status: 'started', transactionName: transactionName }); } startWithGroup(transactionName, uniqueTransactionKey, _transactionGroup) { this.transactionNameByKey.set(uniqueTransactionKey, transactionName); this.counter?.inc({ status: 'started', transactionName }); } stop(uniqueTransactionKey, wasSuccessful = true) { const transactionName = this.transactionNameByKey.get(uniqueTransactionKey); if (!transactionName) return; const labels = { status: wasSuccessful ? 'success' : 'failed', transactionName, }; let labelsWithCustom; if (this.customLabelsByKey.has(uniqueTransactionKey)) { const customLabels = this.customLabelsByKey.get(uniqueTransactionKey); labelsWithCustom = { ...labels, // biome-ignore lint/style/noNonNullAssertion: we already checked the presence ...customLabels, }; } this.counter?.inc(labelsWithCustom ?? labels); this.transactionNameByKey.delete(uniqueTransactionKey); this.customLabelsByKey.delete(uniqueTransactionKey); } /** * Prometheus labels are the way Prometheus handles custom attributes * Note that it will skip any attributes that were not included in the constructor param "customLabels" */ addCustomAttributes(uniqueTransactionKey, atts) { const transactionName = this.transactionNameByKey.get(uniqueTransactionKey); if (!transactionName) return; const supportedLabels = Object.entries(atts).reduce((acc, [key, value]) => { if (this.supportedCustomLabels.has(key)) { acc[key] = value; } return acc; }, {}); this.customLabelsByKey.set(uniqueTransactionKey, supportedLabels); } registerMetric(appMetrics, customLabels = []) { if (!appMetrics) return; const existingMetric = appMetrics.client.register.getSingleMetric(this.metricName); if (existingMetric) return existingMetric; return new appMetrics.client.Counter({ name: this.metricName, help: this.metricDescription, labelNames: ['status', 'transactionName', ...customLabels], }); } } //# sourceMappingURL=PrometheusCounterTransactionManager.js.map