feat(infra): add OTel auto-instrumentations across all services
Some checks failed
CI / quality-proto (push) Failing after 2s
CI / deploy (push) Has been skipped
CI / quality-ts (push) Failing after 1m11s
CI / quality-go (push) Failing after 5s

NestJS 6 services use getNodeAutoInstrumentations().

Python 2 services use FastAPIInstrumentor. Go 2 services use otelgin.
This commit is contained in:
SpecialX
2026-07-09 13:25:46 +08:00
parent 1f901c5b20
commit d8dab70406
28 changed files with 1653 additions and 224 deletions

View File

@@ -12,8 +12,10 @@ import (
"github.com/edu-cloud/api-gateway/internal/config"
"github.com/edu-cloud/api-gateway/internal/health"
"github.com/edu-cloud/api-gateway/internal/middleware"
"github.com/edu-cloud/api-gateway/internal/observability"
"github.com/edu-cloud/api-gateway/internal/proxy"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
)
// maxBodyBytes 请求体大小上限10MB
@@ -21,6 +23,10 @@ const maxBodyBytes int64 = 10 * 1024 * 1024
func main() {
cfg := config.Load()
// 初始化 OpenTelemetry tracerendpoint 为空时自动跳过)
tracerShutdown := observability.InitTracer("api-gateway", cfg.OTLPEndpoint)
defer tracerShutdown()
gin.SetMode(gin.ReleaseMode)
r := gin.New()
// 关闭尾斜杠重定向:避免 Next.js rewrites 代理时 /api/v1/classes → 301 → /api/v1/classes/ 循环
@@ -29,15 +35,17 @@ func main() {
// 全局中间件(按顺序注册)
// 1. panic 恢复(最外层,捕获后续所有中间件与 handler 的 panic
r.Use(middleware.Recovery())
// 2. 请求 ID 注入
// 2. OpenTelemetry 自动埋点HTTP 请求/响应 span
r.Use(otelgin.Middleware("api-gateway"))
// 3. 请求 ID 注入
r.Use(middleware.RequestID())
// 3. 跨域
// 4. 跨域
r.Use(middleware.CORS())
// 4. 安全响应头
// 5. 安全响应头
r.Use(middleware.SecurityHeaders())
// 5. 请求体大小限制
// 6. 请求体大小限制
r.Use(middleware.RequestBodyLimit(maxBodyBytes))
// 6. 限流(每 IP 100 rps突发 20
// 7. 限流(每 IP 100 rps突发 20
r.Use(middleware.RateLimit(100, 20))
// 健康检查路由(无需鉴权,在 Auth 之前)