feat(p6): production hardening with circuit breaker, backup, monitoring and chaos engineering
P6 生产硬化阶段交付物(46 文件):
## 1. API Gateway 中间件链(services/api-gateway/internal/middleware/)
- circuit-breaker.go: gobreaker v2 熔断器(5s 窗口/50% 错误率/30s OPEN→HALF_OPEN)
- ratelimit.go: 令牌桶限流(sync.Map + cleanup goroutine,默认 100rps/20 burst)
- cors.go: CORS 中间件(CORS_ORIGINS 环境变量)
- recovery.go: panic 恢复 + uuid request_id
- security.go: 安全头 + 请求体 10MB 限制
- requestid.go: 请求 ID 注入
- health/health.go: /healthz + /readyz 健康检查
- main.go: 重写注册全部中间件链(Recovery→RequestID→CORS→Security→BodyLimit→RateLimit→CircuitBreaker→Auth)
## 2. 基础设施硬化(infra/)
- backup/backup-mysql.sh: MySQL 全量备份(mysqldump+gzip,按服务独立)
- backup/restore-mysql.sh: 恢复脚本
- backup/backup-cron.sh: cron 调度入口(5 服务批量备份)
- alertmanager/alertmanager.yml: 告警路由(webhook + 邮件示例)
- prometheus/rules.yml: 8 条告警规则(服务可用性/性能/资源 3 组)
- grafana/dashboards/microservices-overview.json: 4 panel 仪表盘
- grafana/provisioning/: 数据源和仪表盘 provisioning
- k8s/namespace.yaml: 4 命名空间(edu-system/services/monitoring/ingress)
- k8s/api-gateway-deployment.yaml: Deployment + Service 骨架
- chaos/experiments.yaml: 3 个 Litmus 混沌实验(pod-kill/network-latency/disk-fill)
- docker-compose.monitoring.yml: 监控栈 profile
- security/secrets.example.env: 8 项密钥占位符
- security/waf-rules.conf: ModSecurity WAF 规则骨架
## 3. 业务服务健康检查 + 优雅停机(5 个 NestJS 服务)
- services/{iam,core-edu,content,msg,classes}/src/shared/health/: /healthz + /readyz
- services/{iam,core-edu,content,msg,classes}/src/shared/lifecycle/: OnModuleInit + OnApplicationShutdown
## 4. Python 服务健康检查
- services/{ai,data-ana}/src/health/health.py: FastAPI APIRouter
## 5. 运维文档
- docs/architecture/runbooks/p6-hardening.md: P6 总览 Runbook(9 章节)
- docs/architecture/runbooks/incident-response.md: 事件响应手册(5 章节)
- docs/architecture/004-p6-addendum.md: 004 架构补记 P6 章节
- docs/troubleshooting/known-issues-p6-addendum.md: 15 条 P6 场景→技术映射
## 验收信号
- RPO ≤ 15min(MySQL 备份 + binlog PITR)
- RTO ≤ 30min(K8s 滚动更新 + DNS 切换)
- P99 ≤ 500ms(熔断 + 限流 + 缓存)
- 熔断器错误率 > 50% 触发 OPEN
- 限流 100rps/20 burst
- 备份保留 7 天
- 混沌实验每月 1 次
This commit is contained in:
36
services/ai/src/health/health.py
Normal file
36
services/ai/src/health/health.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""健康检查端点(ai 服务)。
|
||||
|
||||
- GET /healthz:liveness,仅返回进程存活。
|
||||
- GET /readyz:readiness,简化版返回 ok + TODO,待补全 Elasticsearch
|
||||
连通性与 OpenAI 配置校验。
|
||||
|
||||
集成说明:在 FastAPI app 中挂载 router:
|
||||
|
||||
from health import router as health_router
|
||||
app.include_router(health_router)
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
SERVICE_NAME = "ai"
|
||||
|
||||
|
||||
@router.get("/healthz")
|
||||
async def healthz() -> dict:
|
||||
return {"status": "ok", "service": SERVICE_NAME}
|
||||
|
||||
|
||||
@router.get("/readyz")
|
||||
async def readyz() -> dict:
|
||||
# TODO: 校验关键依赖
|
||||
# 1. Elasticsearch 连通性:es_client.ping()
|
||||
# 2. OpenAI 配置:API key 是否注入、超时是否合理
|
||||
# 依赖客户端就绪后再补全检查逻辑,失败时返回 503。
|
||||
return {
|
||||
"status": "ok",
|
||||
"service": SERVICE_NAME,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
@@ -6,6 +6,7 @@ require (
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/sony/gobreaker/v2 v2.1.0
|
||||
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.52.0
|
||||
go.opentelemetry.io/otel v1.27.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.27.0
|
||||
|
||||
23
services/api-gateway/internal/health/health.go
Normal file
23
services/api-gateway/internal/health/health.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Healthz 存活探针(liveness)。
|
||||
// GET /healthz:返回 200 {"status":"ok"} 表示进程存活。
|
||||
func Healthz(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
// Readyz 就绪探针(readiness)。
|
||||
// GET /readyz:检查下游服务可达性。
|
||||
// TODO: P7 接入服务发现后,检查 classes / iam / teacher-bff 等下游服务健康状态,
|
||||
// 任一不可达则返回 503,当前简化为直接返回 200。
|
||||
func Readyz(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
65
services/api-gateway/internal/middleware/circuit-breaker.go
Normal file
65
services/api-gateway/internal/middleware/circuit-breaker.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sony/gobreaker/v2"
|
||||
)
|
||||
|
||||
// CircuitBreaker 返回针对指定服务的熔断中间件。
|
||||
//
|
||||
// 基于 gobreaker v2 实现:
|
||||
// - Interval=5s:CLOSED 状态下的统计窗口
|
||||
// - ReadyToTrip:错误率 > 50% 触发 OPEN
|
||||
// - Timeout=30s:OPEN 持续 30 秒后转 HALF_OPEN
|
||||
// - MaxRequests=1:HALF_OPEN 仅允许 1 个探测请求
|
||||
//
|
||||
// 仅当下游返回 5xx 视为失败;4xx 与 2xx 不计入熔断。
|
||||
// 熔断打开或半开探测名额已满时返回 503 + JSON {"error":"circuit_open","retry_after":30}。
|
||||
func CircuitBreaker(serviceName string) gin.HandlerFunc {
|
||||
cb := gobreaker.NewCircuitBreaker[struct{}](gobreaker.Settings{
|
||||
Name: serviceName,
|
||||
MaxRequests: 1,
|
||||
Interval: 5 * time.Second,
|
||||
Timeout: 30 * time.Second,
|
||||
ReadyToTrip: func(counts gobreaker.Counts) bool {
|
||||
// 请求数为 0 时不触发,避免除零
|
||||
if counts.Requests == 0 {
|
||||
return false
|
||||
}
|
||||
// 错误率 > 50%
|
||||
return counts.TotalFailures*2 > counts.Requests
|
||||
},
|
||||
OnStateChange: func(name string, from, to gobreaker.State) {
|
||||
log.Printf("[circuit-breaker] service=%s state: %s -> %s", name, from, to)
|
||||
},
|
||||
})
|
||||
|
||||
return func(c *gin.Context) {
|
||||
_, err := cb.Execute(func() (struct{}, error) {
|
||||
c.Next()
|
||||
// 下游 5xx 视为熔断失败
|
||||
if c.Writer.Status() >= 500 {
|
||||
return struct{}{}, errors.New("downstream_error")
|
||||
}
|
||||
return struct{}{}, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
// 熔断打开或半开探测名额已满:返回 503
|
||||
if errors.Is(err, gobreaker.ErrOpenState) || errors.Is(err, gobreaker.ErrTooManyRequests) {
|
||||
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
|
||||
"error": "circuit_open",
|
||||
"retry_after": 30,
|
||||
})
|
||||
return
|
||||
}
|
||||
// 其他情况(下游已写 5xx 响应):响应已写入,不覆盖
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
69
services/api-gateway/internal/middleware/cors.go
Normal file
69
services/api-gateway/internal/middleware/cors.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// corsMaxAge 预检缓存时长:12 小时
|
||||
const corsMaxAge = 12 * 60 * 60
|
||||
|
||||
// CORS 返回跨域资源共享中间件。
|
||||
// 允许来源从环境变量 CORS_ORIGINS 读取(逗号分隔,默认 *)。
|
||||
// 允许方法:GET POST PUT DELETE OPTIONS PATCH
|
||||
// 允许头:Authorization Content-Type X-Request-Id X-Trace-Id
|
||||
// 暴露头:X-Request-Id X-Trace-Id
|
||||
func CORS() gin.HandlerFunc {
|
||||
allowed := parseCORSOrigins(os.Getenv("CORS_ORIGINS"))
|
||||
|
||||
return func(c *gin.Context) {
|
||||
origin := c.GetHeader("Origin")
|
||||
allowOrigin := ""
|
||||
|
||||
if len(allowed) == 0 {
|
||||
// 未配置则默认允许所有来源
|
||||
allowOrigin = "*"
|
||||
} else if allowed[origin] {
|
||||
allowOrigin = origin
|
||||
}
|
||||
|
||||
if allowOrigin != "" {
|
||||
h := c.Writer.Header()
|
||||
h.Set("Access-Control-Allow-Origin", allowOrigin)
|
||||
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
|
||||
h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Request-Id, X-Trace-Id")
|
||||
h.Set("Access-Control-Expose-Headers", "X-Request-Id, X-Trace-Id")
|
||||
h.Set("Access-Control-Max-Age", strconv.Itoa(corsMaxAge))
|
||||
// 非通配来源需标注 Vary,便于缓存正确区分
|
||||
if allowOrigin != "*" {
|
||||
h.Add("Vary", "Origin")
|
||||
}
|
||||
}
|
||||
|
||||
// 预检请求直接返回 204
|
||||
if c.Request.Method == http.MethodOptions {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// parseCORSOrigins 解析逗号分隔的来源列表为集合,空字符串返回空 map(表示通配 *)
|
||||
func parseCORSOrigins(raw string) map[string]bool {
|
||||
allowed := map[string]bool{}
|
||||
if raw == "" {
|
||||
return allowed
|
||||
}
|
||||
for _, o := range strings.Split(raw, ",") {
|
||||
o = strings.TrimSpace(o)
|
||||
if o != "" {
|
||||
allowed[o] = true
|
||||
}
|
||||
}
|
||||
return allowed
|
||||
}
|
||||
94
services/api-gateway/internal/middleware/ratelimit.go
Normal file
94
services/api-gateway/internal/middleware/ratelimit.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// bucket 是单个客户端的令牌桶
|
||||
type bucket struct {
|
||||
mu sync.Mutex
|
||||
tokens float64
|
||||
lastTime time.Time
|
||||
}
|
||||
|
||||
// rateLimiter 持有所有客户端 IP 的令牌桶
|
||||
type rateLimiter struct {
|
||||
rps float64
|
||||
burst int
|
||||
buckets sync.Map // map[string]*bucket
|
||||
}
|
||||
|
||||
// RateLimit 返回基于令牌桶的限流中间件(内存版,不依赖 Redis)。
|
||||
// 每个客户端 IP 独立桶,按 rps(每秒令牌数)补充,最大容量为 burst。
|
||||
// 超限返回 429 + JSON {"error":"rate_limited","retry_after":60}。
|
||||
// 内部启动 cleanup goroutine,每 5 分钟清理 10 分钟未访问的桶。
|
||||
func RateLimit(rps float64, burst int) gin.HandlerFunc {
|
||||
rl := &rateLimiter{rps: rps, burst: burst}
|
||||
// 启动清理 goroutine
|
||||
go rl.cleanup(5*time.Minute, 10*time.Minute)
|
||||
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
b := rl.getBucket(ip)
|
||||
|
||||
b.mu.Lock()
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(b.lastTime).Seconds()
|
||||
b.lastTime = now
|
||||
// 按经过时间补充令牌
|
||||
b.tokens += elapsed * rl.rps
|
||||
if b.tokens > float64(rl.burst) {
|
||||
b.tokens = float64(rl.burst)
|
||||
}
|
||||
// 令牌不足:拒绝
|
||||
if b.tokens < 1 {
|
||||
b.mu.Unlock()
|
||||
c.Header("Retry-After", "60")
|
||||
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
||||
"error": "rate_limited",
|
||||
"retry_after": 60,
|
||||
})
|
||||
return
|
||||
}
|
||||
b.tokens--
|
||||
b.mu.Unlock()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// getBucket 获取指定 IP 的令牌桶,不存在则新建(初始满桶)
|
||||
func (rl *rateLimiter) getBucket(ip string) *bucket {
|
||||
if v, ok := rl.buckets.Load(ip); ok {
|
||||
return v.(*bucket)
|
||||
}
|
||||
b := &bucket{
|
||||
tokens: float64(rl.burst),
|
||||
lastTime: time.Now(),
|
||||
}
|
||||
actual, _ := rl.buckets.LoadOrStore(ip, b)
|
||||
return actual.(*bucket)
|
||||
}
|
||||
|
||||
// cleanup 周期性清理长时间未访问的桶,避免内存无限增长
|
||||
func (rl *rateLimiter) cleanup(interval, maxIdle time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
now := time.Now()
|
||||
rl.buckets.Range(func(key, value any) bool {
|
||||
b := value.(*bucket)
|
||||
b.mu.Lock()
|
||||
idle := now.Sub(b.lastTime)
|
||||
b.mu.Unlock()
|
||||
if idle > maxIdle {
|
||||
rl.buckets.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
32
services/api-gateway/internal/middleware/recovery.go
Normal file
32
services/api-gateway/internal/middleware/recovery.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Recovery 捕获 panic 并返回 500,记录堆栈日志。
|
||||
// 返回 JSON {"error":"internal_error","request_id":"<uuid>"}。
|
||||
// request_id 使用 uuid.New() 生成(Recovery 在 RequestID 之前注册,
|
||||
// panic 发生时上下文中可能尚无 request_id,故独立生成)。
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
stack := debug.Stack()
|
||||
requestID := uuid.New().String()
|
||||
log.Printf("[recovery] panic recovered, request_id=%s: %v\n%s", requestID, r, stack)
|
||||
// 若已写入部分响应,AbortWithStatusJSON 仍会设置状态并尝试写 JSON
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "internal_error",
|
||||
"request_id": requestID,
|
||||
})
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
26
services/api-gateway/internal/middleware/requestid.go
Normal file
26
services/api-gateway/internal/middleware/requestid.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// requestIDHeader 请求 ID 响应头名称
|
||||
const requestIDHeader = "X-Request-Id"
|
||||
|
||||
// requestIDContextKey context 中存储请求 ID 的键
|
||||
const requestIDContextKey = "request_id"
|
||||
|
||||
// RequestID 注入请求 ID 中间件。
|
||||
// 从 X-Request-Id 头读取,无则生成 uuid,写入 context 与响应头。
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rid := c.GetHeader(requestIDHeader)
|
||||
if rid == "" {
|
||||
rid = uuid.New().String()
|
||||
}
|
||||
c.Set(requestIDContextKey, rid)
|
||||
c.Writer.Header().Set(requestIDHeader, rid)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
39
services/api-gateway/internal/middleware/security.go
Normal file
39
services/api-gateway/internal/middleware/security.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SecurityHeaders 设置安全响应头中间件。
|
||||
// 设置:X-Content-Type-Options: nosniff
|
||||
//
|
||||
// X-Frame-Options: DENY
|
||||
// Referrer-Policy: strict-origin-when-cross-origin
|
||||
// Strict-Transport-Security: max-age=31536000; includeSubDomains
|
||||
// Content-Security-Policy: default-src 'self'
|
||||
// 移除 Server 头
|
||||
func SecurityHeaders() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
h := c.Writer.Header()
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
h.Set("Content-Security-Policy", "default-src 'self'")
|
||||
h.Del("Server")
|
||||
c.Next()
|
||||
// 响应处理结束后再次移除 Server 头,防止处理过程中被写入
|
||||
c.Writer.Header().Del("Server")
|
||||
}
|
||||
}
|
||||
|
||||
// RequestBodyLimit 限制请求体大小中间件。
|
||||
// 通过 http.MaxBytesReader 包装 Body,超限读取时返回 413。
|
||||
func RequestBodyLimit(maxBytes int64) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -10,13 +10,66 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/edu-cloud/api-gateway/internal/config"
|
||||
"github.com/edu-cloud/api-gateway/internal/routing"
|
||||
"github.com/edu-cloud/api-gateway/internal/health"
|
||||
"github.com/edu-cloud/api-gateway/internal/middleware"
|
||||
"github.com/edu-cloud/api-gateway/internal/proxy"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// maxBodyBytes 请求体大小上限:10MB
|
||||
const maxBodyBytes int64 = 10 * 1024 * 1024
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
r := gin.New()
|
||||
|
||||
r := routing.Setup(cfg)
|
||||
// 全局中间件(按顺序注册)
|
||||
// 1. panic 恢复(最外层,捕获后续所有中间件与 handler 的 panic)
|
||||
r.Use(middleware.Recovery())
|
||||
// 2. 请求 ID 注入
|
||||
r.Use(middleware.RequestID())
|
||||
// 3. 跨域
|
||||
r.Use(middleware.CORS())
|
||||
// 4. 安全响应头
|
||||
r.Use(middleware.SecurityHeaders())
|
||||
// 5. 请求体大小限制
|
||||
r.Use(middleware.RequestBodyLimit(maxBodyBytes))
|
||||
// 6. 限流(每 IP 100 rps,突发 20)
|
||||
r.Use(middleware.RateLimit(100, 20))
|
||||
|
||||
// 健康检查路由(无需鉴权,在 Auth 之前)
|
||||
r.GET("/healthz", health.Healthz)
|
||||
r.GET("/readyz", health.Readyz)
|
||||
|
||||
// API v1 组:熔断 + 鉴权 + 反向代理
|
||||
api := r.Group("/api/v1")
|
||||
// 7. 熔断(仅作用于代理路由,下游 5xx 触发)
|
||||
api.Use(middleware.CircuitBreaker("downstream"))
|
||||
// 8. JWT 鉴权
|
||||
api.Use(middleware.AuthMiddleware(cfg))
|
||||
{
|
||||
// classes 服务路由
|
||||
classesProxy, err := proxy.NewProxy(cfg.ClassesServiceURL)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to create classes proxy: %v", err)
|
||||
}
|
||||
api.Any("/classes/*path", proxy.ProxyHandler(classesProxy))
|
||||
|
||||
// IAM 服务路由(身份与访问管理)
|
||||
iamProxy, err := proxy.NewProxy(cfg.IamServiceURL)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to create iam proxy: %v", err)
|
||||
}
|
||||
api.Any("/iam/*path", proxy.ProxyHandler(iamProxy))
|
||||
|
||||
// Teacher BFF 路由(教师聚合层)
|
||||
bffProxy, err := proxy.NewProxy(cfg.TeacherBffURL)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to create teacher-bff proxy: %v", err)
|
||||
}
|
||||
api.Any("/teacher/*path", proxy.ProxyHandler(bffProxy))
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + cfg.Port,
|
||||
@@ -29,7 +82,7 @@ func main() {
|
||||
go func() {
|
||||
log.Printf("API Gateway listening on :%s", cfg.Port)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("listen: %s\n", err)
|
||||
log.Fatalf("listen: %s", err)
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
49
services/classes/src/shared/health/health.controller.ts
Normal file
49
services/classes/src/shared/health/health.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
const SERVICE_NAME = 'classes';
|
||||
|
||||
/**
|
||||
* 健康检查端点。
|
||||
*
|
||||
* - GET /healthz:liveness,仅返回进程存活,不检查依赖。
|
||||
* - GET /readyz:readiness,检查 DB 连接,失败返回 503。
|
||||
*
|
||||
* 不需要鉴权,必须在路由白名单中放行。本控制器内容在 iam / core-edu /
|
||||
* content / msg / classes 五个 NestJS 服务中一致,仅 SERVICE_NAME 不同。
|
||||
*/
|
||||
@Controller()
|
||||
export class HealthController {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
@Get('healthz')
|
||||
liveness(): { status: string; service: string; timestamp: string } {
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('readyz')
|
||||
async readiness(): Promise<{ status: string; service: string; timestamp: string }> {
|
||||
try {
|
||||
await this.dataSource.query('SELECT 1');
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
{
|
||||
status: 'error',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : 'database unreachable',
|
||||
},
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
services/classes/src/shared/health/health.module.ts
Normal file
23
services/classes/src/shared/health/health.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
/**
|
||||
* 健康检查模块。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
*
|
||||
* 在 `app.module.ts` 的 imports 数组中加入 `HealthModule`:
|
||||
*
|
||||
* ```ts
|
||||
* import { HealthModule } from './shared/health/health.module';
|
||||
*
|
||||
* @Module({ imports: [ ..., HealthModule ], ... })
|
||||
* export class AppModule {}
|
||||
* ```
|
||||
*
|
||||
* DataSource 由 `TypeOrmModule.forRoot(...)` 提供,本模块无需额外 provider。
|
||||
*/
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
63
services/classes/src/shared/lifecycle/lifecycle.service.ts
Normal file
63
services/classes/src/shared/lifecycle/lifecycle.service.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Inject, Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { Redis } from 'ioredis';
|
||||
import type { Producer } from 'kafkajs';
|
||||
|
||||
const SERVICE_NAME = 'classes';
|
||||
|
||||
/**
|
||||
* 优雅停机服务。
|
||||
*
|
||||
* 信号处理由 NestJS 在 `app.listen` 之前调用 `app.enableShutdownHooks()`
|
||||
* 触发(SIGTERM / SIGINT),NestJS 会依次调用 OnApplicationShutdown 钩子。
|
||||
* K8s 配置 `terminationGracePeriodSeconds=60` 给予足够时间清理。
|
||||
*
|
||||
* 关闭顺序:Kafka producer → Redis → DataSource。
|
||||
* 先停外部消息生产避免新事件,再关缓存,最后关 DB。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
* - 在 `app.module.ts` 的 providers 中加入 `LifecycleService`。
|
||||
* - 在 `main.ts` 中 `app.listen` 之前调用 `app.enableShutdownHooks()`。
|
||||
*
|
||||
* 依赖注入 token 约定(需与各服务 provider 注册一致):
|
||||
* - DataSource:由 `TypeOrmModule.forRoot()` 提供。
|
||||
* - 'REDIS_CLIENT':需在对应模块注册 `{ provide: 'REDIS_CLIENT', useFactory: ... }`。
|
||||
* - 'KAFKA_PRODUCER':需在对应模块注册 `{ provide: 'KAFKA_PRODUCER', useFactory: ... }`。
|
||||
*/
|
||||
@Injectable()
|
||||
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(LifecycleService.name);
|
||||
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
@Inject('REDIS_CLIENT') private readonly redis: Redis,
|
||||
@Inject('KAFKA_PRODUCER') private readonly kafkaProducer: Producer,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
this.logger.log(`service ${SERVICE_NAME} module initialized`);
|
||||
}
|
||||
|
||||
async onApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.logger.log(
|
||||
`service ${SERVICE_NAME} shutting down (signal=${signal ?? 'unknown'})`,
|
||||
);
|
||||
|
||||
await this.safeDisconnect('kafka producer', () => this.kafkaProducer.disconnect());
|
||||
await this.safeDisconnect('redis', () => this.redis.quit());
|
||||
await this.safeDisconnect('datasource', () => this.dataSource.destroy());
|
||||
|
||||
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
|
||||
}
|
||||
|
||||
private async safeDisconnect(name: string, fn: () => Promise<unknown>): Promise<void> {
|
||||
try {
|
||||
await fn();
|
||||
this.logger.log(`${name} closed`);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`${name} close failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
49
services/content/src/shared/health/health.controller.ts
Normal file
49
services/content/src/shared/health/health.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
const SERVICE_NAME = 'content';
|
||||
|
||||
/**
|
||||
* 健康检查端点。
|
||||
*
|
||||
* - GET /healthz:liveness,仅返回进程存活,不检查依赖。
|
||||
* - GET /readyz:readiness,检查 DB 连接,失败返回 503。
|
||||
*
|
||||
* 不需要鉴权,必须在路由白名单中放行。本控制器内容在 iam / core-edu /
|
||||
* content / msg / classes 五个 NestJS 服务中一致,仅 SERVICE_NAME 不同。
|
||||
*/
|
||||
@Controller()
|
||||
export class HealthController {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
@Get('healthz')
|
||||
liveness(): { status: string; service: string; timestamp: string } {
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('readyz')
|
||||
async readiness(): Promise<{ status: string; service: string; timestamp: string }> {
|
||||
try {
|
||||
await this.dataSource.query('SELECT 1');
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
{
|
||||
status: 'error',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : 'database unreachable',
|
||||
},
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
services/content/src/shared/health/health.module.ts
Normal file
23
services/content/src/shared/health/health.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
/**
|
||||
* 健康检查模块。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
*
|
||||
* 在 `app.module.ts` 的 imports 数组中加入 `HealthModule`:
|
||||
*
|
||||
* ```ts
|
||||
* import { HealthModule } from './shared/health/health.module';
|
||||
*
|
||||
* @Module({ imports: [ ..., HealthModule ], ... })
|
||||
* export class AppModule {}
|
||||
* ```
|
||||
*
|
||||
* DataSource 由 `TypeOrmModule.forRoot(...)` 提供,本模块无需额外 provider。
|
||||
*/
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
64
services/content/src/shared/lifecycle/lifecycle.service.ts
Normal file
64
services/content/src/shared/lifecycle/lifecycle.service.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { Inject, Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { Redis } from 'ioredis';
|
||||
import type { Producer } from 'kafkajs';
|
||||
|
||||
const SERVICE_NAME = 'content';
|
||||
|
||||
/**
|
||||
* 优雅停机服务。
|
||||
*
|
||||
* 信号处理由 NestJS 在 `app.listen` 之前调用 `app.enableShutdownHooks()`
|
||||
* 触发(SIGTERM / SIGINT),NestJS 会依次调用 OnApplicationShutdown 钩子。
|
||||
* K8s 配置 `terminationGracePeriodSeconds=60` 给予足够时间清理。
|
||||
*
|
||||
* 关闭顺序:Kafka producer → Redis → DataSource。
|
||||
* 先停外部消息生产避免新事件,再关缓存,最后关 DB。
|
||||
* 注:content 服务额外使用 S3/MinIO 客户端,其连接由 SDK 内部管理,无需显式关闭。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
* - 在 `app.module.ts` 的 providers 中加入 `LifecycleService`。
|
||||
* - 在 `main.ts` 中 `app.listen` 之前调用 `app.enableShutdownHooks()`。
|
||||
*
|
||||
* 依赖注入 token 约定(需与各服务 provider 注册一致):
|
||||
* - DataSource:由 `TypeOrmModule.forRoot()` 提供。
|
||||
* - 'REDIS_CLIENT':需在对应模块注册 `{ provide: 'REDIS_CLIENT', useFactory: ... }`。
|
||||
* - 'KAFKA_PRODUCER':需在对应模块注册 `{ provide: 'KAFKA_PRODUCER', useFactory: ... }`。
|
||||
*/
|
||||
@Injectable()
|
||||
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(LifecycleService.name);
|
||||
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
@Inject('REDIS_CLIENT') private readonly redis: Redis,
|
||||
@Inject('KAFKA_PRODUCER') private readonly kafkaProducer: Producer,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
this.logger.log(`service ${SERVICE_NAME} module initialized`);
|
||||
}
|
||||
|
||||
async onApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.logger.log(
|
||||
`service ${SERVICE_NAME} shutting down (signal=${signal ?? 'unknown'})`,
|
||||
);
|
||||
|
||||
await this.safeDisconnect('kafka producer', () => this.kafkaProducer.disconnect());
|
||||
await this.safeDisconnect('redis', () => this.redis.quit());
|
||||
await this.safeDisconnect('datasource', () => this.dataSource.destroy());
|
||||
|
||||
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
|
||||
}
|
||||
|
||||
private async safeDisconnect(name: string, fn: () => Promise<unknown>): Promise<void> {
|
||||
try {
|
||||
await fn();
|
||||
this.logger.log(`${name} closed`);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`${name} close failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
49
services/core-edu/src/shared/health/health.controller.ts
Normal file
49
services/core-edu/src/shared/health/health.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
const SERVICE_NAME = 'core-edu';
|
||||
|
||||
/**
|
||||
* 健康检查端点。
|
||||
*
|
||||
* - GET /healthz:liveness,仅返回进程存活,不检查依赖。
|
||||
* - GET /readyz:readiness,检查 DB 连接,失败返回 503。
|
||||
*
|
||||
* 不需要鉴权,必须在路由白名单中放行。本控制器内容在 iam / core-edu /
|
||||
* content / msg / classes 五个 NestJS 服务中一致,仅 SERVICE_NAME 不同。
|
||||
*/
|
||||
@Controller()
|
||||
export class HealthController {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
@Get('healthz')
|
||||
liveness(): { status: string; service: string; timestamp: string } {
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('readyz')
|
||||
async readiness(): Promise<{ status: string; service: string; timestamp: string }> {
|
||||
try {
|
||||
await this.dataSource.query('SELECT 1');
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
{
|
||||
status: 'error',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : 'database unreachable',
|
||||
},
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
services/core-edu/src/shared/health/health.module.ts
Normal file
23
services/core-edu/src/shared/health/health.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
/**
|
||||
* 健康检查模块。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
*
|
||||
* 在 `app.module.ts` 的 imports 数组中加入 `HealthModule`:
|
||||
*
|
||||
* ```ts
|
||||
* import { HealthModule } from './shared/health/health.module';
|
||||
*
|
||||
* @Module({ imports: [ ..., HealthModule ], ... })
|
||||
* export class AppModule {}
|
||||
* ```
|
||||
*
|
||||
* DataSource 由 `TypeOrmModule.forRoot(...)` 提供,本模块无需额外 provider。
|
||||
*/
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
63
services/core-edu/src/shared/lifecycle/lifecycle.service.ts
Normal file
63
services/core-edu/src/shared/lifecycle/lifecycle.service.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Inject, Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { Redis } from 'ioredis';
|
||||
import type { Producer } from 'kafkajs';
|
||||
|
||||
const SERVICE_NAME = 'core-edu';
|
||||
|
||||
/**
|
||||
* 优雅停机服务。
|
||||
*
|
||||
* 信号处理由 NestJS 在 `app.listen` 之前调用 `app.enableShutdownHooks()`
|
||||
* 触发(SIGTERM / SIGINT),NestJS 会依次调用 OnApplicationShutdown 钩子。
|
||||
* K8s 配置 `terminationGracePeriodSeconds=60` 给予足够时间清理。
|
||||
*
|
||||
* 关闭顺序:Kafka producer → Redis → DataSource。
|
||||
* 先停外部消息生产避免新事件,再关缓存,最后关 DB。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
* - 在 `app.module.ts` 的 providers 中加入 `LifecycleService`。
|
||||
* - 在 `main.ts` 中 `app.listen` 之前调用 `app.enableShutdownHooks()`。
|
||||
*
|
||||
* 依赖注入 token 约定(需与各服务 provider 注册一致):
|
||||
* - DataSource:由 `TypeOrmModule.forRoot()` 提供。
|
||||
* - 'REDIS_CLIENT':需在对应模块注册 `{ provide: 'REDIS_CLIENT', useFactory: ... }`。
|
||||
* - 'KAFKA_PRODUCER':需在对应模块注册 `{ provide: 'KAFKA_PRODUCER', useFactory: ... }`。
|
||||
*/
|
||||
@Injectable()
|
||||
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(LifecycleService.name);
|
||||
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
@Inject('REDIS_CLIENT') private readonly redis: Redis,
|
||||
@Inject('KAFKA_PRODUCER') private readonly kafkaProducer: Producer,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
this.logger.log(`service ${SERVICE_NAME} module initialized`);
|
||||
}
|
||||
|
||||
async onApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.logger.log(
|
||||
`service ${SERVICE_NAME} shutting down (signal=${signal ?? 'unknown'})`,
|
||||
);
|
||||
|
||||
await this.safeDisconnect('kafka producer', () => this.kafkaProducer.disconnect());
|
||||
await this.safeDisconnect('redis', () => this.redis.quit());
|
||||
await this.safeDisconnect('datasource', () => this.dataSource.destroy());
|
||||
|
||||
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
|
||||
}
|
||||
|
||||
private async safeDisconnect(name: string, fn: () => Promise<unknown>): Promise<void> {
|
||||
try {
|
||||
await fn();
|
||||
this.logger.log(`${name} closed`);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`${name} close failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
34
services/data-ana/src/health/health.py
Normal file
34
services/data-ana/src/health/health.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""健康检查端点(data-ana 服务)。
|
||||
|
||||
- GET /healthz:liveness,仅返回进程存活。
|
||||
- GET /readyz:readiness,简化版返回 ok + TODO,待补全 ClickHouse 连通性校验。
|
||||
|
||||
集成说明:在 FastAPI app 中挂载 router:
|
||||
|
||||
from health import router as health_router
|
||||
app.include_router(health_router)
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
SERVICE_NAME = "data-ana"
|
||||
|
||||
|
||||
@router.get("/healthz")
|
||||
async def healthz() -> dict:
|
||||
return {"status": "ok", "service": SERVICE_NAME}
|
||||
|
||||
|
||||
@router.get("/readyz")
|
||||
async def readyz() -> dict:
|
||||
# TODO: 校验关键依赖
|
||||
# 1. ClickHouse 连通性:clickhouse_client.execute("SELECT 1")
|
||||
# 依赖客户端就绪后再补全检查逻辑,失败时返回 503。
|
||||
return {
|
||||
"status": "ok",
|
||||
"service": SERVICE_NAME,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
49
services/iam/src/shared/health/health.controller.ts
Normal file
49
services/iam/src/shared/health/health.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
const SERVICE_NAME = 'iam';
|
||||
|
||||
/**
|
||||
* 健康检查端点。
|
||||
*
|
||||
* - GET /healthz:liveness,仅返回进程存活,不检查依赖。
|
||||
* - GET /readyz:readiness,检查 DB 连接,失败返回 503。
|
||||
*
|
||||
* 不需要鉴权,必须在路由白名单中放行。本控制器内容在 iam / core-edu /
|
||||
* content / msg / classes 五个 NestJS 服务中一致,仅 SERVICE_NAME 不同。
|
||||
*/
|
||||
@Controller()
|
||||
export class HealthController {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
@Get('healthz')
|
||||
liveness(): { status: string; service: string; timestamp: string } {
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('readyz')
|
||||
async readiness(): Promise<{ status: string; service: string; timestamp: string }> {
|
||||
try {
|
||||
await this.dataSource.query('SELECT 1');
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
{
|
||||
status: 'error',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : 'database unreachable',
|
||||
},
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
services/iam/src/shared/health/health.module.ts
Normal file
23
services/iam/src/shared/health/health.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
/**
|
||||
* 健康检查模块。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
*
|
||||
* 在 `app.module.ts` 的 imports 数组中加入 `HealthModule`:
|
||||
*
|
||||
* ```ts
|
||||
* import { HealthModule } from './shared/health/health.module';
|
||||
*
|
||||
* @Module({ imports: [ ..., HealthModule ], ... })
|
||||
* export class AppModule {}
|
||||
* ```
|
||||
*
|
||||
* DataSource 由 `TypeOrmModule.forRoot(...)` 提供,本模块无需额外 provider。
|
||||
*/
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
63
services/iam/src/shared/lifecycle/lifecycle.service.ts
Normal file
63
services/iam/src/shared/lifecycle/lifecycle.service.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Inject, Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { Redis } from 'ioredis';
|
||||
import type { Producer } from 'kafkajs';
|
||||
|
||||
const SERVICE_NAME = 'iam';
|
||||
|
||||
/**
|
||||
* 优雅停机服务。
|
||||
*
|
||||
* 信号处理由 NestJS 在 `app.listen` 之前调用 `app.enableShutdownHooks()`
|
||||
* 触发(SIGTERM / SIGINT),NestJS 会依次调用 OnApplicationShutdown 钩子。
|
||||
* K8s 配置 `terminationGracePeriodSeconds=60` 给予足够时间清理。
|
||||
*
|
||||
* 关闭顺序:Kafka producer → Redis → DataSource。
|
||||
* 先停外部消息生产避免新事件,再关缓存,最后关 DB。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
* - 在 `app.module.ts` 的 providers 中加入 `LifecycleService`。
|
||||
* - 在 `main.ts` 中 `app.listen` 之前调用 `app.enableShutdownHooks()`。
|
||||
*
|
||||
* 依赖注入 token 约定(需与各服务 provider 注册一致):
|
||||
* - DataSource:由 `TypeOrmModule.forRoot()` 提供。
|
||||
* - 'REDIS_CLIENT':需在对应模块注册 `{ provide: 'REDIS_CLIENT', useFactory: ... }`。
|
||||
* - 'KAFKA_PRODUCER':需在对应模块注册 `{ provide: 'KAFKA_PRODUCER', useFactory: ... }`。
|
||||
*/
|
||||
@Injectable()
|
||||
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(LifecycleService.name);
|
||||
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
@Inject('REDIS_CLIENT') private readonly redis: Redis,
|
||||
@Inject('KAFKA_PRODUCER') private readonly kafkaProducer: Producer,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
this.logger.log(`service ${SERVICE_NAME} module initialized`);
|
||||
}
|
||||
|
||||
async onApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.logger.log(
|
||||
`service ${SERVICE_NAME} shutting down (signal=${signal ?? 'unknown'})`,
|
||||
);
|
||||
|
||||
await this.safeDisconnect('kafka producer', () => this.kafkaProducer.disconnect());
|
||||
await this.safeDisconnect('redis', () => this.redis.quit());
|
||||
await this.safeDisconnect('datasource', () => this.dataSource.destroy());
|
||||
|
||||
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
|
||||
}
|
||||
|
||||
private async safeDisconnect(name: string, fn: () => Promise<unknown>): Promise<void> {
|
||||
try {
|
||||
await fn();
|
||||
this.logger.log(`${name} closed`);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`${name} close failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
49
services/msg/src/shared/health/health.controller.ts
Normal file
49
services/msg/src/shared/health/health.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
const SERVICE_NAME = 'msg';
|
||||
|
||||
/**
|
||||
* 健康检查端点。
|
||||
*
|
||||
* - GET /healthz:liveness,仅返回进程存活,不检查依赖。
|
||||
* - GET /readyz:readiness,检查 DB 连接,失败返回 503。
|
||||
*
|
||||
* 不需要鉴权,必须在路由白名单中放行。本控制器内容在 iam / core-edu /
|
||||
* content / msg / classes 五个 NestJS 服务中一致,仅 SERVICE_NAME 不同。
|
||||
*/
|
||||
@Controller()
|
||||
export class HealthController {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
@Get('healthz')
|
||||
liveness(): { status: string; service: string; timestamp: string } {
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Get('readyz')
|
||||
async readiness(): Promise<{ status: string; service: string; timestamp: string }> {
|
||||
try {
|
||||
await this.dataSource.query('SELECT 1');
|
||||
return {
|
||||
status: 'ok',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
{
|
||||
status: 'error',
|
||||
service: SERVICE_NAME,
|
||||
timestamp: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : 'database unreachable',
|
||||
},
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
services/msg/src/shared/health/health.module.ts
Normal file
23
services/msg/src/shared/health/health.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
/**
|
||||
* 健康检查模块。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
*
|
||||
* 在 `app.module.ts` 的 imports 数组中加入 `HealthModule`:
|
||||
*
|
||||
* ```ts
|
||||
* import { HealthModule } from './shared/health/health.module';
|
||||
*
|
||||
* @Module({ imports: [ ..., HealthModule ], ... })
|
||||
* export class AppModule {}
|
||||
* ```
|
||||
*
|
||||
* DataSource 由 `TypeOrmModule.forRoot(...)` 提供,本模块无需额外 provider。
|
||||
*/
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
63
services/msg/src/shared/lifecycle/lifecycle.service.ts
Normal file
63
services/msg/src/shared/lifecycle/lifecycle.service.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Inject, Injectable, Logger, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { Redis } from 'ioredis';
|
||||
import type { Producer } from 'kafkajs';
|
||||
|
||||
const SERVICE_NAME = 'msg';
|
||||
|
||||
/**
|
||||
* 优雅停机服务。
|
||||
*
|
||||
* 信号处理由 NestJS 在 `app.listen` 之前调用 `app.enableShutdownHooks()`
|
||||
* 触发(SIGTERM / SIGINT),NestJS 会依次调用 OnApplicationShutdown 钩子。
|
||||
* K8s 配置 `terminationGracePeriodSeconds=60` 给予足够时间清理。
|
||||
*
|
||||
* 关闭顺序:Kafka producer → Redis → DataSource。
|
||||
* 先停外部消息生产避免新事件,再关缓存,最后关 DB。
|
||||
*
|
||||
* 集成说明(不修改 app.module.ts,仅在 README 注释说明):
|
||||
* - 在 `app.module.ts` 的 providers 中加入 `LifecycleService`。
|
||||
* - 在 `main.ts` 中 `app.listen` 之前调用 `app.enableShutdownHooks()`。
|
||||
*
|
||||
* 依赖注入 token 约定(需与各服务 provider 注册一致):
|
||||
* - DataSource:由 `TypeOrmModule.forRoot()` 提供。
|
||||
* - 'REDIS_CLIENT':需在对应模块注册 `{ provide: 'REDIS_CLIENT', useFactory: ... }`。
|
||||
* - 'KAFKA_PRODUCER':需在对应模块注册 `{ provide: 'KAFKA_PRODUCER', useFactory: ... }`。
|
||||
*/
|
||||
@Injectable()
|
||||
export class LifecycleService implements OnModuleInit, OnApplicationShutdown {
|
||||
private readonly logger = new Logger(LifecycleService.name);
|
||||
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
@Inject('REDIS_CLIENT') private readonly redis: Redis,
|
||||
@Inject('KAFKA_PRODUCER') private readonly kafkaProducer: Producer,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
this.logger.log(`service ${SERVICE_NAME} module initialized`);
|
||||
}
|
||||
|
||||
async onApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.logger.log(
|
||||
`service ${SERVICE_NAME} shutting down (signal=${signal ?? 'unknown'})`,
|
||||
);
|
||||
|
||||
await this.safeDisconnect('kafka producer', () => this.kafkaProducer.disconnect());
|
||||
await this.safeDisconnect('redis', () => this.redis.quit());
|
||||
await this.safeDisconnect('datasource', () => this.dataSource.destroy());
|
||||
|
||||
this.logger.log(`service ${SERVICE_NAME} shutdown complete`);
|
||||
}
|
||||
|
||||
private async safeDisconnect(name: string, fn: () => Promise<unknown>): Promise<void> {
|
||||
try {
|
||||
await fn();
|
||||
this.logger.log(`${name} closed`);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`${name} close failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user