package http import ( "context" "errors" "net/http" "strings" "time" failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" ) // ReadinessCheck 是应用声明的依赖探测,不暴露驱动错误到健康响应。 type ReadinessCheck struct { Name string `json:"name" dc:"安全的依赖名称,不包含连接地址或凭据"` Check func(context.Context) error `json:"-" dc:"遵守传入上下文的探测函数,不负责创建连接"` } // HealthOptions 描述固定的启动期探测清单。 type HealthOptions struct { TimeoutMS int64 `json:"timeout_ms" dc:"一次就绪检查的总预算毫秒,缺省 1000"` Checks []ReadinessCheck `json:"-" dc:"应用已创建资源的探测列表,注册时复制"` } type checkResult struct { Name string `json:"name" dc:"应用声明的安全依赖名称"` Ready bool `json:"ready" dc:"依赖是否通过检查,不携带原始原因"` } type healthResult struct { Status string `json:"status" dc:"ok 或 not_ready"` Checks []checkResult `json:"checks,omitempty" dc:"就绪探测结果,不输出连接信息"` } // RegisterHealth 批次注册 GET {prefix}/live 和 GET {prefix}/ready。 // 入参:prefix 为完整路径前缀,空值使用 /_health;options 为探测配置。 // 返回:配置、路由冲突或注册已冻结时返回错误,不部分注册。 // 隐式逻辑:就绪初始为 false,应用完成全部装配后显式调用 SetReady(true)。 func (s *Server) RegisterHealth(prefix string, options HealthOptions) error { if prefix == "" { prefix = "/_health" } prefix = strings.TrimRight(prefix, "/") if !strings.HasPrefix(prefix, "/") || strings.ContainsAny(prefix, ":*?#") || options.TimeoutMS < 0 || options.TimeoutMS > int64((1<<63-1)/time.Millisecond) { return failure.Wrap(codeHealthConfig, "validate health endpoint configuration failed", errors.New("invalid health prefix or probe budget")) } if options.TimeoutMS == 0 { options.TimeoutMS = 1000 } options.Checks = append([]ReadinessCheck(nil), options.Checks...) names := make(map[string]bool, len(options.Checks)) for _, check := range options.Checks { if strings.TrimSpace(check.Name) == "" || check.Check == nil || names[check.Name] { return failure.Wrap(codeHealthConfig, "validate readiness check configuration failed", errors.New("check names and callbacks must be unique and non-empty")) } names[check.Name] = true } return s.commit([]route{ {meta: Metadata{Method: http.MethodGet, Path: prefix + "/live", Summary: "Process liveness", Tag: "health"}, handlers: []gin.HandlerFunc{func(ctx *gin.Context) { ctx.JSON(http.StatusOK, healthResult{Status: "ok"}) }}}, {meta: Metadata{Method: http.MethodGet, Path: prefix + "/ready", Summary: "Service readiness", Tag: "health"}, handlers: []gin.HandlerFunc{s.readiness(options)}}, }) } // SetReady 设置应用装配/排空阶段的就绪信号,不代替依赖探测。 // 入参:ready 为应用是否允许接收业务流量;停止时框架自动置 false。 func (s *Server) SetReady(ready bool) { s.ready.Store(ready) } // readiness 创建使用固定探测快照的处理器,不建立后台任务或动态注册表。 // 入参:options 为已经校验的检查清单和总预算。 // 返回:不泄露检查原始错误的 Gin Handler;回调必须响应取消。 func (s *Server) readiness(options HealthOptions) gin.HandlerFunc { return func(ctx *gin.Context) { if !s.ready.Load() { ctx.JSON(http.StatusServiceUnavailable, healthResult{Status: "not_ready"}) return } probe, cancel := context.WithTimeout(ctx.Request.Context(), time.Duration(options.TimeoutMS)*time.Millisecond) defer cancel() result := healthResult{Status: "ok", Checks: make([]checkResult, 0, len(options.Checks))} for _, check := range options.Checks { err := probe.Err() if err == nil { err = check.Check(probe) } if err == nil { err = probe.Err() } passed := err == nil if !passed { _ = failure.WrapContext(probe, codeReadinessCheck, "check service readiness failed", err) result.Status = "not_ready" } result.Checks = append(result.Checks, checkResult{Name: check.Name, Ready: passed}) } status := http.StatusOK if !s.ready.Load() || result.Status != "ok" { status = http.StatusServiceUnavailable result.Status = "not_ready" } ctx.JSON(status, result) } }