willsoto/nestjs-prometheus

[HMR] Error: A metric with the name X has already been registered.

AndreyNikolov opened this issue · 1 comments

Hey!

I am using "nestjs-prometheus":"5.3.0" with "@nestjs/core": "9.3.11", and I am experiencing the following problem when I run my nest app in docker with HMR enabled:

dev  | Entrypoint main 3.3 MiB = main.js 3.29 MiB 0.bff7ae7a987fbf27b165.hot-update.js 10.2 KiB
dev  | webpack 5.76.2 compiled successfully in 22491 ms
dev  | Running in env: development
dev  | [HMR] Cannot apply update.
dev  | [HMR] Error: A metric with the name process_cpu_user_seconds_total has already been registered.
dev  |     at Registry.registerMetric (/usr/src/app/server/node_modules/prom-client/lib/registry.js:67:10)
dev  |     at new Metric (/usr/src/app/server/node_modules/prom-client/lib/metric.js:48:13)
dev  |     at new Counter (/usr/src/app/server/node_modules/prom-client/lib/counter.js:12:1)
dev  |     at module.exports (/usr/src/app/server/node_modules/prom-client/lib/metrics/processCpuTotal.js:16:30)
dev  |     at Object.collectDefaultMetrics (/usr/src/app/server/node_modules/prom-client/lib/defaultMetrics.js:47:3)
dev  |     at Function.configureServer (/usr/src/app/server/node_modules/@willsoto/nestjs-prometheus/dist/module.js:104:24)
dev  |     at Function.register (/usr/src/app/server/node_modules/@willsoto/nestjs-prometheus/dist/module.js:23:28)
dev  |     at Object.<anonymous> (/usr/src/app/server/dist/main.js:454:50)
dev  |     at __webpack_require__ (/usr/src/app/server/dist/main.js:40842:33)
dev  |     at fn (/usr/src/app/server/dist/main.js:40949:21)
dev  | [HMR] You need to restart the application!

This is one of the default prom-client metrics.

My configuration is the following:
app.module.ts

imports: [
...
  PrometheusModule.register({
        defaultLabels: {
          app: 'test',
        },
        path: '/api/test/metrics',
      }),
  ...
  })
...],
providers: [
  ...
  makeCounterProvider({
      name: 'http_exception',
      help: 'Counter of HTTP exceptions, based on method, path and status',
      labelNames: ['method', 'path', 'status'],
    }),
  ...
]

I see that this is a common issue, and I was able to overcome it with clearing all the metrics before loading the new hmr update:

if (module.hot) {
    prom.register.clear();
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }

but is there any more Nest way to achieve this?

Nope. Looks about right to me. prom-client is a global singleton so HMR doesn't really work it