From 0b1f26f16a227c5e0bd6c74bd54ecd6e9ac9aa2e Mon Sep 17 00:00:00 2001 From: huanghaosheng <386998068@qq.com> Date: Wed, 14 Oct 2026 14:37:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(api):=20=E6=96=B0=E5=A2=9E=20/readyz=20?= =?UTF-8?q?=E4=BE=9D=E8=B5=96=E5=B0=B1=E7=BB=AA=E6=8E=A2=E9=92=88=EF=BC=8C?= =?UTF-8?q?=E4=B8=8E=20/healthz=20=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原 /healthz 无条件返回 200,MQ 断连时也报健康,运维无法从探针看出"异步链路已停"; 而 P0-2 修复之后 MQ 会自愈,更需要一个能表达"当前是否已就绪"的出口。 新增 /readyz:MQ 未连接时返回 503,并输出 mq_enabled / mq_connected / mq_generation / mq_reconnects / mq_topology。刻意不改 /healthz: - broker 故障期间 API 本身仍然可用——写路径有"MQ 发布失败则直写 DB"的降级,读路径不依赖 MQ; - 若把 MQ 状态塞进 /healthz 并返回非 200,容器编排或负载均衡可能把仍然健康的实例反复重启 或摘除,把"异步能力降级"放大成"整站不可用"。故障可见 ≠ 故障致命。 mq_enabled 用于区分"根本没启用 MQ"(配置决策)与"已启用但当前断开"(待恢复的故障)—— 只凭 mq_connected=false 无法区分,而两者的处置动作完全不同。 新增 internal/http/router_test.go(该包此前无测试)锁定这条不变式:两个用例都断言 "MQ 不可用时 /healthz 仍为 200、/readyz 为 503"。之所以要写回归测试,正是因为 "顺手把两个探针合并"看起来像简化,而不像破坏。 --- backend/internal/http/router.go | 22 ++++++++ backend/internal/http/router_test.go | 84 ++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 backend/internal/http/router_test.go diff --git a/backend/internal/http/router.go b/backend/internal/http/router.go index 96d1368..7889697 100644 --- a/backend/internal/http/router.go +++ b/backend/internal/http/router.go @@ -13,6 +13,7 @@ import ( "feedsystem_video_go/internal/video" "feedsystem_video_go/internal/worker" "log" + "net/http" "time" "github.com/gin-gonic/gin" @@ -25,9 +26,30 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g if err := r.SetTrustedProxies(nil); err != nil { log.Printf("SetTrustedProxies failed: %v", err) } + // /healthz 只表示"进程存活",永远 200。 r.GET("/healthz", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) }) + // /readyz 表示"依赖就绪",MQ 断连时返回 503(P0-2 配套的可观测性)。 + // + // 刻意与 /healthz 分开:broker 故障期间 API 本身仍然是可用的——写路径有 + // "MQ 发布失败则直写 DB"的降级,读路径不依赖 MQ。若把 MQ 状态塞进 /healthz + // 并返回非 200,容器编排/负载均衡可能把仍然健康的实例反复重启或摘除,把 + // "异步能力降级"放大成"整站不可用"。故障可见 ≠ 故障致命,两者的处置通道必须分开。 + r.GET("/readyz", func(c *gin.Context) { + st := rmq.Stats() // nil 接收者安全:返回零值 + status := http.StatusOK + if !st.Connected { + status = http.StatusServiceUnavailable + } + c.JSON(status, gin.H{ + "mq_enabled": rmq != nil, // 区分"未启用 MQ"与"已启用但当前断开" + "mq_connected": st.Connected, + "mq_generation": st.Generation, + "mq_reconnects": st.Reconnects, + "mq_topology": st.Topology, + }) + }) r.Static("/static", "./.run/uploads") // rate_limit loginLimiter := ratelimit.Limit(cache, "account_login", 10, time.Minute, ratelimit.KeyByIP) diff --git a/backend/internal/http/router_test.go b/backend/internal/http/router_test.go new file mode 100644 index 0000000..77ca21d --- /dev/null +++ b/backend/internal/http/router_test.go @@ -0,0 +1,84 @@ +package http + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "feedsystem_video_go/internal/config" + mqrabbit "feedsystem_video_go/internal/middleware/rabbitmq" + + "github.com/gin-gonic/gin" +) + +func doGet(t *testing.T, r *gin.Engine, path string) (int, map[string]any) { + t.Helper() + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + + var body map[string]any + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("%s: cannot parse body %q: %v", path, w.Body.String(), err) + } + return w.Code, body +} + +func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + return SetRouter(nil, nil, rmq) +} + +// 这是 /readyz 存在的全部意义所在,也是最容易被后人"顺手合并"掉的不变式: +// MQ 断连时 /healthz 必须仍然是 200,否则容器编排会在 broker 故障期间反复重启 +// 仍然健康的实例,把"异步能力降级"放大成"整站不可用"。 +func TestReadyz_MQDisabled_HealthzStaysOK(t *testing.T) { + r := newRouterForTest(t, nil) + + code, body := doGet(t, r, "/healthz") + if code != http.StatusOK { + t.Fatalf("/healthz must stay 200 regardless of MQ state, got %d (%v)", code, body) + } + + code, body = doGet(t, r, "/readyz") + if code != http.StatusServiceUnavailable { + t.Fatalf("/readyz must be 503 when MQ is not connected, got %d (%v)", code, body) + } + if body["mq_enabled"] != false || body["mq_connected"] != false { + t.Fatalf("disabled MQ must report mq_enabled=false, mq_connected=false: %v", body) + } +} + +// "已启用但当前断开"必须与"根本没启用"可区分——两者的处置动作完全不同。 +// +// 注意本用例约需 5 秒:SetRouter 末尾的启动期 EnsureTopology 有 5 秒超时 +// (避免连接恰在启动时断开把 API 启动挂住),而这里的管理器连不上, +// 因此会等满这 5 秒。这 5 秒本身就是该护栏生效的证据,不要为此改短生产超时。 +func TestReadyz_MQEnabledButDisconnected_IsDistinguishable(t *testing.T) { + // 指向必然连不上的端口:管理器会持续重连,当前状态即"已启用、未连接"。 + mgr := mqrabbit.NewRabbitMQLazy(&config.RabbitMQConfig{ + Host: "127.0.0.1", Port: 1, Username: "u", Password: "p", + }) + if mgr == nil { + t.Fatal("lazy manager must not be nil for a valid config") + } + t.Cleanup(func() { _ = mgr.Close() }) + + r := newRouterForTest(t, mgr) + + if code, _ := doGet(t, r, "/healthz"); code != http.StatusOK { + t.Fatalf("/healthz must stay 200 while MQ is down, got %d", code) + } + + code, body := doGet(t, r, "/readyz") + if code != http.StatusServiceUnavailable { + t.Fatalf("/readyz must be 503 while disconnected, got %d (%v)", code, body) + } + if body["mq_enabled"] != true { + t.Fatalf("mq_enabled must distinguish disabled from disconnected: %v", body) + } + if body["mq_reconnects"] != float64(0) { + t.Fatalf("a manager that never connected must report 0 reconnects: %v", body) + } +}