Files
VLoop/backend/internal/http/router.go
huanghaosheng 90a7feb6d3 feat(video): 热度写入单轨化,点赞兜底不再重复插入
热度有两个写入者(PopularityWorker 与兜底直写)和三份实现,其中
VideoService.UpdatePopularity 是死代码且漏删 video:entity 缓存。这里
收敛成一条轨,并让"加过分"这件事可以判重。

- popularity_cache: UpdatePopularityCache 改成 5 参数并返回 error,
  用 redis SETNX 占位 hot:applied:<意图键> 实现幂等;ZINCRBY 失败必须
  撤销占位再上抛(占位留在失败路径上会让增量被永久跳过);三次 Del 是
  best-effort,不受 opCtx 约束。返回 error 同时修掉 P0-3 的 N2——
  原来三条路径全返回 nil,消费端的 Nack/重试/sleep 全是死代码。
- popularityMQ.Update / likeMQ.Like/Unlike 增加 intentKey 入参,写进
  event_id,让点赞事件与热度事件共享一次判重身份。
- like_service: 兜底拆成两个独立的 if(!likeEnqueued 写 DB、
  !popEnqueued 写热榜)。旧代码"两个都成功才 return"会在"点赞已入队 +
  热度发布失败"时再插一次 likes,撞唯一索引返回 500,而点赞其实成功了。
- 删除 VideoService.UpdatePopularity 及其 popularityMQ 字段与构造参数
  (router.go 是唯一调用点)。

行为变更:点赞在热度发布失败时不再返回 500。热度是展示数据,失败只降级
记日志,不回滚已经成立的点赞。
2026-10-30 13:25:48 +08:00

269 lines
11 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"
"net/http"
"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)
}
// /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)
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)
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, rabbitmq.TimelineQueue, cache)
// SSE notification
sseHub := worker.NewSSEHub(db)
notifGroup := r.Group("/notification")
notifGroup.Use(sseHub.SSERequireAuth())
sseHub.RegisterRoutes(r, notifGroup)
// 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放。
// 交换机名、队列名、路由键全部复用 rabbitmq 包的导出常量——它们是跨进程的
// 线缆契约,在这里再写一遍字面量就会与 Worker 侧悄悄漂移。
if rmq != nil {
rmq.RegisterTopology(
rabbitmq.Topology{Exchange: rabbitmq.LikeExchange, Queue: rabbitmq.NotificationLikeQueue, BindingKey: rabbitmq.LikeLikeRK},
rabbitmq.Topology{Exchange: rabbitmq.CommentExchange, Queue: rabbitmq.NotificationCommentQueue, BindingKey: rabbitmq.CommentPublishRK},
rabbitmq.Topology{Exchange: rabbitmq.SocialExchange, Queue: rabbitmq.NotificationSocialQueue, BindingKey: rabbitmq.SocialFollowRK},
)
for _, q := range []string{rabbitmq.NotificationLikeQueue, rabbitmq.NotificationCommentQueue, rabbitmq.NotificationSocialQueue} {
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
}