|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + NestInterceptor, |
| 4 | + ExecutionContext, |
| 5 | + CallHandler, |
| 6 | +} from '@nestjs/common'; |
| 7 | +import { Observable, throwError } from 'rxjs'; |
| 8 | +import { tap, catchError } from 'rxjs/operators'; |
| 9 | +import { PrometheusService } from './prometheus.service'; |
| 10 | + |
| 11 | +@Injectable() |
| 12 | +export class PrometheusInterceptor implements NestInterceptor { |
| 13 | + constructor(private readonly prometheusService: PrometheusService) {} |
| 14 | + |
| 15 | + intercept(context: ExecutionContext, next: CallHandler): Observable<any> { |
| 16 | + const request = context.switchToHttp().getRequest(); |
| 17 | + const response = context.switchToHttp().getResponse(); |
| 18 | + const method = request.method; |
| 19 | + const route = this.getRoute(request); |
| 20 | + const startTime = Date.now(); |
| 21 | + |
| 22 | + // Пропускаем сбор метрик для самого endpoint /metrics |
| 23 | + if (route === '/metrics' || request.path === '/metrics' || request.originalUrl?.includes('/metrics')) { |
| 24 | + return next.handle(); |
| 25 | + } |
| 26 | + |
| 27 | + return next.handle().pipe( |
| 28 | + tap((data) => { |
| 29 | + const duration = (Date.now() - startTime) / 1000; |
| 30 | + // Используем статус код из response, если доступен, иначе 200 |
| 31 | + const statusCode = response.statusCode || 200; |
| 32 | + |
| 33 | + // Записываем метрики для успешных запросов |
| 34 | + this.prometheusService.incrementHttpRequests(method, route, statusCode); |
| 35 | + this.prometheusService.recordHttpRequestDuration(method, route, duration); |
| 36 | + }), |
| 37 | + catchError((error) => { |
| 38 | + const duration = (Date.now() - startTime) / 1000; |
| 39 | + const statusCode = error.status || error.statusCode || response.statusCode || 500; |
| 40 | + const errorType = error.constructor?.name || 'UnknownError'; |
| 41 | + |
| 42 | + // Записываем метрики для ошибок |
| 43 | + this.prometheusService.incrementHttpRequests(method, route, statusCode); |
| 44 | + this.prometheusService.recordHttpRequestDuration(method, route, duration); |
| 45 | + this.prometheusService.incrementHttpErrors(method, route, statusCode, errorType); |
| 46 | + |
| 47 | + return throwError(() => error); |
| 48 | + }), |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Получает нормализованный маршрут из запроса |
| 54 | + */ |
| 55 | + private getRoute(request: any): string { |
| 56 | + // Используем route.path если доступен (NestJS) |
| 57 | + if (request.route?.path) { |
| 58 | + return request.route.path; |
| 59 | + } |
| 60 | + |
| 61 | + // Используем originalUrl или path |
| 62 | + const url = request.originalUrl || request.url || '/'; |
| 63 | + |
| 64 | + // Убираем query параметры |
| 65 | + const path = url.split('?')[0]; |
| 66 | + |
| 67 | + // Нормализуем путь (убираем версию API и префикс для более чистых метрик) |
| 68 | + let normalizedPath = path.replace(/^\/admin\/api\/v\d+\//, '/'); |
| 69 | + normalizedPath = normalizedPath.replace(/^\/admin\/api\//, '/'); |
| 70 | + |
| 71 | + // Заменяем ID параметры на :id для группировки |
| 72 | + normalizedPath = normalizedPath.replace(/\/\d+/g, '/:id'); |
| 73 | + normalizedPath = normalizedPath.replace(/\/[a-f0-9-]{36}/gi, '/:id'); // UUID |
| 74 | + |
| 75 | + return normalizedPath || '/'; |
| 76 | + } |
| 77 | +} |
| 78 | + |
0 commit comments