@@ -12,6 +12,9 @@ import type { RedisClientType } from 'redis';
1212import { checkHealth } from '../monitoring/health/health.js' ;
1313import type { AuthMiddleware } from '../middleware/types.js' ;
1414import { isDomainError } from '../../shared/errors/errors.js' ;
15+ import { tracingMiddleware } from '../middleware/tracing.js' ;
16+ import { metricsMiddleware , metricsResponseHook } from '../middleware/metrics.js' ;
17+ import { register } from '../monitoring/metrics/metrics.js' ;
1518
1619/**
1720 * 创建 Fastify 服务器
@@ -40,11 +43,20 @@ export function createServer(config: Config): FastifyInstance {
4043 * 注册全局中间件
4144 */
4245export async function registerMiddleware ( fastify : FastifyInstance ) : Promise < void > {
46+ // 请求追踪(必须在最前面,确保所有请求都有 TraceID/RequestID)
47+ fastify . addHook ( 'onRequest' , tracingMiddleware ) ;
48+
4349 // CORS
4450 await fastify . register ( cors , {
4551 origin : true ,
4652 } ) ;
4753
54+ // Metrics 中间件(记录请求开始时间)
55+ fastify . addHook ( 'onRequest' , metricsMiddleware ) ;
56+
57+ // Metrics 响应 Hook(记录请求指标)
58+ fastify . addHook ( 'onResponse' , metricsResponseHook ) ;
59+
4860 // Security headers (手动实现,因为 @fastify/helmet 不支持 Fastify 5)
4961 fastify . addHook ( 'onRequest' , async ( _request : FastifyRequest , reply : FastifyReply ) => {
5062 reply . header ( 'X-Content-Type-Options' , 'nosniff' ) ;
@@ -111,6 +123,12 @@ export function registerRoutes(
111123 return reply . code ( statusCode ) . send ( health ) ;
112124 } ) ;
113125
126+ // Prometheus Metrics 端点
127+ fastify . get ( '/metrics' , async ( _request : unknown , reply ) => {
128+ reply . type ( 'text/plain' ) ;
129+ return register . metrics ( ) ;
130+ } ) ;
131+
114132 // 根路径
115133 fastify . get ( '/' , async ( _request : unknown , reply ) => {
116134 return reply . send ( {
@@ -128,7 +146,8 @@ export function registerRoutes(
128146export async function registerDomainRoutes (
129147 fastify : FastifyInstance ,
130148 handlerDeps : Record < string , unknown > ,
131- authMiddleware : AuthMiddleware
149+ authMiddleware : AuthMiddleware ,
150+ redis : RedisClientType | null = null
132151) : Promise < void > {
133152 // 动态导入并注册 Task 路由
134153 if ( handlerDeps . task ) {
@@ -153,7 +172,11 @@ export async function registerDomainRoutes(
153172 // 动态导入并注册 Auth 路由(不需要认证中间件)
154173 if ( handlerDeps . auth ) {
155174 const authRouter = await import ( '../../domains/auth/http/router.js' ) ;
156- authRouter . registerAuthRoutes ( fastify , handlerDeps . auth as Parameters < typeof authRouter . registerAuthRoutes > [ 1 ] ) ;
175+ authRouter . registerAuthRoutes (
176+ fastify ,
177+ handlerDeps . auth as Parameters < typeof authRouter . registerAuthRoutes > [ 1 ] ,
178+ redis
179+ ) ;
157180 }
158181}
159182
0 commit comments