Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(metrics): stop logging a warning on every refused scrape

Yudhi Armyndharis79c7838b6d0d
diff --git a/src/modules/metrics/metrics.controller.spec.ts b/src/modules/metrics/metrics.controller.spec.ts
new file mode 100644
index 000000000..7f2b13c99
--- /dev/null
+++ b/src/modules/metrics/metrics.controller.spec.ts
@@ -0,0 +1,53 @@
+import type { Server } from 'http';
+import { INestApplication, Logger, NotFoundException } from '@nestjs/common';
+import { Test } from '@nestjs/testing';
+import request from 'supertest';
+import { MetricsController } from './metrics.controller';
+import { MetricsService } from './metrics.service';
+
+describe('MetricsController', () => {
+ let app: INestApplication;
+ let warn: jest.SpyInstance;
+ const metricsService = { assertScrapeAuthorized: jest.fn(), render: jest.fn() };
+
+ beforeAll(async () => {
+ const moduleRef = await Test.createTestingModule({
+ controllers: [MetricsController],
+ providers: [{ provide: MetricsService, useValue: metricsService }],
+ }).compile();
+ app = moduleRef.createNestApplication({ logger: false });
+ await app.init();
+ });
+
+ beforeEach(() => {
+ warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
+ metricsService.assertScrapeAuthorized.mockReset();
+ metricsService.render.mockReset().mockResolvedValue('openwa_up 1\n');
+ });
+
+ afterEach(() => warn.mockRestore());
+
+ afterAll(async () => {
+ await app.close();
+ });
+
+ it('answers a scrape with Prometheus text that is never cached', async () => {
+ const res = await request(app.getHttpServer() as Server).get('/metrics');
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/^text\/plain/);
+ expect(res.headers['content-type']).toContain('version=0.0.4');
+ expect(res.headers['cache-control']).toBe('no-store');
+ expect(res.text).toBe('openwa_up 1\n');
+ });
+
+ it('answers a refused scrape as JSON without logging a content-type warning', async () => {
+ metricsService.assertScrapeAuthorized.mockImplementation(() => {
+ throw new NotFoundException();
+ });
+ const res = await request(app.getHttpServer() as Server).get('/metrics');
+ expect(res.status).toBe(404);
+ expect(res.headers['content-type']).toMatch(/^application\/json/);
+ expect(warn).not.toHaveBeenCalled();
+ expect(metricsService.render).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/metrics/metrics.controller.ts b/src/modules/metrics/metrics.controller.ts
index e3cf027b4..b5c23f639 100644
--- a/src/modules/metrics/metrics.controller.ts
+++ b/src/modules/metrics/metrics.controller.ts
@@ -1,7 +1,7 @@
-import { Controller, Get, Header, Req } from '@nestjs/common';
+import { Controller, Get, Header, Req, Res } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiSecurity } from '@nestjs/swagger';
import { SkipThrottle } from '@nestjs/throttler';
-import type { Request } from 'express';
+import type { Request, Response } from 'express';
import { Public } from '../auth/decorators/auth.decorators';
import { MetricsService } from './metrics.service';
import { METRICS_BEARER_SCHEME } from '../../config/swagger.config';
@@ -30,12 +30,13 @@ export class MetricsController {
@ApiResponse({ status: 401, description: 'METRICS_TOKEN is configured but the bearer is missing or wrong' })
@ApiResponse({ status: 404, description: 'Metrics endpoint is disabled (METRICS_TOKEN unset)' })
@ApiResponse({ status: 429, description: 'Too many failed token attempts from this client; retry after a minute' })
- @Header('Content-Type', 'text/plain; version=0.0.4; charset=utf-8')
@Header('Cache-Control', 'no-store')
// @Req (not @Headers('authorization')) so the OpenAPI op doesn't sprout a spurious required
// `authorization` header parameter — the bearer is expressed via the security scheme above.
- async scrape(@Req() req: Request): Promise<string> {
+ async scrape(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<string> {
this.metricsService.assertScrapeAuthorized(req.headers.authorization, req);
+ // Set only once authorized: a text/plain type on a refused (JSON) reply makes Nest log a warning.
+ res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
return this.metricsService.render();
}
}