Skip to content

Commit

Permalink
fix(registries): add workaround to save default labels
Browse files Browse the repository at this point in the history
  • Loading branch information
SkeLLLa committed Jul 28, 2022
1 parent f1501d0 commit 51247ce
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
47 changes: 47 additions & 0 deletions src/__tests__/edge-cases.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,51 @@ describe('edge cases', () => {
// );
});
});

describe('default labels', () => {
const app = fastify();

afterAll(async () => {
await app.close();
});

beforeAll(async () => {
await app.register(fastifyPlugin, {
endpoint: '/metrics',
});
app.metrics.client.register.setDefaultLabels({ foo: 'bar' });
app.get('/test', async () => {
return 'get test';
});
await app.ready();
});

test('added labels present in metrics', async () => {
await expect(
app.inject({
method: 'GET',
url: '/test',
})
).resolves.toBeDefined();

const metrics = await app.inject({
method: 'GET',
url: '/metrics',
});

expect(typeof metrics.payload).toBe('string');

const lines = metrics.payload.split('\n');

expect(lines).toEqual(
expect.arrayContaining([
expect.stringMatching(
/process_cpu_user_seconds_total\{foo="bar"\} \d+/
),
'http_request_duration_seconds_count{method="GET",route="/test",status_code="200",foo="bar"} 1',
'http_request_summary_seconds_count{method="GET",route="/test",status_code="200",foo="bar"} 1',
])
);
});
});
});
15 changes: 10 additions & 5 deletions src/fastify-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,17 @@ export class FastifyMetrics implements IFastifyMetrics {
const defaultRegistries = this.getCustomDefaultMetricsRegistries();
const routeRegistries = this.getCustomRouteMetricsRegistries();

const regisitriesToMerge = Array.from(
new Set([globalRegistry, ...defaultRegistries, ...routeRegistries])
);

const routeHandler = async (_: FastifyRequest, reply: FastifyReply) => {
const merged = this.deps.client.Registry.merge([
globalRegistry,
...defaultRegistries,
...routeRegistries,
]);
if (regisitriesToMerge.length === 1) {
const data = await regisitriesToMerge[0].metrics();
return reply.type(regisitriesToMerge[0].contentType).send(data);
}
// WARN: Looses default labels
const merged = this.deps.client.Registry.merge(regisitriesToMerge);

const data = await merged.metrics();
return reply.type(merged.contentType).send(data);
Expand Down

0 comments on commit 51247ce

Please sign in to comment.