Files
VLoop/backend/internal/http/router.go
huanghaosheng 65ca5c5218 feat(rabbitmq): 连接管理器接管连接生命周期,MQ 重启后自动恢复
原实现全进程只 amqp.Dial 一次,之后所有消费者共享该连接,而
runWorkerWithRetry 只重建 channel。amqp091-go 的连接一旦关闭,Channel()
会直接返回 ErrClosed(connection.go:842-848),连一次网络 I/O 都不会发出,
因此循环退化为"每 5 秒打一行日志"的死转:MQ 重启后 8 个消费者永久卡死,
只能人工重启进程。

本次把 RabbitMQ 从"持有一个 Conn 字段的结构体"改为连接管理器:

- 连接私有化,只由 supervise 协程创建;断连由 NotifyClose 事件驱动(必须用
  带缓冲 channel,否则会卡死库的 shutdown 路径),重连采用指数退避 + 抖动。
- 引入"连接代":Session 同时返回 channel 与其所属代的令牌,避免消费者拿着
  旧 channel 等在新代上——那会表现为永久挂起,与原始缺陷无法区分。
- 就绪判定一律以 conn 为准,ready 仅作状态变化广播,因此不存在
  "ready 与 conn 不一致"的窗口;install / markDown 在同一把锁内成对迁移状态。
- 拓扑登记(RegisterTopology)与重放(EnsureTopology)分离:每次重连后自动
  重放全部已登记拓扑,从而同时修掉报告之外的第二种卡死——"连接活着但队列
  没了"(broker 数据卷重建、队列被删、声明参数冲突),那种情况永远不会触发
  连接重连。
- 新增 consumer.go:RunConsumer 是全项目唯一的消费循环。断连期间阻塞等待
  (不轮询、不打日志,消除 96 行/分钟的 504 噪声),恢复后重建 channel、重新
  设置 QoS 并重新 Consume;channel 级异常则先重放拓扑再退避重试。原先三处
  重复实现(prefetch 还分别为 50 / 无 / 10)收敛为一处。
- 为连接注入 connection 接口,使连接代状态机可脱离 broker 被测试。

API 侧接线同步改造:outboxworker 的 StartConsumer 委托 RunConsumer,router.go
的 3 个通知消费者改用 RunConsumer(原为手写 5 秒轮询重连)。

publisher 的改造放在下一个提交;本提交先用一个带注释的临时兼容函数
PublishJSON 让尚未迁移的 5 个 publisher 继续编译,下一次提交即删除。
2026-10-14 14:03:08 +08:00

245 lines
10 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package http
import (
"context"
"feedsystem_video_go/internal/account"
"feedsystem_video_go/internal/feed"
"feedsystem_video_go/internal/message"
"feedsystem_video_go/internal/middleware/jwt"
"feedsystem_video_go/internal/middleware/rabbitmq"
"feedsystem_video_go/internal/middleware/ratelimit"
rediscache "feedsystem_video_go/internal/middleware/redis"
"feedsystem_video_go/internal/social"
"feedsystem_video_go/internal/video"
"feedsystem_video_go/internal/worker"
"log"
"time"
"github.com/gin-gonic/gin"
amqp "github.com/rabbitmq/amqp091-go"
"gorm.io/gorm"
)
func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
r := gin.Default()
if err := r.SetTrustedProxies(nil); err != nil {
log.Printf("SetTrustedProxies failed: %v", err)
}
r.GET("/healthz", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok"})
})
r.Static("/static", "./.run/uploads")
// rate_limit
loginLimiter := ratelimit.Limit(cache, "account_login", 10, time.Minute, ratelimit.KeyByIP)
registerLimiter := ratelimit.Limit(cache, "account_register", 5, time.Hour, ratelimit.KeyByIP)
likeLimiter := ratelimit.Limit(cache, "like_write", 30, time.Minute, ratelimit.KeyByAccount)
commentLimiter := ratelimit.Limit(cache, "comment_write", 10, time.Minute, ratelimit.KeyByAccount)
socialLimiter := ratelimit.Limit(cache, "social_write", 20, time.Minute, ratelimit.KeyByAccount)
// account
accountRepository := account.NewAccountRepository(db)
accountService := account.NewAccountService(accountRepository, cache)
accountHandler := account.NewAccountHandler(accountService)
accountGroup := r.Group("/account")
{
accountGroup.POST("/register", registerLimiter, accountHandler.CreateAccount)
accountGroup.POST("/login", loginLimiter, accountHandler.Login)
accountGroup.POST("/changePassword", accountHandler.ChangePassword)
accountGroup.POST("/findByID", accountHandler.FindByID)
accountGroup.POST("/findByUsername", accountHandler.FindByUsername)
accountGroup.POST("/refresh", accountHandler.Refresh)
}
protectedAccountGroup := accountGroup.Group("")
protectedAccountGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedAccountGroup.POST("/logout", accountHandler.Logout)
protectedAccountGroup.POST("/rename", accountHandler.Rename)
protectedAccountGroup.POST("/uploadAvatar", accountHandler.UploadAvatar)
protectedAccountGroup.POST("/updateProfile", accountHandler.UpdateProfile)
}
// video
videoRepository := video.NewVideoRepository(db)
popularityMQ, err := rabbitmq.NewPopularityMQ(rmq)
if err != nil {
log.Printf("PopularityMQ init failed (mq disabled): %v", err)
popularityMQ = nil
}
videoService := video.NewVideoService(videoRepository, cache, popularityMQ)
videoHandler := video.NewVideoHandler(videoService, accountService)
chunkHandler := video.NewChunkUploadHandler(cache)
videoGroup := r.Group("/video")
{
videoGroup.POST("/listByAuthorID", videoHandler.ListByAuthorID)
videoGroup.POST("/getDetail", videoHandler.GetDetail)
}
protectedVideoGroup := videoGroup.Group("")
protectedVideoGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedVideoGroup.POST("/uploadVideo", videoHandler.UploadVideo)
protectedVideoGroup.POST("/uploadCover", videoHandler.UploadCover)
protectedVideoGroup.POST("/publish", videoHandler.PublishVideo)
protectedVideoGroup.POST("/chunk/init", chunkHandler.InitChunkUpload)
protectedVideoGroup.POST("/chunk/upload", chunkHandler.UploadChunk)
protectedVideoGroup.POST("/chunk/status", chunkHandler.ChunkStatus)
protectedVideoGroup.POST("/chunk/complete", chunkHandler.CompleteChunkUpload)
}
// like
likeMQ, err := rabbitmq.NewLikeMQ(rmq)
if err != nil {
log.Printf("LikeMQ init failed (mq disabled): %v", err)
likeMQ = nil
}
likeRepository := video.NewLikeRepository(db)
likeService := video.NewLikeService(likeRepository, videoRepository, cache, likeMQ, popularityMQ)
likeHandler := video.NewLikeHandler(likeService)
likeGroup := r.Group("/like")
protectedLikeGroup := likeGroup.Group("")
protectedLikeGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedLikeGroup.POST("/like", likeLimiter, likeHandler.Like)
protectedLikeGroup.POST("/unlike", likeLimiter, likeHandler.Unlike)
protectedLikeGroup.POST("/isLiked", likeHandler.IsLiked)
protectedLikeGroup.POST("/listMyLikedVideos", likeHandler.ListMyLikedVideos)
}
// comment
commentRepository := video.NewCommentRepository(db)
commentMQ, err := rabbitmq.NewCommentMQ(rmq)
if err != nil {
log.Printf("CommentMQ init failed (mq disabled): %v", err)
commentMQ = nil
}
commentService := video.NewCommentService(commentRepository, videoRepository, cache, commentMQ, popularityMQ)
commentHandler := video.NewCommentHandler(commentService, accountService)
commentGroup := r.Group("/comment")
{
commentGroup.POST("/listAll", commentHandler.GetAllComments)
}
protectedCommentGroup := commentGroup.Group("")
protectedCommentGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedCommentGroup.POST("/publish", commentLimiter, commentHandler.PublishComment)
protectedCommentGroup.POST("/delete", commentLimiter, commentHandler.DeleteComment)
}
// social
socialMQ, err := rabbitmq.NewSocialMQ(rmq)
if err != nil {
log.Printf("SocialMQ init failed (mq disabled): %v", err)
socialMQ = nil
}
socialRepository := social.NewSocialRepository(db)
socialService := social.NewSocialService(socialRepository, accountRepository, socialMQ, cache)
socialHandler := social.NewSocialHandler(socialService)
socialGroup := r.Group("/social")
protectedSocialGroup := socialGroup.Group("")
protectedSocialGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedSocialGroup.POST("/follow", socialLimiter, socialHandler.Follow)
protectedSocialGroup.POST("/unfollow", socialLimiter, socialHandler.Unfollow)
protectedSocialGroup.POST("/getAllFollowers", socialHandler.GetAllFollowers)
protectedSocialGroup.POST("/getAllVloggers", socialHandler.GetAllVloggers)
protectedSocialGroup.POST("/getCounts", socialHandler.GetCounts)
}
accountGroup.POST("/getProfile", func(c *gin.Context) {
var req account.GetProfileRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if req.AccountID == 0 {
c.JSON(400, gin.H{"error": "account_id is required"})
return
}
acc, err := accountService.FindByID(c.Request.Context(), req.AccountID)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
videoCount, _ := videoRepository.CountByAuthor(c.Request.Context(), req.AccountID)
totalLikes, _ := videoRepository.TotalLikesByAuthor(c.Request.Context(), req.AccountID)
followerCount, _ := socialRepository.CountFollowers(c.Request.Context(), req.AccountID)
vloggerCount, _ := socialRepository.CountVloggers(c.Request.Context(), req.AccountID)
c.JSON(200, account.GetProfileResponse{
Account: account.FindByIDResponse{ID: acc.ID, Username: acc.Username, AvatarURL: acc.AvatarURL, Bio: acc.Bio},
VideoCount: videoCount, TotalLikes: totalLikes,
FollowerCount: followerCount, VloggerCount: vloggerCount,
})
})
// feed
feedRepository := feed.NewFeedRepository(db)
feedService := feed.NewFeedService(feedRepository, likeRepository, cache)
feedHandler := feed.NewFeedHandler(feedService)
feedGroup := r.Group("/feed")
feedGroup.Use(jwt.SoftJWTAuth(accountRepository, cache))
{
feedGroup.POST("/listLatest", feedHandler.ListLatest)
feedGroup.POST("/listLikesCount", feedHandler.ListLikesCount)
feedGroup.POST("/listByPopularity", feedHandler.ListByPopularity)
feedGroup.POST("/listByTag", feedHandler.ListByTag)
}
protectedFeedGroup := feedGroup.Group("")
protectedFeedGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedFeedGroup.POST("/listByFollowing", feedHandler.ListByFollowing)
}
// message
messageRepo := message.NewRepository(db)
messageService := message.NewService(messageRepo)
messageHandler := message.NewHandler(messageService)
messageGroup := r.Group("/message")
protectedMessageGroup := messageGroup.Group("")
protectedMessageGroup.Use(jwt.JWTAuth(accountRepository, cache))
{
protectedMessageGroup.POST("/send", messageHandler.Send)
protectedMessageGroup.POST("/list", messageHandler.List)
}
// worker:Outbox 轮询 + Timeline 消费者
// 连接级重连 / 拓扑重放 / channel 重建统一由连接管理器(rabbitmq.RunConsumer)负责
timelineMQ, err := rabbitmq.NewTimelineMQ(rmq)
if err != nil {
log.Printf("timelineMQ init failed (mq disabled): %v", err)
timelineMQ = nil
}
worker.StartOutboxPoller(db, timelineMQ)
worker.StartConsumer(context.Background(), rmq, "video.timeline.update.queue", cache)
// SSE notification
sseHub := worker.NewSSEHub(db)
notifGroup := r.Group("/notification")
notifGroup.Use(sseHub.SSERequireAuth())
sseHub.RegisterRoutes(r, notifGroup)
// 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放
if rmq != nil {
rmq.RegisterTopology(
rabbitmq.Topology{Exchange: "like.events", Queue: "notification.like", BindingKey: "like.like"},
rabbitmq.Topology{Exchange: "comment.events", Queue: "notification.comment", BindingKey: "comment.publish"},
rabbitmq.Topology{Exchange: "social.events", Queue: "notification.social", BindingKey: "social.follow"},
)
for _, q := range []string{"notification.like", "notification.comment", "notification.social"} {
queue := q
go rabbitmq.RunConsumer(context.Background(), rmq, "notification-"+queue, 10,
func(ch *amqp.Channel) error {
return worker.NewNotificationWorker(ch, db, queue, sseHub).Run(context.Background())
})
}
} else {
log.Printf("Notification SSE disabled (MQ not available)")
}
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
if rmq != nil {
initCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := rmq.EnsureTopology(initCtx); err != nil {
log.Printf("rabbitmq topology init failed (will be redeclared on reconnect): %v", err)
}
cancel()
}
return r
}