51 lines
1.8 KiB
TypeScript
51 lines
1.8 KiB
TypeScript
/**
|
|
* API service-scoped Prometheus registry singleton.
|
|
*
|
|
* Lazily constructed so test files that mock env vars can swap the registry
|
|
* via {@link resetApiMetricsForTests}. The singleton is cheap (~30 KB of
|
|
* prom-client default metrics) and is intentionally NOT gated behind
|
|
* METRICS_ENABLED — the gate lives on the endpoints, not the registry. This
|
|
* lets business code call `apiMetrics.aiTokensConsumedTotal.inc(...)` without
|
|
* branching on an env flag everywhere.
|
|
*/
|
|
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@hivegrid/metrics";
|
|
import { setEnqueueObserver } from "@hivegrid/queue";
|
|
|
|
type ApiMetricsBundle = {
|
|
registry: MetricsRegistry;
|
|
metrics: DefaultMetrics;
|
|
};
|
|
|
|
let cached: ApiMetricsBundle | undefined;
|
|
|
|
export function getApiMetrics(): ApiMetricsBundle {
|
|
if (!cached) {
|
|
cached = buildApiMetrics();
|
|
}
|
|
return cached;
|
|
}
|
|
|
|
/**
|
|
* Reset the cached bundle. Test-only — production code never calls this.
|
|
*/
|
|
export function resetApiMetricsForTests(): void {
|
|
cached = undefined;
|
|
}
|
|
|
|
function buildApiMetrics(): ApiMetricsBundle {
|
|
const revision = process.env.APP_REVISION?.trim() ?? "";
|
|
const registry = createMetricsRegistry({
|
|
serviceName: "api",
|
|
collectDefaultProcessMetrics: true,
|
|
...(revision ? { defaultLabels: { revision } } : {}),
|
|
});
|
|
const metrics = createDefaultMetrics(registry);
|
|
// Wire BullMQ enqueue events into queue_jobs_enqueued_total. The queue
|
|
// package keeps a module-level observer slot so we register exactly once
|
|
// per process; subsequent registrations from re-built bundles overwrite.
|
|
setEnqueueObserver((event) => {
|
|
metrics.queueJobsEnqueuedTotal.labels({ queue: event.queueName, priority: event.priorityLabel }).inc();
|
|
});
|
|
return { registry, metrics };
|
|
}
|