refactor(video): 计数改由业务事务维护并删除热度第二条写路径
点赞与评论的计数只由业务事务写。ApplyLike、ApplyUnlike、CreateIdempotentWithPopularity 与 DeleteWithPopularity 各自在单事务内完成插行与计数。 热榜增量改为提交后的 best-effort 写。ApplyHotDelta 按行的 created_at 落分钟桶,写失败只记日志,DB 计数仍然正确。 删除 PopularityMQ 与 PopularityWorker。同一次互动因此只有一个写者,不再有两个门闩各自放行。 删除 hot:applied 占位键。判重改由 likes 的唯一索引与 uk_comments_author_key 负责。 DeleteWithPopularity 先读行再删行。评论删除因此回退热度,重复投递不再多减一次。 likes 与 comments 各加 (created_at, video_id) 覆盖索引,服务热榜窗口查询。 验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
This commit is contained in:
@@ -82,11 +82,6 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
}
|
||||
// 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)
|
||||
@@ -113,7 +108,7 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
likeMQ = nil
|
||||
}
|
||||
likeRepository := video.NewLikeRepository(db)
|
||||
likeService := video.NewLikeService(likeRepository, videoRepository, cache, likeMQ, popularityMQ)
|
||||
likeService := video.NewLikeService(likeRepository, videoRepository, cache, likeMQ)
|
||||
likeHandler := video.NewLikeHandler(likeService)
|
||||
likeGroup := r.Group("/like")
|
||||
protectedLikeGroup := likeGroup.Group("")
|
||||
@@ -131,7 +126,7 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
log.Printf("CommentMQ init failed (mq disabled): %v", err)
|
||||
commentMQ = nil
|
||||
}
|
||||
commentService := video.NewCommentService(commentRepository, videoRepository, cache, commentMQ, popularityMQ)
|
||||
commentService := video.NewCommentService(commentRepository, videoRepository, cache, commentMQ)
|
||||
commentHandler := video.NewCommentHandler(commentService, accountService)
|
||||
commentGroup := r.Group("/comment")
|
||||
{
|
||||
|
||||
@@ -32,11 +32,6 @@ func TestTopologyConstants_WireNamesAreStable(t *testing.T) {
|
||||
{"SocialFollowRK", SocialFollowRK, "social.follow"},
|
||||
{"SocialUnfollowRK", SocialUnfollowRK, "social.unfollow"},
|
||||
|
||||
{"PopularityExchange", PopularityExchange, "video.popularity.events"},
|
||||
{"PopularityQueue", PopularityQueue, "video.popularity.events"},
|
||||
{"PopularityBindingKey", PopularityBindingKey, "video.popularity.*"},
|
||||
{"PopularityUpdateRK", PopularityUpdateRK, "video.popularity.update"},
|
||||
|
||||
{"TimelineExchange", TimelineExchange, "video.timeline.events"},
|
||||
{"TimelineQueue", TimelineQueue, "video.timeline.update.queue"},
|
||||
{"TimelineBindingKey", TimelineBindingKey, "video.timeline.*"},
|
||||
|
||||
@@ -40,8 +40,8 @@ func NewLikeMQ(base *RabbitMQ) (*LikeMQ, error) {
|
||||
return &LikeMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
// Like / Unlike 的 intentKey 语义见 PopularityMQ.Update:同一个键会同时
|
||||
// 出现在点赞事件与热度事件的 event_id 里,让两条投递链路共享一次判重身份。
|
||||
// Like / Unlike 的 intentKey 只作为 LikeEvent.EventID:调用方用它把日志与
|
||||
// 一条用户意图对齐,判重仍由 likes 表的唯一索引负责(见 ApplyLike)。
|
||||
func (l *LikeMQ) Like(ctx context.Context, userID, videoID uint, intentKey string) error {
|
||||
return l.publish(ctx, "like", LikeLikeRK, userID, videoID, intentKey)
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PopularityMQ 通过连接管理器发布热度事件(不再持有长生命周期 channel)。
|
||||
type PopularityMQ struct {
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
// 拓扑常量导出:见 likeMQ.go 中的说明。
|
||||
const (
|
||||
PopularityExchange = "video.popularity.events"
|
||||
PopularityQueue = "video.popularity.events"
|
||||
PopularityBindingKey = "video.popularity.*"
|
||||
|
||||
PopularityUpdateRK = "video.popularity.update"
|
||||
)
|
||||
|
||||
type PopularityEvent struct {
|
||||
EventID string `json:"event_id"`
|
||||
VideoID uint `json:"video_id"`
|
||||
Change int64 `json:"change"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
}
|
||||
|
||||
func NewPopularityMQ(base *RabbitMQ) (*PopularityMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
base.RegisterTopology(Topology{Exchange: PopularityExchange, Queue: PopularityQueue, BindingKey: PopularityBindingKey})
|
||||
return &PopularityMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
// Update 发布一条热度事件。
|
||||
//
|
||||
// intentKey 是"这次用户意图"的稳定标识,会写进 event_id:调用方(如点赞)
|
||||
// 用同一个键同时发布点赞事件与热度事件,于是两条消息无论重复投递多少次,
|
||||
// 消费端都能认出"这是同一次意图"(P0-4)。intentKey 为空时退化为随机 id
|
||||
// ——注意此时消费端无法去重,所以生产路径必须传键。
|
||||
func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64, intentKey string) error {
|
||||
if p == nil || p.mgr == nil {
|
||||
return errors.New("popularity mq is not initialized")
|
||||
}
|
||||
if videoID == 0 || change == 0 {
|
||||
return errors.New("videoID and change are required")
|
||||
}
|
||||
id := intentKey
|
||||
if id == "" {
|
||||
var err error
|
||||
id, err = newEventID(16)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
event := PopularityEvent{
|
||||
EventID: id,
|
||||
VideoID: videoID,
|
||||
Change: change,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
}
|
||||
return p.mgr.PublishJSON(ctx, PopularityExchange, PopularityUpdateRK, event)
|
||||
}
|
||||
@@ -2,13 +2,16 @@ package video
|
||||
|
||||
import "time"
|
||||
|
||||
// Comment 的 (created_at, video_id) 覆盖索引 idx_comments_created_video
|
||||
// 服务热榜窗口查询与 DB 回退排序:范围扫描走 created_at,video_id 留在
|
||||
// 索引里避免回表。
|
||||
type Comment struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Username string `gorm:"index" json:"username"`
|
||||
VideoID uint `gorm:"index" json:"video_id"`
|
||||
VideoID uint `gorm:"index;index:idx_comments_created_video,priority:2" json:"video_id"`
|
||||
AuthorID uint `gorm:"index;uniqueIndex:uk_comments_author_key,priority:1" json:"author_id"`
|
||||
Content string `gorm:"type:text" json:"content"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;index:idx_comments_created_video,priority:1" json:"created_at"`
|
||||
|
||||
// IdempotencyKey 必须是 *string:空串会互撞唯一索引,NULL 不会。
|
||||
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
|
||||
|
||||
@@ -2,6 +2,7 @@ package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/notification"
|
||||
@@ -49,20 +50,46 @@ func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context,
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *CommentRepository) DeleteComment(ctx context.Context, comment *Comment) error {
|
||||
return r.db.WithContext(ctx).Delete(comment).Error
|
||||
}
|
||||
|
||||
// DeleteByID 返回是否真的删除了一行,供调用方门控热度回退。
|
||||
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
|
||||
// DeleteWithPopularity 删除评论,并在同一事务里把所属视频的 popularity 减 1。
|
||||
//
|
||||
// 返回被删的那一行:调用方要它的 created_at 把热榜分数减回评论发布那一刻的
|
||||
// 分钟桶,还要它的 video_id 定位视频。这两个值都从库里取,比事件里的快照
|
||||
// 更可信——事件到达时行可能已经被别的路径删掉了。
|
||||
//
|
||||
// deleted=false 表示没有这一行(重复投递的删除),此时不能再减热度。
|
||||
func (r *CommentRepository) DeleteWithPopularity(ctx context.Context, id uint) (*Comment, bool, error) {
|
||||
if id == 0 {
|
||||
return false, nil
|
||||
return nil, false, nil
|
||||
}
|
||||
res := r.db.WithContext(ctx).Delete(&Comment{}, id)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
var deleted *Comment
|
||||
ok := false
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var row Comment
|
||||
if err := tx.First(&row, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
res := tx.Delete(&Comment{}, row.ID)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
deleted = &row
|
||||
ok = true
|
||||
|
||||
return tx.Model(&Video{}).
|
||||
Where("id = ?", row.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
return deleted, ok, nil
|
||||
}
|
||||
|
||||
func (r *CommentRepository) GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) {
|
||||
|
||||
@@ -51,10 +51,10 @@ func newTestDB(t *testing.T) *gorm.DB {
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&Comment{}, &Video{}, ¬ification.Notification{}, &testAccount{}); err != nil {
|
||||
if err := db.Migrator().DropTable(&Comment{}, &Video{}, &Like{}, ¬ification.Notification{}, &testAccount{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, ¬ification.Notification{}); err != nil {
|
||||
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &Like{}, ¬ification.Notification{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
@@ -245,3 +245,51 @@ func TestFindAccountIDs_BatchResolve(t *testing.T) {
|
||||
t.Fatalf("解析结果异常: %+v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// P2-20:删除评论必须回退热度,且只能回退一次。
|
||||
//
|
||||
// 旧实现只删行(DeleteByID),popularity 永远停在原值。这里双击一次判重:
|
||||
// 第一次返回 deleted=true 并减 1,第二次读不到行、deleted=false,不得再减。
|
||||
func TestDeleteWithPopularity_DecrementsOnce(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 5)
|
||||
|
||||
c := &Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
|
||||
if _, err := repo.CreateIdempotentWithPopularity(ctx, c, 1); err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
|
||||
row, deleted, err := repo.DeleteWithPopularity(ctx, c.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteWithPopularity: %v", err)
|
||||
}
|
||||
if !deleted {
|
||||
t.Fatal("首次删除必须报告 deleted=true")
|
||||
}
|
||||
if row == nil || row.VideoID != v.ID {
|
||||
t.Fatalf("返回行 = %+v, want video_id=%d(热度减到哪个视频必须由行决定)", row, v.ID)
|
||||
}
|
||||
if row.CreatedAt.IsZero() {
|
||||
t.Fatal("返回行必须带原始 created_at:热榜 -1 要落回创建那一分钟")
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 5 {
|
||||
t.Fatalf("popularity = %d, want 5(5+1-1,删除只减一次)", got.Popularity)
|
||||
}
|
||||
|
||||
if _, deleted, err := repo.DeleteWithPopularity(ctx, c.ID); err != nil || deleted {
|
||||
t.Fatalf("重复删除 = deleted:%v err:%v, want false/nil", deleted, err)
|
||||
}
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 5 {
|
||||
t.Fatalf("重复删除后 popularity = %d, want 5(空操作不能再减)", got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"log"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
@@ -20,34 +21,31 @@ type CommentPublisher interface {
|
||||
Delete(ctx context.Context, commentID uint, intentKey string) error
|
||||
}
|
||||
|
||||
type PopularityPublisher interface {
|
||||
Update(ctx context.Context, videoID uint, change int64, intentKey string) error
|
||||
}
|
||||
|
||||
// videoExister 由 *VideoRepository 满足,因此 router.go 无需改动。
|
||||
type videoExister interface {
|
||||
IsExist(ctx context.Context, id uint) (bool, error)
|
||||
}
|
||||
|
||||
type CommentService struct {
|
||||
store CommentStore
|
||||
videos videoExister
|
||||
cache *rediscache.Client
|
||||
commentMQ CommentPublisher
|
||||
popularityMQ PopularityPublisher
|
||||
store CommentStore
|
||||
videos videoExister
|
||||
cache *rediscache.Client
|
||||
commentMQ CommentPublisher
|
||||
}
|
||||
|
||||
func NewCommentService(store CommentStore, videos videoExister, cache *rediscache.Client, commentMQ CommentPublisher, popularityMQ PopularityPublisher) *CommentService {
|
||||
func NewCommentService(store CommentStore, videos videoExister, cache *rediscache.Client, commentMQ CommentPublisher) *CommentService {
|
||||
return &CommentService{
|
||||
store: store,
|
||||
videos: videos,
|
||||
cache: cache,
|
||||
commentMQ: commentMQ,
|
||||
popularityMQ: popularityMQ,
|
||||
store: store,
|
||||
videos: videos,
|
||||
cache: cache,
|
||||
commentMQ: commentMQ,
|
||||
}
|
||||
}
|
||||
|
||||
// Publish 用同一个意图键编排两条路径:MQ 成功则不直写,失败则直写。
|
||||
// Publish 先入队,入队失败才直写。
|
||||
//
|
||||
// 热度不再单独发布:它只由"这次插入是否真的落库"驱动,所以两条轨不会
|
||||
// 各自成功一半。
|
||||
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
if comment == nil {
|
||||
return errors.New("comment is nil")
|
||||
@@ -71,6 +69,9 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
return fmt.Errorf("%w: video not found", apierror.ErrValidation)
|
||||
}
|
||||
|
||||
// 行时间只在"直写"分支用到;worker 分支用它自己消息里的 occurred_at。
|
||||
comment.CreatedAt = time.Now().UTC()
|
||||
|
||||
commentEnqueued := false
|
||||
if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{
|
||||
EventID: key,
|
||||
@@ -85,13 +86,6 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
log.Printf("%s enqueue comment failed, fallback to direct write: %v", span, err)
|
||||
}
|
||||
|
||||
popularityEnqueued := false
|
||||
if err := s.popularityMQ.Update(ctx, comment.VideoID, 1, key); err == nil {
|
||||
popularityEnqueued = true
|
||||
} else {
|
||||
log.Printf("%s enqueue popularity failed, fallback to hot cache: %v", span, err)
|
||||
}
|
||||
|
||||
// 入队成功时不直写,避免正常路径上稳定双写。
|
||||
if !commentEnqueued {
|
||||
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
||||
@@ -99,12 +93,11 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
return fmt.Errorf("fallback create comment: %w", err)
|
||||
}
|
||||
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
|
||||
}
|
||||
|
||||
// 热度与评论是两次独立发布,失败只降级。
|
||||
if !popularityEnqueued {
|
||||
if err := UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, key); err != nil {
|
||||
log.Printf("%s hot cache update failed (degraded): %v", span, err)
|
||||
// 只有真的插入了才加热度:重复意图已经被唯一索引挡掉。
|
||||
if created {
|
||||
if err := ApplyHotDelta(ctx, s.cache, comment.VideoID, 1, comment.CreatedAt); err != nil {
|
||||
log.Printf("%s hot window update failed (degraded): %v", span, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,14 +116,31 @@ func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID u
|
||||
if comment.AuthorID != accountID {
|
||||
return apierror.ErrUnauthorized
|
||||
}
|
||||
key, keyErr := NewIntentKey()
|
||||
if keyErr != nil {
|
||||
key = ""
|
||||
|
||||
if s.commentMQ != nil {
|
||||
key, keyErr := NewIntentKey()
|
||||
if keyErr != nil {
|
||||
key = ""
|
||||
}
|
||||
err := s.commentMQ.Delete(ctx, commentID, key)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
log.Printf("comment_id=%d stage=comment.delete enqueue failed, fallback to direct write: %v", commentID, err)
|
||||
}
|
||||
if err := s.commentMQ.Delete(ctx, commentID, key); err == nil {
|
||||
|
||||
deleted, ok, err := s.store.DeleteWithPopularity(ctx, commentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
// 已经被删除(重复投递或另一条路径先到):空操作,热度不能再减。
|
||||
return nil
|
||||
}
|
||||
return s.store.DeleteComment(ctx, comment)
|
||||
if err := ApplyHotDelta(ctx, s.cache, deleted.VideoID, -1, deleted.CreatedAt); err != nil {
|
||||
log.Printf("comment_id=%d stage=comment.delete hot window update failed (degraded): %v", commentID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CommentService) GetAll(ctx context.Context, videoID uint) ([]Comment, error) {
|
||||
|
||||
@@ -4,9 +4,13 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
)
|
||||
|
||||
type fakeVideoExister struct {
|
||||
@@ -25,6 +29,13 @@ type fakeCommentStore struct {
|
||||
lastComment *Comment
|
||||
lastDelta int64
|
||||
|
||||
// 删除路径:byID 是 GetByID 的返回,deleteRow/deleted 是 DeleteWithPopularity 的返回。
|
||||
byID *Comment
|
||||
deleteCalls int
|
||||
deleteRow *Comment
|
||||
deleted bool
|
||||
deleteErr error
|
||||
|
||||
findNames []string
|
||||
ids map[string]uint
|
||||
findErr error
|
||||
@@ -40,11 +51,14 @@ func (f *fakeCommentStore) CreateIdempotentWithPopularity(_ context.Context, c *
|
||||
return f.created, f.createErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) GetByID(_ context.Context, _ uint) (*Comment, error) { return nil, nil }
|
||||
func (f *fakeCommentStore) GetByID(_ context.Context, _ uint) (*Comment, error) {
|
||||
return f.byID, nil
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) DeleteComment(_ context.Context, _ *Comment) error { return nil }
|
||||
|
||||
func (f *fakeCommentStore) DeleteByID(_ context.Context, _ uint) (bool, error) { return false, nil }
|
||||
func (f *fakeCommentStore) DeleteWithPopularity(_ context.Context, _ uint) (*Comment, bool, error) {
|
||||
f.deleteCalls++
|
||||
return f.deleteRow, f.deleted, f.deleteErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) GetAllComments(_ context.Context, _ uint) ([]Comment, error) {
|
||||
return nil, nil
|
||||
@@ -63,6 +77,7 @@ func (f *fakeCommentStore) FindAccountIDs(_ context.Context, names []string) (ma
|
||||
type fakeCommentPublisher struct {
|
||||
events []rabbitmq.CommentEvent
|
||||
pubErr error
|
||||
delErr error
|
||||
}
|
||||
|
||||
func (f *fakeCommentPublisher) Publish(_ context.Context, evt rabbitmq.CommentEvent) error {
|
||||
@@ -70,50 +85,45 @@ func (f *fakeCommentPublisher) Publish(_ context.Context, evt rabbitmq.CommentEv
|
||||
return f.pubErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentPublisher) Delete(_ context.Context, _ uint, _ string) error { return nil }
|
||||
|
||||
type popularityCall struct {
|
||||
videoID uint
|
||||
change int64
|
||||
key string
|
||||
}
|
||||
|
||||
type fakePopularityPublisher struct {
|
||||
calls []popularityCall
|
||||
pubErr error
|
||||
}
|
||||
|
||||
func (f *fakePopularityPublisher) Update(_ context.Context, videoID uint, change int64, intentKey string) error {
|
||||
f.calls = append(f.calls, popularityCall{videoID: videoID, change: change, key: intentKey})
|
||||
return f.pubErr
|
||||
}
|
||||
func (f *fakeCommentPublisher) Delete(_ context.Context, _ uint, _ string) error { return f.delErr }
|
||||
|
||||
type commentFixture struct {
|
||||
svc *CommentService
|
||||
store *fakeCommentStore
|
||||
comments *fakeCommentPublisher
|
||||
pop *fakePopularityPublisher
|
||||
cache *rediscache.Client
|
||||
mr *miniredis.Miniredis
|
||||
}
|
||||
|
||||
func newCommentFixture(t *testing.T) *commentFixture {
|
||||
t.Helper()
|
||||
store := &fakeCommentStore{created: true, ids: map[string]uint{}}
|
||||
comments := &fakeCommentPublisher{}
|
||||
pop := &fakePopularityPublisher{}
|
||||
cache, _ := newTestCache(t)
|
||||
svc := NewCommentService(store, &fakeVideoExister{exists: true}, cache, comments, pop)
|
||||
return &commentFixture{svc: svc, store: store, comments: comments, pop: pop}
|
||||
cache, mr := newTestCache(t)
|
||||
svc := NewCommentService(store, &fakeVideoExister{exists: true}, cache, comments)
|
||||
return &commentFixture{svc: svc, store: store, comments: comments, cache: cache, mr: mr}
|
||||
}
|
||||
|
||||
// hotScoreAt 返回某个视频在某一分钟桶里的分数;桶不存在时返回 0。
|
||||
func (f *commentFixture) hotScoreAt(t *testing.T, videoID uint, at time.Time) float64 {
|
||||
t.Helper()
|
||||
score, err := f.mr.ZScore(f.cache.Key("hot:video:1m:%s", HotBucket(at)), HotMember(videoID))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func newComment(videoID, authorID uint, content string) *Comment {
|
||||
return &Comment{VideoID: videoID, AuthorID: authorID, Username: "alice", Content: content}
|
||||
}
|
||||
|
||||
// 两条事件都发出去之后,API 绝不能再写一次库:否则"MQ 正常"的常规路径
|
||||
// 评论事件发出去之后,API 绝不能再写一次库:否则"MQ 正常"的常规路径
|
||||
// 会稳定产生两条评论——这正是 P0-4 的核心症状之一。
|
||||
func TestCommentService_Publish_BothEnqueued_SkipsLocalWrite(t *testing.T) {
|
||||
func TestCommentService_Publish_Enqueued_SkipsLocalWriteAndHot(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
if err := f.svc.Publish(context.Background(), newComment(7, 1, "hello")); err != nil {
|
||||
c := newComment(7, 1, "hello")
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 0 {
|
||||
@@ -122,12 +132,9 @@ func TestCommentService_Publish_BothEnqueued_SkipsLocalWrite(t *testing.T) {
|
||||
if len(f.comments.events) != 1 || f.comments.events[0].EventID == "" {
|
||||
t.Fatalf("评论事件 = %+v, want 1 条且带 event_id", f.comments.events)
|
||||
}
|
||||
if len(f.pop.calls) != 1 || f.pop.calls[0].key == "" {
|
||||
t.Fatalf("热度事件 = %+v, want 1 条且带意图键", f.pop.calls)
|
||||
}
|
||||
if f.comments.events[0].EventID != f.pop.calls[0].key {
|
||||
t.Fatalf("两条事件必须共享同一个意图键: comment=%q popularity=%q",
|
||||
f.comments.events[0].EventID, f.pop.calls[0].key)
|
||||
// 热榜由 worker 在事务提交后写:API 提前加一次就是双计。
|
||||
if got := f.hotScoreAt(t, 7, c.CreatedAt); got != 0 {
|
||||
t.Fatalf("入队成功的路径不得改热榜,实际分数 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +144,8 @@ func TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey(t
|
||||
f := newCommentFixture(t)
|
||||
f.comments.pubErr = errors.New("broker down")
|
||||
|
||||
if err := f.svc.Publish(context.Background(), newComment(7, 1, "hello")); err != nil {
|
||||
c := newComment(7, 1, "hello")
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 1 {
|
||||
@@ -147,25 +155,80 @@ func TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey(t
|
||||
if written == nil || *written == "" {
|
||||
t.Fatal("兜底写入的评论必须带上意图键,否则 worker 侧无法判重")
|
||||
}
|
||||
if got := f.pop.calls[0].key; got != *written {
|
||||
t.Fatalf("兜底写入的键 %q 与热度事件的键 %q 不一致", *written, got)
|
||||
}
|
||||
if f.store.lastDelta != 1 {
|
||||
t.Fatalf("热度增量 = %d, want 1", f.store.lastDelta)
|
||||
}
|
||||
// 事务真的插入了行,热榜才 +1,且落在评论的 created_at 分钟。
|
||||
if got := f.hotScoreAt(t, 7, f.store.lastComment.CreatedAt); got != 1 {
|
||||
t.Fatalf("兜底路径热榜分数 = %v, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 评论事件入队成功、热度发布失败:这是旧代码返回 500 的那条路径。
|
||||
// 现在只降级更新热榜,库由 worker 写,接口返回成功。
|
||||
func TestCommentService_Publish_PopularityPublishFails_AppliesHotCacheOnce(t *testing.T) {
|
||||
// 兜底写入命中唯一索引(created=false)说明这一行早就存在,计数与热榜
|
||||
// 都已经被那次写驱动过:此时再加一次就是重复。
|
||||
func TestCommentService_Publish_FallbackDedupeHit_DoesNotTouchHot(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.pop.pubErr = errors.New("broker down")
|
||||
f.comments.pubErr = errors.New("broker down")
|
||||
f.store.created = false
|
||||
|
||||
if err := f.svc.Publish(context.Background(), newComment(9, 1, "hello")); err != nil {
|
||||
t.Fatalf("Publish 不应失败: %v", err)
|
||||
c := newComment(7, 1, "hello")
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 0 {
|
||||
t.Fatalf("评论已入队,不应直写,实际调用 %d 次", f.store.createCalls)
|
||||
if f.store.createCalls != 1 {
|
||||
t.Fatalf("兜底写入 %d 次, want 1", f.store.createCalls)
|
||||
}
|
||||
if got := f.hotScoreAt(t, 7, c.CreatedAt); got != 0 {
|
||||
t.Fatalf("判重命中时热榜不得变化,实际分数 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 删除入队成功时 API 不碰库:热度回退由 worker 在同一事务后做。
|
||||
func TestCommentService_Delete_Enqueued_SkipsLocalWrite(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1}
|
||||
|
||||
if err := f.svc.Delete(context.Background(), 5, 1); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if f.store.deleteCalls != 0 {
|
||||
t.Fatalf("删除已入队,不得直写库,实际调用 %d 次", f.store.deleteCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 删除事件发不出去时走兜底:删行与热度 -1 都发生,且 -1 落回评论创建的那一分钟
|
||||
// (P2-20:旧实现只删行、不减热度)。
|
||||
func TestCommentService_Delete_FallbackRevertsHotAtOriginalBucket(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.delErr = errors.New("broker down")
|
||||
createdAt := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Minute)
|
||||
f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1}
|
||||
f.store.deleted = true
|
||||
f.store.deleteRow = &Comment{ID: 5, VideoID: 7, AuthorID: 1, CreatedAt: createdAt}
|
||||
|
||||
if err := f.svc.Delete(context.Background(), 5, 1); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if f.store.deleteCalls != 1 {
|
||||
t.Fatalf("兜底删除 %d 次, want 1", f.store.deleteCalls)
|
||||
}
|
||||
if got := f.hotScoreAt(t, 7, createdAt); got != -1 {
|
||||
t.Fatalf("原桶分数 = %v, want -1(回退必须落回创建那一分钟)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 重复删除是空操作:deleted=false 时不能再减一次热度。
|
||||
func TestCommentService_Delete_RepeatIsNoop(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.delErr = errors.New("broker down")
|
||||
f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1}
|
||||
f.store.deleted = false
|
||||
|
||||
if err := f.svc.Delete(context.Background(), 5, 1); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if got := f.hotScoreAt(t, 7, time.Now()); got != 0 {
|
||||
t.Fatalf("重复删除不得改热榜,实际分数 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +19,11 @@ type CommentStore interface {
|
||||
CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (created bool, err error)
|
||||
|
||||
GetByID(ctx context.Context, id uint) (*Comment, error)
|
||||
DeleteComment(ctx context.Context, comment *Comment) error
|
||||
DeleteByID(ctx context.Context, id uint) (deleted bool, err error)
|
||||
|
||||
// DeleteWithPopularity 在同一事务内删除评论并向热度 -1。
|
||||
// 返回被删的行(拿 created_at 落桶);deleted=false 表示空操作。
|
||||
DeleteWithPopularity(ctx context.Context, id uint) (row *Comment, deleted bool, err error)
|
||||
|
||||
GetAllComments(ctx context.Context, videoID uint) ([]Comment, error)
|
||||
|
||||
CreateMentions(ctx context.Context, mentions []Mention) error
|
||||
|
||||
85
backend/internal/video/hot_window.go
Normal file
85
backend/internal/video/hot_window.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
)
|
||||
|
||||
const (
|
||||
// HotWindowMinutes 是热榜窗口覆盖的分钟桶数。读侧按 60 个桶求并集。
|
||||
HotWindowMinutes = 60
|
||||
|
||||
// HotWindowTTL 是单个分钟桶的寿命。
|
||||
//
|
||||
// 它必须大于读窗口(60 分钟):读侧只合并最近 60 个桶,但迟到增量可以
|
||||
// 落在更早的桶里,桶在窗口滑出之前都不该被驱逐。
|
||||
HotWindowTTL = 2 * time.Hour
|
||||
|
||||
// hotOpTimeout 只约束 ZINCRBY / EXPIRE 两次往返。
|
||||
hotOpTimeout = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
// HotBucket 把一个时刻折算成分钟桶名(UTC)。
|
||||
//
|
||||
// 桶名就是那一分钟的起始时刻,落下标一律用行自己的 created_at,
|
||||
// 而不是消费时刻——worker 积压时两者能差几分钟。
|
||||
func HotBucket(t time.Time) string {
|
||||
return t.UTC().Truncate(time.Minute).Format("200601021504")
|
||||
}
|
||||
|
||||
// HotMember 是视频在桶里的成员名。
|
||||
//
|
||||
// 补零到 12 位:ZSET 同分成员按字典序返回,补零后字典序与数值序一致,
|
||||
// 才能和 MySQL 路径的 "ORDER BY score DESC, video_id DESC" 对上。
|
||||
func HotMember(videoID uint) string {
|
||||
return fmt.Sprintf("%012d", videoID)
|
||||
}
|
||||
|
||||
// ApplyHotDelta 把一次互动的增量写进它所属分钟桶。
|
||||
//
|
||||
// occurredAt 是这条互动落库那一行的 created_at:增量必须记在事件发生的
|
||||
// 分钟,不能记在消费者看到它的分钟(否则积压会伪造尖峰)。
|
||||
//
|
||||
// 这里只写派生缓存,失败不回滚任何东西:DB 计数是事实,桶可以由
|
||||
// cmd/reconcile 按 DB 重建。
|
||||
func ApplyHotDelta(ctx context.Context, cache *rediscache.Client, videoID uint, delta int64, occurredAt time.Time) error {
|
||||
if cache == nil || videoID == 0 || delta == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
if occurredAt.IsZero() {
|
||||
// 兼容不带 occurred_at 的旧消息:这时只能按当前时刻落桶。
|
||||
occurredAt = now
|
||||
}
|
||||
if occurredAt.After(now) {
|
||||
// 未来时间戳会落进未来的桶,读窗口永远看不到它。
|
||||
occurredAt = now
|
||||
}
|
||||
if now.Sub(occurredAt) > HotWindowTTL {
|
||||
// 超过桶寿命的增量落下去也马上过期,静默丢弃。
|
||||
return nil
|
||||
}
|
||||
|
||||
// 缓存失效是 best-effort,不进 opCtx 的预算:详情页的热度数字变了,
|
||||
// 但它不该拖慢写路径。
|
||||
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", videoID))
|
||||
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", videoID))
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, hotOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
key := cache.Key("hot:video:1m:%s", HotBucket(occurredAt))
|
||||
if err := cache.ZincrBy(opCtx, key, HotMember(videoID), float64(delta)); err != nil {
|
||||
return fmt.Errorf("hot window: zincrby video=%d delta=%d key=%s: %w", videoID, delta, key, err)
|
||||
}
|
||||
|
||||
if err := cache.Expire(opCtx, key, HotWindowTTL); err != nil {
|
||||
log.Printf("hot window: expire %s failed (non-fatal): %v", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
134
backend/internal/video/hot_window_test.go
Normal file
134
backend/internal/video/hot_window_test.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newTestCache(t *testing.T) (*rediscache.Client, *miniredis.Miniredis) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rediscache.NewClient(rdb, "test:"), mr
|
||||
}
|
||||
|
||||
// 桶名必须是那一分钟的 UTC 起始时刻:非 UTC 时区或未截断都会让同一次
|
||||
// 互动落进不同的桶,-verify 与 -rebuild-hot 也就对不上。
|
||||
func TestHotBucket_TruncatesToUTC(t *testing.T) {
|
||||
at := time.Date(2026, 3, 4, 5, 6, 7, 800_000_000, time.FixedZone("UTC+8", 8*3600))
|
||||
|
||||
got := HotBucket(at)
|
||||
want := "202603032106" // 05:06:07+08:00 == 21:06:07Z,截断到分钟
|
||||
if got != want {
|
||||
t.Fatalf("HotBucket(%v) = %q, want %q", at, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 补零到 12 位让 ZSET 的字典序等同数值序:同分时才能与 DB 的
|
||||
// "ORDER BY score DESC, video_id DESC" 给出同一个顺序。
|
||||
func TestHotMember_PadsToTwelveDigits(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
id uint
|
||||
want string
|
||||
}{
|
||||
{"small", 7, "000000000007"},
|
||||
{"large", 123456789012, "123456789012"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := HotMember(c.id); got != c.want {
|
||||
t.Fatalf("HotMember(%d) = %q, want %q", c.id, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 增量落在 occurredAt 那一分钟,而不是"现在"。
|
||||
// 这是本方案与旧实现的根本区别:积压 10 分钟的 worker 不能把 10 分钟前的
|
||||
// 点赞记成此刻的尖峰。
|
||||
func TestApplyHotDelta_WritesToOccurredBucket(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Minute)
|
||||
|
||||
if err := ApplyHotDelta(context.Background(), cache, 42, 1, at); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
|
||||
key := cache.Key("hot:video:1m:%s", HotBucket(at))
|
||||
if !mr.Exists(key) {
|
||||
t.Fatalf("桶 %s 不存在:增量没有落在 occurredAt 那一分钟", key)
|
||||
}
|
||||
if score, err := mr.ZScore(key, HotMember(42)); err != nil || score != 1 {
|
||||
t.Fatalf("桶内分数 = %v, err = %v, want 1", score, err)
|
||||
}
|
||||
if nowKey := cache.Key("hot:video:1m:%s", HotBucket(time.Now())); mr.Exists(nowKey) {
|
||||
t.Fatalf("增量不得落进当前分钟的桶 %s(那是消费时刻,不是事件时刻)", nowKey)
|
||||
}
|
||||
}
|
||||
|
||||
// 没有 cache(Redis 未启用)时不得报错:调用方是 best-effort 路径,
|
||||
// 让它返回错误会把"本来就没有热榜"的部署变成失败请求。
|
||||
func TestApplyHotDelta_NilCacheIsNoop(t *testing.T) {
|
||||
if err := ApplyHotDelta(context.Background(), nil, 42, 1, time.Now()); err != nil {
|
||||
t.Fatalf("nil cache 不应返回错误: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 超过桶寿命的迟到增量直接丢弃:落下去也会在读到它之前过期,
|
||||
// 留着只会让 -verify 把它当成"应该存在"的桶。
|
||||
func TestApplyHotDelta_StaleBucketIsSkipped(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
at := time.Now().UTC().Add(-HotWindowTTL - time.Minute)
|
||||
|
||||
if err := ApplyHotDelta(context.Background(), cache, 43, 1, at); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
for _, key := range mr.Keys() {
|
||||
t.Fatalf("超期增量不得写入任何桶,却发现 key=%s", key)
|
||||
}
|
||||
}
|
||||
|
||||
// 未来时间戳按当前分钟处理:否则增量会落进读窗口永远到不了的未来桶。
|
||||
func TestApplyHotDelta_FutureTimestampUsesCurrentBucket(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
future := time.Now().UTC().Add(24 * time.Hour)
|
||||
|
||||
if err := ApplyHotDelta(context.Background(), cache, 44, 1, future); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
if mr.Exists(cache.Key("hot:video:1m:%s", HotBucket(future))) {
|
||||
t.Fatal("未来时间戳不得落进未来的桶")
|
||||
}
|
||||
if score, err := mr.ZScore(cache.Key("hot:video:1m:%s", HotBucket(time.Now())), HotMember(44)); err != nil || score != 1 {
|
||||
t.Fatalf("当前分钟桶内分数 = %v, err = %v, want 1", score, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 缓存失效是 best-effort:热度变了,详情与实体缓存里的旧数字必须消失。
|
||||
func TestApplyHotDelta_InvalidatesDetailAndEntity(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
ctx := context.Background()
|
||||
detail := cache.Key("video:detail:id=%d", 46)
|
||||
entity := cache.Key("video:entity:%d", 46)
|
||||
if err := cache.SetBytes(ctx, detail, []byte("x"), time.Hour); err != nil {
|
||||
t.Fatalf("seed detail: %v", err)
|
||||
}
|
||||
if err := cache.SetBytes(ctx, entity, []byte("y"), time.Hour); err != nil {
|
||||
t.Fatalf("seed entity: %v", err)
|
||||
}
|
||||
|
||||
if err := ApplyHotDelta(ctx, cache, 46, 1, time.Now()); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
if mr.Exists(detail) || mr.Exists(entity) {
|
||||
t.Fatalf("详情/实体缓存必须被失效")
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,16 @@ package video
|
||||
|
||||
import "time"
|
||||
|
||||
// Like 的两个索引都承载语义,不能删:
|
||||
// - idx_like_video_account(video_id, account_id,唯一)是 ApplyLike 的判重门闩:
|
||||
// RowsAffected==0 表示这条互动已经存在,计数与热榜都不得再加。
|
||||
// - idx_likes_created_video(created_at, video_id)让热榜窗口查询只走索引,
|
||||
// 不回表。created_at 是事件时间,撤销点赞要减回同一分钟。
|
||||
type Like struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
VideoID uint `gorm:"uniqueIndex:idx_like_video_account;not null" json:"video_id"`
|
||||
VideoID uint `gorm:"uniqueIndex:idx_like_video_account;index:idx_likes_created_video,priority:2;not null" json:"video_id"`
|
||||
AccountID uint `gorm:"uniqueIndex:idx_like_video_account;not null" json:"account_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CreatedAt time.Time `gorm:"index:idx_likes_created_video,priority:1" json:"created_at"`
|
||||
}
|
||||
|
||||
type LikeRequest struct {
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type LikeRepository struct {
|
||||
@@ -16,39 +16,79 @@ func NewLikeRepository(db *gorm.DB) *LikeRepository {
|
||||
return &LikeRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *LikeRepository) Like(ctx context.Context, like *Like) error {
|
||||
return r.db.WithContext(ctx).Create(like).Error
|
||||
}
|
||||
|
||||
func (r *LikeRepository) Unlike(ctx context.Context, like *Like) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).
|
||||
Delete(&Like{}).Error
|
||||
}
|
||||
|
||||
func (r *LikeRepository) LikeIgnoreDuplicate(ctx context.Context, like *Like) (created bool, err error) {
|
||||
// ApplyLike 插入点赞行,并在同一事务里给 likes_count 与 popularity 各 +1。
|
||||
//
|
||||
// created=false 表示这一行本来就在(唯一索引 idx_like_video_account 判重),
|
||||
// 此时计数与热榜都不能再动:重复投递只能算一次。判重交给数据库,不做
|
||||
// "先查再插"——那样并发下必然漏判。
|
||||
//
|
||||
// 注意:DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
|
||||
func (r *LikeRepository) ApplyLike(ctx context.Context, like *Like) (created bool, err error) {
|
||||
if like == nil || like.VideoID == 0 || like.AccountID == 0 {
|
||||
return false, nil
|
||||
}
|
||||
err = r.db.WithContext(ctx).Create(like).Error
|
||||
if err == nil {
|
||||
return true, nil
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(like)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
created = true
|
||||
|
||||
if err := tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count + 1, 0)")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *LikeRepository) DeleteByVideoAndAccount(ctx context.Context, videoID, accountID uint) (deleted bool, err error) {
|
||||
// ApplyUnlike 删除点赞行,并在同一事务里把两个计数各 -1。
|
||||
//
|
||||
// 返回被删的那一行:它的 created_at 是热榜回退时要用的时间。取消点赞必须
|
||||
// 把分数减回点赞那一刻的桶,所以这个值必须来自库里,而不是调用方此刻的钟。
|
||||
// deleted=false 表示没有这一行(重复投递),此时什么都不改。
|
||||
func (r *LikeRepository) ApplyUnlike(ctx context.Context, videoID, accountID uint) (like *Like, deleted bool, err error) {
|
||||
if videoID == 0 || accountID == 0 {
|
||||
return false, nil
|
||||
return nil, false, nil
|
||||
}
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("video_id = ? AND account_id = ?", videoID, accountID).
|
||||
Delete(&Like{})
|
||||
return res.RowsAffected > 0, res.Error
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var row Like
|
||||
if err := tx.Where("video_id = ? AND account_id = ?", videoID, accountID).First(&row).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
res := tx.Delete(&Like{}, row.ID)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
deleted = true
|
||||
like = &row
|
||||
|
||||
if err := tx.Model(&Video{}).Where("id = ?", videoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count - 1, 0)")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", videoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return like, deleted, nil
|
||||
}
|
||||
|
||||
func (r *LikeRepository) IsLiked(ctx context.Context, videoID, accountID uint) (bool, error) {
|
||||
|
||||
118
backend/internal/video/like_repo_integration_test.go
Normal file
118
backend/internal/video/like_repo_integration_test.go
Normal file
@@ -0,0 +1,118 @@
|
||||
//go:build integration
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ApplyLike 是"点赞一行 + 两个计数"的唯一写者:判重、计数、行时间必须在
|
||||
// 同一个事务里一次算清。这里断言的是幂等性与 created_at 的保真——
|
||||
// 后者决定热榜增量落在哪个分钟桶(见 ApplyHotDelta)。
|
||||
|
||||
func TestApplyLike_InsertsAndCountsOnce(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewLikeRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
// 用 10 分钟前的时间,模拟"消息积压后消费":桶必须按行时间落,而不是按消费时刻。
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
|
||||
|
||||
created, err := repo.ApplyLike(ctx, &Like{VideoID: v.ID, AccountID: 7, CreatedAt: at})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyLike: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Fatal("首次点赞必须报告 created=true")
|
||||
}
|
||||
|
||||
var row Like
|
||||
if err := db.Where("video_id = ? AND account_id = ?", v.ID, 7).First(&row).Error; err != nil {
|
||||
t.Fatalf("load like: %v", err)
|
||||
}
|
||||
if !row.CreatedAt.Equal(at) {
|
||||
t.Fatalf("created_at = %v, want %v(热榜桶按行时间落)", row.CreatedAt.UTC(), at)
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1", got.LikesCount, got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyLike_DuplicateDoesNotCount(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewLikeRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
like := &Like{VideoID: v.ID, AccountID: 7, CreatedAt: time.Now().UTC()}
|
||||
if created, err := repo.ApplyLike(ctx, like); err != nil || !created {
|
||||
t.Fatalf("首次 ApplyLike = created:%v err:%v", created, err)
|
||||
}
|
||||
// 同一账户重复投递:唯一索引吸收,计数不得再动。
|
||||
created, err := repo.ApplyLike(ctx, &Like{VideoID: v.ID, AccountID: 7, CreatedAt: time.Now().UTC()})
|
||||
if err != nil {
|
||||
t.Fatalf("重复 ApplyLike: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Fatal("重复点赞必须报告 created=false")
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1(判重命中不得计数)", got.LikesCount, got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyUnlike_RestoresOriginalBucket(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewLikeRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 2)
|
||||
|
||||
// 点赞发生在 20 分钟前的桶:取消时必须把 -1 记回同一分钟。
|
||||
likedAt := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)
|
||||
if created, err := repo.ApplyLike(ctx, &Like{VideoID: v.ID, AccountID: 7, CreatedAt: likedAt}); err != nil || !created {
|
||||
t.Fatalf("seed ApplyLike = created:%v err:%v", created, err)
|
||||
}
|
||||
|
||||
row, deleted, err := repo.ApplyUnlike(ctx, v.ID, 7)
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyUnlike: %v", err)
|
||||
}
|
||||
if !deleted {
|
||||
t.Fatal("首次取消点赞必须报告 deleted=true")
|
||||
}
|
||||
if row == nil || !row.CreatedAt.Equal(likedAt) {
|
||||
t.Fatalf("返回行 = %+v, want created_at=%v(-1 要落回点赞那一分钟)", row, likedAt)
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 0 || got.Popularity != 2 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 0/2", got.LikesCount, got.Popularity)
|
||||
}
|
||||
|
||||
// 重复投递:行已不在,空操作。
|
||||
if _, deleted, err := repo.ApplyUnlike(ctx, v.ID, 7); err != nil || deleted {
|
||||
t.Fatalf("重复 ApplyUnlike = deleted:%v err:%v, want false/nil", deleted, err)
|
||||
}
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 0 || got.Popularity != 2 {
|
||||
t.Fatalf("重复取消后 likes_count=%d popularity=%d, want 0/2", got.LikesCount, got.Popularity)
|
||||
}
|
||||
}
|
||||
@@ -7,26 +7,17 @@ import (
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LikeService struct {
|
||||
repo *LikeRepository
|
||||
VideoRepo *VideoRepository
|
||||
cache *rediscache.Client
|
||||
likeMQ *rabbitmq.LikeMQ
|
||||
popularityMQ *rabbitmq.PopularityMQ
|
||||
repo *LikeRepository
|
||||
VideoRepo *VideoRepository
|
||||
cache *rediscache.Client
|
||||
likeMQ *rabbitmq.LikeMQ
|
||||
}
|
||||
|
||||
func NewLikeService(repo *LikeRepository, videoRepo *VideoRepository, cache *rediscache.Client, likeMQ *rabbitmq.LikeMQ, popularityMQ *rabbitmq.PopularityMQ) *LikeService {
|
||||
return &LikeService{repo: repo, VideoRepo: videoRepo, cache: cache, likeMQ: likeMQ, popularityMQ: popularityMQ}
|
||||
}
|
||||
|
||||
func isDupKey(err error) bool {
|
||||
var me *mysql.MySQLError
|
||||
return errors.As(err, &me) && me.Number == 1062
|
||||
func NewLikeService(repo *LikeRepository, videoRepo *VideoRepository, cache *rediscache.Client, likeMQ *rabbitmq.LikeMQ) *LikeService {
|
||||
return &LikeService{repo: repo, VideoRepo: videoRepo, cache: cache, likeMQ: likeMQ}
|
||||
}
|
||||
|
||||
func (s *LikeService) Like(ctx context.Context, like *Like) error {
|
||||
@@ -57,58 +48,35 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
|
||||
|
||||
like.CreatedAt = time.Now()
|
||||
|
||||
// 同一个键喂给点赞事件与热度事件,两条消费端各自去重。
|
||||
// 意图键只用于日志关联(LikeEvent.EventID),不再参与去重:
|
||||
// 判重由 likes 的唯一索引在事务里做,重复投递不会重复计数。
|
||||
intentKey, err := NewIntentKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
likeEnqueued := false
|
||||
popEnqueued := false
|
||||
enqueued := false
|
||||
if s.likeMQ != nil {
|
||||
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err == nil {
|
||||
likeEnqueued = true
|
||||
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err != nil {
|
||||
log.Printf("like: enqueue like failed, fallback to direct write: %v", err)
|
||||
} else {
|
||||
enqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, like.VideoID, 1, intentKey); err == nil {
|
||||
popEnqueued = true
|
||||
}
|
||||
if enqueued {
|
||||
// 入队成功即返回:落库与热榜都由 worker 在同一条事务路径上完成。
|
||||
return nil
|
||||
}
|
||||
|
||||
// 两条轨各自独立降级:合并判断会在"点赞已入队、热度失败"时再插一次 likes,
|
||||
// 撞 idx_like_video_account 并返回 500。
|
||||
if !likeEnqueued {
|
||||
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Select("id").First(&Video{}, like.VideoID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("video not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(like).Error; err != nil {
|
||||
if isDupKey(err) {
|
||||
return errors.New("user has liked this video")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("likes_count + 1")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
created, err := s.repo.ApplyLike(ctx, like)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 热度是展示数据:写失败只降级记日志,不回滚已经成立的点赞。
|
||||
if !popEnqueued {
|
||||
if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, 1, intentKey); err != nil {
|
||||
log.Printf("like: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
|
||||
}
|
||||
if !created {
|
||||
return errors.New("user has liked this video")
|
||||
}
|
||||
if err := ApplyHotDelta(ctx, s.cache, like.VideoID, 1, like.CreatedAt); err != nil {
|
||||
log.Printf("like: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -144,46 +112,28 @@ func (s *LikeService) Unlike(ctx context.Context, like *Like) error {
|
||||
return err
|
||||
}
|
||||
|
||||
likeEnqueued := false
|
||||
popEnqueued := false
|
||||
enqueued := false
|
||||
if s.likeMQ != nil {
|
||||
if err := s.likeMQ.Unlike(ctx, like.AccountID, like.VideoID, intentKey); err == nil {
|
||||
likeEnqueued = true
|
||||
if err := s.likeMQ.Unlike(ctx, like.AccountID, like.VideoID, intentKey); err != nil {
|
||||
log.Printf("unlike: enqueue unlike failed, fallback to direct write: %v", err)
|
||||
} else {
|
||||
enqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, like.VideoID, -1, intentKey); err == nil {
|
||||
popEnqueued = true
|
||||
}
|
||||
if enqueued {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 与 Like 对称:两条轨各自降级,不做合并判断。
|
||||
if !likeEnqueued {
|
||||
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
del := tx.Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).Delete(&Like{})
|
||||
if del.Error != nil {
|
||||
return del.Error
|
||||
}
|
||||
if del.RowsAffected == 0 {
|
||||
return errors.New("user has not liked this video")
|
||||
}
|
||||
|
||||
if err := tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count - 1, 0)")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row, deleted, err := s.repo.ApplyUnlike(ctx, like.VideoID, like.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !popEnqueued {
|
||||
if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, -1, intentKey); err != nil {
|
||||
log.Printf("unlike: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
|
||||
}
|
||||
if !deleted {
|
||||
return errors.New("user has not liked this video")
|
||||
}
|
||||
// 减回点赞那一分钟:热榜是窗口,不能按此刻的钟回退。
|
||||
if err := ApplyHotDelta(ctx, s.cache, like.VideoID, -1, row.CreatedAt); err != nil {
|
||||
log.Printf("unlike: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
)
|
||||
|
||||
const (
|
||||
// hotAppliedTTL 覆盖同一次意图的重复投递窗口。
|
||||
hotAppliedTTL = 2 * time.Hour
|
||||
hotWindowTTL = 2 * time.Hour
|
||||
// hotOpTimeout 只约束 SetNX / ZINCRBY / EXPIRE 三次往返。
|
||||
hotOpTimeout = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
// UpdatePopularityCache 给视频的分钟窗口热度加 change。
|
||||
//
|
||||
// intentKey 非空时先抢 hot:applied:<intentKey> 占位,抢不到说明该意图
|
||||
// 已生效,直接返回 nil。ZINCRBY 失败必须撤销占位,否则这次增量会被
|
||||
// 永久跳过。
|
||||
func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uint, change int64, intentKey string) error {
|
||||
if cache == nil || id == 0 || change == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, hotOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
marker := ""
|
||||
if intentKey != "" {
|
||||
marker = cache.Key("hot:applied:%s", intentKey)
|
||||
claimed, err := cache.SetNX(opCtx, marker, []byte("1"), hotAppliedTTL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hot cache: claim intent %q: %w", intentKey, err)
|
||||
}
|
||||
if !claimed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 缓存失效是 best-effort,不计入 opCtx 预算。
|
||||
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id))
|
||||
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", id))
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Minute)
|
||||
windowKey := cache.Key("hot:video:1m:%s", now.Format("200601021504"))
|
||||
member := strconv.FormatUint(uint64(id), 10)
|
||||
|
||||
if err := cache.ZincrBy(opCtx, windowKey, member, float64(change)); err != nil {
|
||||
if marker != "" {
|
||||
if delErr := cache.Del(context.Background(), marker); delErr != nil {
|
||||
log.Printf("hot cache: revoke intent marker %s failed: %v", marker, delErr)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("hot cache: zincrby video=%d change=%d: %w", id, change, err)
|
||||
}
|
||||
|
||||
if err := cache.Expire(opCtx, windowKey, hotWindowTTL); err != nil {
|
||||
log.Printf("hot cache: expire %s failed (non-fatal): %v", windowKey, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newTestCache(t *testing.T) (*rediscache.Client, *miniredis.Miniredis) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rediscache.NewClient(rdb, "test:"), mr
|
||||
}
|
||||
|
||||
// hotScore 汇总所有分钟窗口里某个视频的分数。
|
||||
//
|
||||
// 不直接构造 windowKey:那会把测试和"窗口按分钟切分"这一实现细节绑死,
|
||||
// 而我们要断言的是"这条意图到底加了几次分"。
|
||||
func hotScore(t *testing.T, mr *miniredis.Miniredis, id uint) float64 {
|
||||
t.Helper()
|
||||
member := strconv.FormatUint(uint64(id), 10)
|
||||
var sum float64
|
||||
for _, key := range mr.Keys() {
|
||||
if !strings.Contains(key, "hot:video:1m:") {
|
||||
continue
|
||||
}
|
||||
if !mr.Exists(key) {
|
||||
continue
|
||||
}
|
||||
if v, err := mr.ZScore(key, member); err == nil {
|
||||
sum += v
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
// 同一条意图重复调用只能加一次分:这是"双倍热度"的直接对手。
|
||||
func TestUpdatePopularityCache_SecondCallIsNoop(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
ctx := context.Background()
|
||||
key := "intent-heat-1"
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := UpdatePopularityCache(ctx, cache, 42, 1, key); err != nil {
|
||||
t.Fatalf("第 %d 次调用: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
if got := hotScore(t, mr, 42); got != 1 {
|
||||
t.Fatalf("热度 = %v, want 1(同一意图键只能生效一次)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 没有意图键时必须每次都生效:这是点赞兜底路径,调用方已经确保
|
||||
// "只有发不出去才走到这里",在这里再去重会把真实增量吞掉。
|
||||
func TestUpdatePopularityCache_EmptyKeyAppliesEveryTime(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := UpdatePopularityCache(ctx, cache, 43, 1, ""); err != nil {
|
||||
t.Fatalf("第 %d 次调用: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
if got := hotScore(t, mr, 43); got != 2 {
|
||||
t.Fatalf("热度 = %v, want 2(无意图键不参与去重)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 占位必须与"加分成功"同生共死:加分失败却留下占位,会让这次增量被
|
||||
// 永久跳过——比重复加分更难发现(用户只会觉得"热度不动了")。
|
||||
type failZincrByHook struct {
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (h *failZincrByHook) DialHook(next goredis.DialHook) goredis.DialHook { return next }
|
||||
|
||||
func (h *failZincrByHook) ProcessHook(next goredis.ProcessHook) goredis.ProcessHook {
|
||||
return func(ctx context.Context, cmd goredis.Cmder) error {
|
||||
if h.fail && strings.EqualFold(cmd.Name(), "zincrby") {
|
||||
return errors.New("injected zincrby failure")
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *failZincrByHook) ProcessPipelineHook(next goredis.ProcessPipelineHook) goredis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
|
||||
func TestUpdatePopularityCache_MarkerRevokedOnFailure(t *testing.T) {
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
hook := &failZincrByHook{fail: true}
|
||||
rdb.AddHook(hook)
|
||||
cache := rediscache.NewClient(rdb, "test:")
|
||||
ctx := context.Background()
|
||||
key := "intent-heat-2"
|
||||
|
||||
if err := UpdatePopularityCache(ctx, cache, 44, 1, key); err == nil {
|
||||
t.Fatal("ZINCRBY 失败时 UpdatePopularityCache 必须返回 error(否则消费端无法重试)")
|
||||
}
|
||||
|
||||
// 故障恢复后重试同一条意图:占位已被撤销,这次必须真的加上。
|
||||
hook.fail = false
|
||||
if err := UpdatePopularityCache(ctx, cache, 44, 1, key); err != nil {
|
||||
t.Fatalf("故障恢复后重试: %v", err)
|
||||
}
|
||||
if got := hotScore(t, mr, 44); got != 1 {
|
||||
t.Fatalf("热度 = %v, want 1(失败后占位必须被撤销)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 降级路径:没有 cache(Redis 未启用)时不得报错,否则热度事件会被
|
||||
// 无限重投直到停泊——一个"本来就没有热榜"的部署会凭空产生死信。
|
||||
func TestUpdatePopularityCache_NilCacheIsNoop(t *testing.T) {
|
||||
if err := UpdatePopularityCache(context.Background(), nil, 45, 1, "k"); err != nil {
|
||||
t.Fatalf("nil cache 不应返回错误: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 缓存失效是 best-effort:它不在 opCtx 的预算里,也不阻塞主流程。
|
||||
func TestUpdatePopularityCache_InvalidatesDetailAndEntityKeys(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
ctx := context.Background()
|
||||
detail := cache.Key("video:detail:id=%d", 46)
|
||||
entity := cache.Key("video:entity:%d", 46)
|
||||
if err := cache.SetBytes(ctx, detail, []byte("x"), time.Hour); err != nil {
|
||||
t.Fatalf("seed detail: %v", err)
|
||||
}
|
||||
if err := cache.SetBytes(ctx, entity, []byte("y"), time.Hour); err != nil {
|
||||
t.Fatalf("seed entity: %v", err)
|
||||
}
|
||||
|
||||
if err := UpdatePopularityCache(ctx, cache, 46, 1, "intent-heat-3"); err != nil {
|
||||
t.Fatalf("UpdatePopularityCache: %v", err)
|
||||
}
|
||||
if mr.Exists(detail) || mr.Exists(entity) {
|
||||
t.Fatalf("详情/实体缓存必须被失效")
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,10 @@ type VideoService struct {
|
||||
cacheTTL time.Duration
|
||||
}
|
||||
|
||||
// NewVideoService 不再接收 popularityMQ:热度写入只有两个入口——
|
||||
// PopularityWorker(异步)与 LikeService/CommentService 的兜底路径,
|
||||
// 视频服务从来不直接改热度。原来这里挂着一个没人调用的 UpdatePopularity,
|
||||
// 它是热度写入的第三份实现,且漏删 video:entity 缓存(P0-4 的 N3)。
|
||||
// NewVideoService 不涉及热度写入:likes_count / popularity 只由点赞与评论的
|
||||
// 业务事务维护(LikeRepository.ApplyLike、CommentRepository.CreateIdempotentWithPopularity、
|
||||
// DeleteWithPopularity),视频服务从来不直接改热度。原来这里挂着一个没人调用的
|
||||
// UpdatePopularity,它是热度写入的第三份实现,且漏删 video:entity 缓存(P0-4 的 N3)。
|
||||
func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService {
|
||||
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute}
|
||||
}
|
||||
|
||||
@@ -25,12 +25,6 @@ func (failingCommentPublisher) Delete(context.Context, uint, string) error {
|
||||
return errors.New("mq publish failed")
|
||||
}
|
||||
|
||||
type failingPopularityPublisher struct{}
|
||||
|
||||
func (failingPopularityPublisher) Update(context.Context, uint, int64, string) error {
|
||||
return errors.New("mq publish failed")
|
||||
}
|
||||
|
||||
// P0-4 的原始缺陷是"兜底直写一次 + 消费者再写一次",结果是两条评论、双倍热度。
|
||||
// 这个用例把两条路径接起来跑:先让服务层兜底写入,再让同一个意图键的事件到达
|
||||
// worker。断言收敛到一行评论、热度恰为 1。
|
||||
@@ -45,10 +39,8 @@ func TestP0_4_FallbackAndWorkerConvergeToOneComment(t *testing.T) {
|
||||
|
||||
commentRepo := video.NewCommentRepository(db)
|
||||
videoRepo := video.NewVideoRepository(db)
|
||||
svc := video.NewCommentService(
|
||||
commentRepo, videoRepo, nil,
|
||||
failingCommentPublisher{}, failingPopularityPublisher{},
|
||||
)
|
||||
// cache 传 nil:热榜是 best-effort 派生数据,本用例只断言 DB 侧的收敛。
|
||||
svc := video.NewCommentService(commentRepo, videoRepo, nil, failingCommentPublisher{})
|
||||
|
||||
intentKey := "converge-intent-0001"
|
||||
comment := &video.Comment{
|
||||
@@ -66,7 +58,7 @@ func TestP0_4_FallbackAndWorkerConvergeToOneComment(t *testing.T) {
|
||||
}
|
||||
|
||||
// 消息其实已到 broker,稍后由消费者处理同一个意图键。
|
||||
w := NewCommentWorker(nil, nil, commentRepo, videoRepo, rabbitmq.CommentQueue)
|
||||
w := NewCommentWorker(nil, nil, commentRepo, videoRepo, nil, rabbitmq.CommentQueue)
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
EventID: intentKey,
|
||||
Action: "publish",
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
@@ -19,11 +20,12 @@ type CommentWorker struct {
|
||||
parker rabbitmq.Parker
|
||||
comments video.CommentStore
|
||||
videos *video.VideoRepository
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewCommentWorker(ch *amqp.Channel, parker rabbitmq.Parker, comments video.CommentStore, videos *video.VideoRepository, queue string) *CommentWorker {
|
||||
return &CommentWorker{ch: ch, parker: parker, comments: comments, videos: videos, queue: queue}
|
||||
func NewCommentWorker(ch *amqp.Channel, parker rabbitmq.Parker, comments video.CommentStore, videos *video.VideoRepository, cache *rediscache.Client, queue string) *CommentWorker {
|
||||
return &CommentWorker{ch: ch, parker: parker, comments: comments, videos: videos, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *CommentWorker) Run(ctx context.Context) error {
|
||||
@@ -71,6 +73,10 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
|
||||
VideoID: evt.VideoID,
|
||||
AuthorID: evt.AuthorID,
|
||||
Content: strings.TrimSpace(evt.Content),
|
||||
// 行时间来自事件:桶必须落在评论发生的那一分钟。
|
||||
// 事件没带时间时保持零值,由 GORM 的 autoCreateTime 补当前时刻,
|
||||
// 并回填到这个字段,因此下面的落桶仍与行一致。
|
||||
CreatedAt: evt.OccurredAt,
|
||||
}
|
||||
// event_id 即意图键:API 已直写时这里会命中唯一索引。
|
||||
if evt.EventID != "" {
|
||||
@@ -85,6 +91,11 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
|
||||
if !created {
|
||||
log.Printf("comment worker: dedupe=hit event_id=%s video_id=%d author_id=%d",
|
||||
evt.EventID, evt.VideoID, evt.AuthorID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, c.VideoID, 1, c.CreatedAt); err != nil {
|
||||
log.Printf("comment worker: hot window update failed video=%d: %v", c.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -93,13 +104,18 @@ func (w *CommentWorker) applyDelete(ctx context.Context, evt *rabbitmq.CommentEv
|
||||
if evt == nil || evt.CommentID == 0 {
|
||||
return rabbitmq.Permanent(errors.New("comment worker: invalid delete event: comment_id is required"))
|
||||
}
|
||||
deleted, err := w.comments.DeleteByID(ctx, evt.CommentID)
|
||||
deleted, ok, err := w.comments.DeleteWithPopularity(ctx, evt.CommentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
// 重复投递的删除是空操作,不是错误。
|
||||
if !ok {
|
||||
// 重复投递的删除是空操作,不是错误;热度也不能再减一次。
|
||||
log.Printf("comment worker: comment already deleted id=%d event_id=%s", evt.CommentID, evt.EventID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, deleted.VideoID, -1, deleted.CreatedAt); err != nil {
|
||||
log.Printf("comment worker: hot window update failed comment_id=%d: %v", evt.CommentID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 评论消费者"只写一次评论、不再碰热度"这条不变式只能在真实 MySQL 上验证:
|
||||
// 评论消费者"只写一次评论、热度跟着事务走"这条不变式只能在真实 MySQL 上验证:
|
||||
// 判重落在唯一索引 (author_id, idempotency_key) 上,没有数据库就没有被测对象。
|
||||
//
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
@@ -37,10 +37,10 @@ func newCommentWorkerTestDB(t *testing.T) *gorm.DB {
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&video.Comment{}, &video.Video{}); err != nil {
|
||||
if err := db.Migrator().DropTable(&video.Comment{}, &video.Like{}, &video.Video{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&video.Video{}, &video.Comment{}); err != nil {
|
||||
if err := db.AutoMigrate(&video.Video{}, &video.Comment{}, &video.Like{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
@@ -67,12 +67,11 @@ func seedCommentVideo(t *testing.T, db *gorm.DB) *video.Video {
|
||||
//
|
||||
// 两个断言分别钉住两件不同的事:行数 = 1 证明唯一索引吸收了重复;热度 = 1
|
||||
// (而不是 2)证明"加热度"与"插入评论"在同一个事务里、且以 created 为门控。
|
||||
// 热度写在这里而不是 Redis,是因为 videos.popularity 与 comments 必须原子
|
||||
// 提交——Redis 那条轨由 popularity 事件单独负责。
|
||||
// 热度写在这里而不是 Redis,是因为 videos.popularity 是事实,热榜只是它的滑窗副本。
|
||||
func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events")
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), nil, "comment.events")
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
EventID: "evt-comment-1",
|
||||
Action: "publish",
|
||||
@@ -110,7 +109,7 @@ func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) {
|
||||
func TestCommentWorker_ApplyPublish_EmptyEventIDStillWrites(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events")
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), nil, "comment.events")
|
||||
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
Action: "publish",
|
||||
@@ -137,10 +136,10 @@ func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
repo := video.NewCommentRepository(db)
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), "comment.events")
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), nil, "comment.events")
|
||||
|
||||
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
|
||||
if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 0); err != nil {
|
||||
if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 1); err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
|
||||
@@ -158,4 +157,12 @@ func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) {
|
||||
if count != 0 {
|
||||
t.Fatalf("评论行数 = %d, want 0", count)
|
||||
}
|
||||
// P2-20:删除必须回退热度,且只回退一次(第二次删除是空操作)。
|
||||
var got video.Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 0 {
|
||||
t.Fatalf("popularity = %d, want 0(删除要回退热度,重复删除不得再减)", got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
@@ -18,11 +20,12 @@ type LikeWorker struct {
|
||||
parker rabbitmq.Parker
|
||||
likes *video.LikeRepository
|
||||
videos *video.VideoRepository
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewLikeWorker(ch *amqp.Channel, parker rabbitmq.Parker, likes *video.LikeRepository, videos *video.VideoRepository, queue string) *LikeWorker {
|
||||
return &LikeWorker{ch: ch, parker: parker, likes: likes, videos: videos, queue: queue}
|
||||
func NewLikeWorker(ch *amqp.Channel, parker rabbitmq.Parker, likes *video.LikeRepository, videos *video.VideoRepository, cache *rediscache.Client, queue string) *LikeWorker {
|
||||
return &LikeWorker{ch: ch, parker: parker, likes: likes, videos: videos, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) Run(ctx context.Context) error {
|
||||
@@ -48,16 +51,16 @@ func (w *LikeWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
|
||||
switch evt.Action {
|
||||
case "like":
|
||||
return w.applyLike(ctx, evt.UserID, evt.VideoID)
|
||||
return w.applyLike(ctx, evt)
|
||||
case "unlike":
|
||||
return w.applyUnlike(ctx, evt.UserID, evt.VideoID)
|
||||
return w.applyUnlike(ctx, evt)
|
||||
default:
|
||||
return rabbitmq.Permanent(fmt.Errorf("like worker: unknown action %q", evt.Action))
|
||||
}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) applyLike(ctx context.Context, userID, videoID uint) error {
|
||||
ok, err := w.videos.IsExist(ctx, videoID)
|
||||
func (w *LikeWorker) applyLike(ctx context.Context, evt rabbitmq.LikeEvent) error {
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -66,27 +69,37 @@ func (w *LikeWorker) applyLike(ctx context.Context, userID, videoID uint) error
|
||||
return nil
|
||||
}
|
||||
|
||||
created, err := w.likes.LikeIgnoreDuplicate(ctx, &video.Like{
|
||||
VideoID: videoID,
|
||||
AccountID: userID,
|
||||
CreatedAt: time.Now(),
|
||||
// 行时间来自消息:积压的 worker 必须把增量记在事件发生的那一分钟,
|
||||
// 不能记在它被消费的那一分钟。旧的告警消息没有 occurred_at,退回当前时刻。
|
||||
at := evt.OccurredAt
|
||||
if at.IsZero() {
|
||||
at = time.Now()
|
||||
}
|
||||
|
||||
// 插行与两个计数在同一个事务里,不再有"点赞成功、计数少 1"的中间态。
|
||||
created, err := w.likes.ApplyLike(ctx, &video.Like{
|
||||
VideoID: evt.VideoID,
|
||||
AccountID: evt.UserID,
|
||||
CreatedAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !created {
|
||||
// 重复投递:点赞已存在,计数不能再加。
|
||||
// 重复投递:点赞已存在,计数与热榜都不能再加。
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.videos.ChangeLikesCount(ctx, videoID, 1); err != nil {
|
||||
return err
|
||||
// 热榜是派生数据。写失败不回滚点赞(I1 只看 DB),只留痕:
|
||||
// -verify 能发现这个桶偏少,-rebuild-hot 能把它建回来。
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, evt.VideoID, 1, at); err != nil {
|
||||
log.Printf("like worker: hot window update failed video=%d: %v", evt.VideoID, err)
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, videoID, 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) error {
|
||||
ok, err := w.videos.IsExist(ctx, videoID)
|
||||
func (w *LikeWorker) applyUnlike(ctx context.Context, evt rabbitmq.LikeEvent) error {
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -94,16 +107,18 @@ func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
deleted, err := w.likes.DeleteByVideoAndAccount(ctx, videoID, userID)
|
||||
row, deleted, err := w.likes.ApplyUnlike(ctx, evt.VideoID, evt.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
// 重复投递:行已经不在了,热度也不能再减。
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.videos.ChangeLikesCount(ctx, videoID, -1); err != nil {
|
||||
return err
|
||||
// 减回点赞那一刻的桶:热榜是滑窗,按消费时刻减会留下一个永远偏高的旧桶。
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, evt.VideoID, -1, row.CreatedAt); err != nil {
|
||||
log.Printf("like worker: hot window update failed video=%d: %v", evt.VideoID, err)
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, videoID, -1)
|
||||
return nil
|
||||
}
|
||||
|
||||
133
backend/internal/worker/likeworker_integration_test.go
Normal file
133
backend/internal/worker/likeworker_integration_test.go
Normal file
@@ -0,0 +1,133 @@
|
||||
//go:build integration
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 热榜增量必须由"事务是否真的插入"驱动,而不是由消息驱动:
|
||||
// 重投一次不能再加一次分,否则同一次点赞会在榜上加两次。
|
||||
func newLikeWorkerCache(t *testing.T) (*rediscache.Client, *miniredis.Miniredis) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rediscache.NewClient(rdb, "test:"), mr
|
||||
}
|
||||
|
||||
func hotScore(t *testing.T, cache *rediscache.Client, mr *miniredis.Miniredis, videoID uint, at time.Time) float64 {
|
||||
t.Helper()
|
||||
score, err := mr.ZScore(cache.Key("hot:video:1m:%s", video.HotBucket(at)), video.HotMember(videoID))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func reloadVideo(t *testing.T, db *gorm.DB, id uint) video.Video {
|
||||
t.Helper()
|
||||
var v video.Video
|
||||
if err := db.First(&v, id).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestLikeWorker_ReplayDoesNotDoubleHot(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
w := NewLikeWorker(nil, nil, video.NewLikeRepository(db), video.NewVideoRepository(db), cache, "like.events")
|
||||
|
||||
// 10 分钟前发生的点赞,10 分钟后才被消费:桶要按 OccurredAt 落。
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
|
||||
evt := &rabbitmq.LikeEvent{EventID: "evt-like-1", Action: "like", UserID: 7, VideoID: v.ID, OccurredAt: at}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyLike(context.Background(), *evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyLike: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1(重投不得再计数)", got.LikesCount, got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, at); score != 1 {
|
||||
t.Fatalf("热榜分数 = %v, want 1(重投不得再加一次分)", score)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLikeWorker_UnlikeRevertsOriginalBucket(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
w := NewLikeWorker(nil, nil, video.NewLikeRepository(db), video.NewVideoRepository(db), cache, "like.events")
|
||||
|
||||
at := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)
|
||||
if err := w.applyLike(context.Background(), rabbitmq.LikeEvent{EventID: "e1", Action: "like", UserID: 7, VideoID: v.ID, OccurredAt: at}); err != nil {
|
||||
t.Fatalf("applyLike: %v", err)
|
||||
}
|
||||
|
||||
// 取消事件的重投也要是空操作,且 -1 落回点赞那一分钟。
|
||||
unlike := &rabbitmq.LikeEvent{EventID: "e2", Action: "unlike", UserID: 7, VideoID: v.ID}
|
||||
if err := w.applyUnlike(context.Background(), *unlike); err != nil {
|
||||
t.Fatalf("applyUnlike: %v", err)
|
||||
}
|
||||
if err := w.applyUnlike(context.Background(), *unlike); err != nil {
|
||||
t.Fatalf("重复 applyUnlike: %v", err)
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.LikesCount != 0 || got.Popularity != 0 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 0/0", got.LikesCount, got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, at); score != 0 {
|
||||
t.Fatalf("原桶分数 = %v, want 0(+1 与 -1 落在同一分钟)", score)
|
||||
}
|
||||
}
|
||||
|
||||
// P2-20:删除评论时必须把热度 -1 记回评论创建的那一分钟。
|
||||
func TestCommentWorker_DeleteRevertsHot(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
repo := video.NewCommentRepository(db)
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), cache, "comment.events")
|
||||
|
||||
createdAt := time.Now().UTC().Add(-15 * time.Minute).Truncate(time.Second)
|
||||
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x", CreatedAt: createdAt}
|
||||
if created, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 1); err != nil || !created {
|
||||
t.Fatalf("seed comment = created:%v err:%v", created, err)
|
||||
}
|
||||
// 用真实行时间模拟"发布时已经加过一分"。
|
||||
if err := video.ApplyHotDelta(context.Background(), cache, v.ID, 1, createdAt); err != nil {
|
||||
t.Fatalf("seed hot delta: %v", err)
|
||||
}
|
||||
|
||||
evt := &rabbitmq.CommentEvent{EventID: "evt-del-1", Action: "delete", CommentID: c.ID}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyDelete(context.Background(), evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyDelete: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.Popularity != 0 {
|
||||
t.Fatalf("popularity = %d, want 0(删除回退一次,重投不再减)", got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, createdAt); score != 0 {
|
||||
t.Fatalf("原桶分数 = %v, want 0(-1 必须落回创建那一分钟)", score)
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type PopularityWorker struct {
|
||||
ch *amqp.Channel
|
||||
parker rabbitmq.Parker
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewPopularityWorker(ch *amqp.Channel, parker rabbitmq.Parker, cache *rediscache.Client, queue string) *PopularityWorker {
|
||||
return &PopularityWorker{ch: ch, parker: parker, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil {
|
||||
return errors.New("popularity worker is not initialized")
|
||||
}
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
var evt rabbitmq.PopularityEvent
|
||||
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("popularity worker: decode event: %w", err))
|
||||
}
|
||||
if evt.VideoID == 0 || evt.Change == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("popularity worker: invalid event video_id=%d change=%d", evt.VideoID, evt.Change))
|
||||
}
|
||||
// 必须把错误上抛,否则重试分支是死代码。
|
||||
return video.UpdatePopularityCache(ctx, w.cache, evt.VideoID, evt.Change, evt.EventID)
|
||||
}
|
||||
Reference in New Issue
Block a user