UNPKG

@promster/fastify

Version:

Fastify server integrations of promster

67 lines (66 loc) 2.96 kB
import { Prometheus, Prometheus as Prometheus$1, createGcMetrics, createGcObserver, createHttpMetrics, createRequestRecorder, defaultNormalizers, defaultNormalizers as defaultNormalizers$1, defaultRegister, getContentType, getSummary, skipMetricsInEnvironment, timing, timing as timing$1 } from "@promster/metrics"; import fastifyPlugin from "fastify-plugin"; import merge from "merge-options"; //#region package.json var name = "@promster/fastify"; //#endregion //#region src/plugin/plugin.ts let recordRequest; let upMetric; const extractPath = (req) => req.raw.originalUrl || req.raw.url; const getRequestRecorder = () => recordRequest; const signalIsUp = () => { if (!upMetric) return; for (const upMetricType of upMetric) upMetricType.set(1); }; const signalIsNotUp = () => { if (!upMetric) return; for (const upMetricType of upMetric) upMetricType.set(0); }; const createPlugin = async (fastify, options) => { const allDefaultedOptions = merge(createHttpMetrics.defaultOptions, createGcMetrics.defaultOptions, createRequestRecorder.defaultOptions, createGcObserver.defaultOptions, defaultNormalizers$1, options); const shouldSkipMetricsByEnvironment = skipMetricsInEnvironment(allDefaultedOptions); const httpMetrics = createHttpMetrics(allDefaultedOptions); const gcMetrics = createGcMetrics(allDefaultedOptions); const observeGc = createGcObserver(gcMetrics, allDefaultedOptions); recordRequest = createRequestRecorder(httpMetrics, allDefaultedOptions); upMetric = gcMetrics?.up; if (!shouldSkipMetricsByEnvironment) observeGc(); fastify.decorate("Prometheus", Prometheus$1); fastify.decorate("recordRequest", recordRequest); fastify.decorateRequest("__promsterTiming__", null); fastify.addHook("onRequest", async (request, _) => { request.__promsterTiming__ = timing$1.start(); }); fastify.addHook("onResponse", async (request, reply) => { const labels = Object.assign({}, { method: allDefaultedOptions.normalizeMethod(request.raw.method ?? "", { req: request, res: reply }), status_code: allDefaultedOptions.normalizeStatusCode(reply.statusCode, { req: request, res: reply }), path: allDefaultedOptions.normalizePath(extractPath(request), { req: request, res: reply }) }, allDefaultedOptions.getLabelValues?.(request, reply)); const requestContentLength = Number(request.headers["content-length"] ?? 0); const responseContentLength = Number(reply.getHeader("content-length") ?? 0); if (!allDefaultedOptions.skip?.(request, reply, labels) && !shouldSkipMetricsByEnvironment) recordRequest(request.__promsterTiming__, { labels, requestContentLength, responseContentLength }); }); signalIsUp(); }; const plugin = fastifyPlugin(createPlugin, { fastify: ">= 5.0.0", name }); //#endregion export { Prometheus, defaultNormalizers, defaultRegister, getContentType, getRequestRecorder, getSummary, plugin, signalIsNotUp, signalIsUp, timing }; //# sourceMappingURL=index.js.map