Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion infra/dev/compose.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ services:
api:
hostname: api
container_name: api
image: ghcr.io/task-tracker-lab/task-tracker-backend:dev
image: ghcr.io/task-tracker-lab/backend:dev
env_file:
- .env
ports:
Expand Down
1 change: 1 addition & 0 deletions libs/metrics/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './metrics.module';
14 changes: 14 additions & 0 deletions libs/metrics/src/metrics.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Controller, Get, Res } from '@nestjs/common';
import * as client from 'prom-client';
import { FastifyReply } from 'fastify';
import { SkipZodValidation } from '@shared/decorators';

@Controller('metrics')
export class MetricsController {
@Get()
@SkipZodValidation()
async getMetrics(@Res() reply: FastifyReply) {
const metrics = await client.register.metrics();
reply.type(client.register.contentType).send(metrics);
}
}
29 changes: 29 additions & 0 deletions libs/metrics/src/metrics.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Module } from '@nestjs/common';
import { makeHistogramProvider, PrometheusModule } from '@willsoto/nestjs-prometheus';
import { MetricsController } from './metrics.controller';
import { HttpMetricsInterceptor } from '@shared/interceptors';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
imports: [
PrometheusModule.register({
controller: MetricsController,
defaultMetrics: {
enabled: process.env.NODE_ENV !== 'test',
},
}),
],
providers: [
makeHistogramProvider({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status'],
buckets: [0.005, 0.01, 0.05, 0.1, 0.5, 1, 2.5, 5],
}),
{
provide: APP_INTERCEPTOR,
useClass: HttpMetricsInterceptor,
},
],
})
export class MetricsModule {}
9 changes: 9 additions & 0 deletions libs/metrics/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": true,
"outDir": "../../dist/libs/metrics"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
9 changes: 9 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@
"compilerOptions": {
"tsConfigPath": "libs/imagor/tsconfig.lib.json"
}
},
"metrics": {
"type": "library",
"root": "libs/metrics",
"entryFile": "index",
"sourceRoot": "libs/metrics/src",
"compilerOptions": {
"tsConfigPath": "libs/metrics/tsconfig.lib.json"
}
}
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
"passport-jwt": "^4.0.1",
"passport-oauth2": "^1.8.0",
"postgres": "^3.4.9",
"prom-client": "^15.1.3",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"ua-parser-js": "^2.0.9",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 2 additions & 9 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { ConfigService } from '@nestjs/config';
import * as schema from './shared/entities';
import { APP_FILTER, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { ZodValidationPipe } from 'nestjs-zod';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { HealthModule } from '@libs/health';
import { UserModule } from './user';
import { GlobalExceptionFilter } from '@shared/error';
Expand All @@ -22,18 +21,11 @@ import { CACHE_SERVICE } from '@shared/adapters/cache/constants';
import { ICacheService } from '@shared/adapters/cache/ports';
import { DatabaseHealthService } from '@libs/database';
import { ZodValidationInterceptor } from '@shared/interceptors';
import { MetricsModule } from '@libs/metrics';

@Module({
imports: [
ConfigModule,
PrometheusModule.registerAsync({
useFactory: () => ({
path: 'dump',
defaultMetrics: {
enabled: process.env.NODE_ENV !== 'test',
},
}),
}),
DatabaseModule.registerAsync({
global: true,
inject: [ConfigService],
Expand Down Expand Up @@ -63,6 +55,7 @@ import { ZodValidationInterceptor } from '@shared/interceptors';
UserModule,
TeamsModule,
ProjectsModule,
MetricsModule,
HealthModule.registerAsync({
inject: [DatabaseHealthService, S3Service, CACHE_SERVICE],
useFactory: (db: DatabaseHealthService, s3: S3Service, cache: ICacheService) => {
Expand Down
4 changes: 4 additions & 0 deletions src/shared/decorators/skip-response-validation.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const SKIP_RESPONSE_VALIDATION_KEY = 'SKIP_RESPONSE_VALIDATION_KEY';
export const SkipResponseValidation = () => SetMetadata(SKIP_RESPONSE_VALIDATION_KEY, true);
51 changes: 51 additions & 0 deletions src/shared/interceptors/http-metrics.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { Histogram } from 'prom-client';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { FastifyReply, FastifyRequest } from 'fastify';

@Injectable()
export class HttpMetricsInterceptor implements NestInterceptor {
constructor(
@InjectMetric('http_request_duration_seconds')
private readonly histogram: Histogram<string>,
) {}

intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const ctx = context.switchToHttp();
const request = ctx.getRequest<FastifyRequest>();
const response = ctx.getResponse<FastifyReply>();

const end = this.histogram.startTimer();

return next.handle().pipe(
tap(() => {
this.recordMetrics(request, response, end);
}),
catchError((err) => {
this.recordMetrics(request, response, end, err);
return throwError(() => err);
}),
);
}

private recordMetrics(
req: FastifyRequest,
res: FastifyReply,
end: (labels?: any) => number,
err?: any,
) {
const route = req.routeOptions?.url || req.url;

if (route === '/metrics') return;

const statusCode = err ? err.status || err.statusCode || 500 : res.statusCode;

end({
method: req.method,
route,
status: statusCode.toString(),
});
}
}
1 change: 1 addition & 0 deletions src/shared/interceptors/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './zod-validation.interceptor';
export * from './http-metrics.interceptor';
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
"@libs/health/*": ["./libs/health/src/*"],
"@libs/imagor": ["./libs/imagor/src"],
"@libs/imagor/*": ["./libs/imagor/src/*"],
"@libs/metrics": ["./libs/metrics/src"],
"@libs/metrics/*": ["./libs/metrics/src/*"],
"@libs/s3": ["./libs/s3/src"],
"@libs/s3/*": ["./libs/s3/src/*"],
"@shared/*": ["./src/shared/*"],
Expand Down
Loading