@boxyhq/metrics
Version:
Internal SDK for OTel instrumentation
76 lines (75 loc) • 2.91 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.instrument = instrument;
exports.instrumented = instrumented;
const counter_1 = require("./counter");
const timer_1 = require("./timer");
/**
* Run the given function, recording throughput, latency and errors
*
* @param operationParams
*/
function instrument(_a) {
return __awaiter(this, arguments, void 0, function* ({ meter, name, delegate, instrumentAttributes }) {
const start = process.hrtime.bigint();
try {
return yield delegate();
}
catch (err) {
(0, counter_1.incrementCounter)({
meter,
name: 'function.errors',
counterAttributes: Object.assign({ function: name }, instrumentAttributes),
});
throw err;
}
finally {
const end = process.hrtime.bigint();
const elapsedNanos = end - start;
(0, timer_1.recordTimer)({
meter,
name: 'function.executionTime',
val: Number(elapsedNanos) /** convert bigint to number */,
timerAttributes: Object.assign({ function: name }, instrumentAttributes),
});
}
});
}
/**
* Decorator that instruments a class method
*
* @param meter - Name of OTel meter
*/
function instrumented(meter) {
return function (target, key, descriptor) {
if (descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, key);
}
if (descriptor === undefined) {
return descriptor;
}
const originalMethod = descriptor.value;
const klass = target.constructor.name;
// this needs to be a non-arrow function or we'll get the wrong `this`
function overrideMethod(...args) {
return instrument({
meter,
name: `${klass}.${key}`,
delegate: () => __awaiter(this, void 0, void 0, function* () {
return yield originalMethod.apply(this, args);
}),
});
}
descriptor.value = overrideMethod;
return descriptor;
};
}