@lokalise/fastify-extras
Version:
Opinionated set of fastify plugins, commonly used in Lokalise
95 lines • 3.29 kB
JavaScript
import tracer, {} from 'dd-trace';
import fp from 'fastify-plugin';
import { FifoMap } from 'toad-cache';
export class DatadogTransactionManager {
isEnabled;
spanMap;
constructor(isEnabled) {
this.isEnabled = isEnabled;
this.spanMap = new FifoMap(2000);
}
static createDisabled() {
return new DatadogTransactionManager(false);
}
/**
* @param transactionName - used for grouping similar transactions together
* @param uniqueTransactionKey - used for identifying specific ongoing transaction. Must be reasonably unique to reduce possibility of collisions
*/
start(transactionName, uniqueTransactionKey) {
if (!this.isEnabled)
return;
const span = tracer.startSpan(transactionName, {
tags: {
'transaction.type': 'background',
},
});
this.spanMap.set(uniqueTransactionKey, span);
}
/**
* @param transactionName - used for grouping similar transactions together
* @param uniqueTransactionKey - used for identifying specific ongoing transaction. Must be reasonably unique to reduce possibility of collisions
* @param transactionGroup - group is used for grouping related transactions with different names
*/
startWithGroup(transactionName, uniqueTransactionKey, transactionGroup) {
if (!this.isEnabled)
return;
const span = tracer.startSpan(transactionName, {
tags: {
'transaction.type': 'background',
'transaction.group': transactionGroup,
},
});
this.spanMap.set(uniqueTransactionKey, span);
}
stop(uniqueTransactionKey) {
if (!this.isEnabled)
return;
const span = this.spanMap.get(uniqueTransactionKey) ?? null;
if (!span)
return;
span.finish();
this.spanMap.delete(uniqueTransactionKey);
}
addCustomAttribute(attrName, attrValue) {
if (!this.isEnabled)
return;
const activeSpan = tracer.scope().active();
if (activeSpan) {
activeSpan.setTag(attrName, attrValue);
}
}
addCustomAttributes(uniqueTransactionKey, atts) {
if (!this.isEnabled)
return;
const span = this.spanMap.get(uniqueTransactionKey);
if (!span)
return;
span.addTags(atts);
}
setUserID(userId) {
if (!this.isEnabled)
return;
const activeSpan = tracer.scope().active();
if (activeSpan) {
activeSpan.setTag('usr.id', userId);
}
}
setControllerName(name, action) {
if (!this.isEnabled)
return;
const activeSpan = tracer.scope().active();
if (activeSpan) {
activeSpan.setTag('code.namespace', name);
activeSpan.setTag('code.function', action);
}
}
}
function plugin(fastify, opts) {
const manager = new DatadogTransactionManager(opts.isEnabled);
fastify.decorate('datadogTransactionManager', manager);
}
export const datadogTransactionManagerPlugin = fp(plugin, {
fastify: '5.x',
name: 'datadog-transaction-manager-plugin',
});
//# sourceMappingURL=datadogTransactionManagerPlugin.js.map