feat: 完善服务监控与下游重投

This commit is contained in:
hectorzhao
2026-08-14 17:21:29 +08:00
parent d30d9ea4d0
commit 1ef4380422
50 changed files with 1279 additions and 82 deletions
+24
View File
@@ -0,0 +1,24 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import type { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { MetricsService } from './metrics.service';
type RequestLike = { method?: string; baseUrl?: string; route?: { path?: string } };
type ResponseLike = { statusCode?: number };
@Injectable()
export class MetricsInterceptor implements NestInterceptor {
constructor(private readonly metrics: MetricsService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
if (context.getType() !== 'http') return next.handle();
const http = context.switchToHttp();
const request = http.getRequest<RequestLike>();
const response = http.getResponse<ResponseLike>();
const startedAt = this.metrics.beginRequest();
return next.handle().pipe(finalize(() => {
const route = `${request.baseUrl ?? ''}${request.route?.path ?? '/unmatched'}`;
this.metrics.finishRequest(startedAt, request.method ?? 'UNKNOWN', route, response.statusCode ?? 500);
}));
}
}