import { Registry, collectDefaultMetrics } from "prom-client"; export type MetricsRegistry = Registry & { readonly serviceName: string; /** * Indicates whether the prom-client default Node.js process metrics * (`process_cpu_seconds_total`, `process_resident_memory_bytes`, etc.) have * been attached to this registry. Tests rely on this flag to assert that * each service registers default metrics exactly once. */ readonly defaultMetricsAttached: boolean; }; export type CreateMetricsRegistryOptions = { serviceName: string; /** * When true (default), enables prom-client's `collectDefaultMetrics()` which * adds standard Node.js process metrics. Pass `false` in unit tests when you * want a deterministic registry without GC / event-loop noise. */ collectDefaultProcessMetrics?: boolean; /** * Extra constant labels applied to every metric on this registry. Use * sparingly — high-cardinality labels (request id, tenant id) MUST NOT be * set here. Service name + revision is the intended use. */ defaultLabels?: Record; }; /** * Returns a service-scoped Prometheus registry with default labels. * * Each app (api / worker / web SSR) creates its own registry so metric * collisions between services are impossible and so a single Prometheus job * can scrape any one endpoint without leakage from the others. */ export function createMetricsRegistry(options: CreateMetricsRegistryOptions): MetricsRegistry { const { serviceName, collectDefaultProcessMetrics = true, defaultLabels } = options; const registry = new Registry(); registry.setDefaultLabels({ service: serviceName, ...defaultLabels, }); if (collectDefaultProcessMetrics) { collectDefaultMetrics({ register: registry, prefix: "" }); } return Object.assign(registry, { serviceName, defaultMetricsAttached: collectDefaultProcessMetrics, }); }