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) + } +}