feat(video): 评论写路径按意图键幂等,HTTP 回显 request_id
同一条用户意图(同 author_id + request_id)在 comments 上只落一行: 唯一索引 uk_comments_author_key 是唯一的判重点,API 与 Worker 共用 同一个键,因此「MQ 假失败后兜底直写」与「消息稍后被消费」不再双写。 - comment_service: 引入 CommentStore/CommentPublisher/PopularityPublisher 三个最小接口;Publish 先解析意图键,再把同一个键喂给评论事件、热度事件 与兜底直写。只有评论事件没入队时才直写(闸 1),热度兜底独立门控。 - comment_repo: CreateIdempotentWithPopularity 在单事务内插入评论并按 created 门控 videos.popularity;CreateMentions 显式补 CreatedAt 并按 dedupe_key 去重;FindAccountIDs 一次 username IN ? 批量解析。 - commentworker: applyPublish 用 event_id 作幂等键并交给同一个事务, !created 记 dedupe=hit;applyDelete 改 DeleteByID,重复删除是空操作。 - comment_handler: 接收 request_id、响应回显,不返回评论 ID(MQ 路径上 评论此刻可能尚未落库)。 - 提及通知带上绑定到意图键的 dedupe_key,重复投递只写一条。 验证:go test ./... 全绿;-tags integration 下 3 个用例在真实 MySQL 上 通过(重复事件 1 行评论 + 热度只加 1、空 event_id 落 NULL 键、重复删除)
This commit is contained in:
@@ -3,95 +3,137 @@ package video
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"fmt"
|
||||
"log"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
)
|
||||
|
||||
// CommentPublisher 只暴露评论服务用得到的两个动作。
|
||||
//
|
||||
// 用接口而不是具体类型,是为了让"发布失败"成为可注入的场景:P0-4 的全部
|
||||
// 分支都取决于"这条消息到底发出去了没有",而这恰恰是真实 broker 最难稳定
|
||||
// 复现的状态。
|
||||
//
|
||||
// 注意:nil 指针装进接口后 != nil 依然为 true,所以真实实现必须在 nil
|
||||
// 接收者上返回 error(commentMQ.go 现状已如此)。
|
||||
type CommentPublisher interface {
|
||||
Publish(ctx context.Context, evt rabbitmq.CommentEvent) error
|
||||
Delete(ctx context.Context, commentID uint, intentKey string) error
|
||||
}
|
||||
|
||||
// PopularityPublisher 是热度事件的最小接口。
|
||||
type PopularityPublisher interface {
|
||||
Update(ctx context.Context, videoID uint, change int64, intentKey string) error
|
||||
}
|
||||
|
||||
// videoExister 只暴露 CommentService 需要的那一个方法。
|
||||
// *VideoRepository 天然满足它,因此 router.go 的构造代码不需要改。
|
||||
type videoExister interface {
|
||||
IsExist(ctx context.Context, id uint) (bool, error)
|
||||
}
|
||||
|
||||
type CommentService struct {
|
||||
repo *CommentRepository
|
||||
VideoRepository *VideoRepository
|
||||
cache *rediscache.Client
|
||||
commentMQ *rabbitmq.CommentMQ
|
||||
popularityMQ *rabbitmq.PopularityMQ
|
||||
store CommentStore
|
||||
videos videoExister
|
||||
cache *rediscache.Client
|
||||
commentMQ CommentPublisher
|
||||
popularityMQ PopularityPublisher
|
||||
}
|
||||
|
||||
func NewCommentService(repo *CommentRepository, videoRepo *VideoRepository, cache *rediscache.Client, commentMQ *rabbitmq.CommentMQ, popularityMQ *rabbitmq.PopularityMQ) *CommentService {
|
||||
return &CommentService{repo: repo, VideoRepository: videoRepo, cache: cache, commentMQ: commentMQ, popularityMQ: popularityMQ}
|
||||
func NewCommentService(store CommentStore, videos videoExister, cache *rediscache.Client, commentMQ CommentPublisher, popularityMQ PopularityPublisher) *CommentService {
|
||||
return &CommentService{
|
||||
store: store,
|
||||
videos: videos,
|
||||
cache: cache,
|
||||
commentMQ: commentMQ,
|
||||
popularityMQ: popularityMQ,
|
||||
}
|
||||
}
|
||||
|
||||
// Publish 把一次"用户想发一条评论"的意图变成一次写入(P0-4 §6.5.2)。
|
||||
//
|
||||
// 关键在于:MQ 路径与兜底路径共用同一个意图键,而"判重"发生在唯一索引上,
|
||||
// 不是在内存里。因此
|
||||
//
|
||||
// - 消息发布成功 → 由 worker 写库,API 不写(否则正常路径会稳定双写);
|
||||
// - 消息发布失败 → API 直写,键仍是同一个,worker 稍后到达时命中唯一索引;
|
||||
// - 客户端重试 → 同一个键,第二次什么都不做,但返回成功。
|
||||
//
|
||||
// 发布失败不代表"没送达"(短超时、channel 抖动都可能发生在 broker 已收下
|
||||
// 之后),这正是旧代码的 D1:把 error 当成"未送达",于是必然双写。
|
||||
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
if comment == nil {
|
||||
return errors.New("comment is nil")
|
||||
}
|
||||
comment.Username = strings.TrimSpace(comment.Username)
|
||||
comment.Content = strings.TrimSpace(comment.Content)
|
||||
if comment.VideoID == 0 || comment.AuthorID == 0 {
|
||||
return errors.New("video_id and author_id are required")
|
||||
}
|
||||
if comment.Content == "" {
|
||||
return errors.New("content is required")
|
||||
comment.Username = strings.TrimSpace(comment.Username)
|
||||
if comment.Content == "" || comment.VideoID == 0 || comment.AuthorID == 0 {
|
||||
return fmt.Errorf("%w: video_id, author_id and content are required", apierror.ErrValidation)
|
||||
}
|
||||
|
||||
exists, err := s.VideoRepository.IsExist(ctx, comment.VideoID)
|
||||
key, err := ResolveIntentKey(comment.IdempotencyKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return errors.New("video not found")
|
||||
comment.IdempotencyKey = &key
|
||||
span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID)
|
||||
|
||||
if ok, err := s.videos.IsExist(ctx, comment.VideoID); err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
return fmt.Errorf("%w: video not found", apierror.ErrValidation)
|
||||
}
|
||||
|
||||
mysqlEnqueued := false
|
||||
redisEnqueued := false
|
||||
if s.commentMQ != nil {
|
||||
if err := s.commentMQ.Publish(ctx, comment.Username, comment.VideoID, comment.AuthorID, comment.Content); err == nil {
|
||||
mysqlEnqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, comment.VideoID, 1, ""); err == nil {
|
||||
redisEnqueued = true
|
||||
}
|
||||
}
|
||||
if mysqlEnqueued && redisEnqueued {
|
||||
s.notifyMentions(ctx, comment)
|
||||
return nil
|
||||
commentEnqueued := false
|
||||
if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{
|
||||
EventID: key,
|
||||
Action: "publish",
|
||||
Username: comment.Username,
|
||||
VideoID: comment.VideoID,
|
||||
AuthorID: comment.AuthorID,
|
||||
Content: comment.Content,
|
||||
}); err == nil {
|
||||
commentEnqueued = true
|
||||
} else {
|
||||
log.Printf("%s enqueue comment failed, fallback to direct write: %v", span, err)
|
||||
}
|
||||
|
||||
// Fallback: direct MySQL write when comment MQ publish fails.
|
||||
if !mysqlEnqueued {
|
||||
if err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Select("id").First(&Video{}, comment.VideoID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("video not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(comment).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", comment.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error
|
||||
}); err != nil {
|
||||
return 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)
|
||||
}
|
||||
|
||||
// —— 闸 1:只有评论事件没入队时才直写。
|
||||
// 入队成功时不写:让 worker 去写,避免"入队成功但 API 又写一遍"的必然双写。
|
||||
if !commentEnqueued {
|
||||
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
||||
if err != nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: direct Redis update when popularity MQ publish fails.
|
||||
if !redisEnqueued {
|
||||
UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, "")
|
||||
}
|
||||
s.notifyMentions(ctx, comment)
|
||||
s.notifyMentions(ctx, comment, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID uint) error {
|
||||
comment, err := s.repo.GetByID(ctx, commentID)
|
||||
comment, err := s.store.GetByID(ctx, commentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -101,58 +143,101 @@ func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID u
|
||||
if comment.AuthorID != accountID {
|
||||
return apierror.ErrUnauthorized
|
||||
}
|
||||
if s.commentMQ != nil {
|
||||
if err := s.commentMQ.Delete(ctx, commentID); err == nil {
|
||||
return nil
|
||||
}
|
||||
// 删除事件的 event_id 也用意图键:同一次删除被重复投递时,worker 侧
|
||||
// 按 id 删除并检查受影响行数,第二次是空操作。
|
||||
key, keyErr := NewIntentKey()
|
||||
if keyErr != nil {
|
||||
key = ""
|
||||
}
|
||||
return s.repo.DeleteComment(ctx, comment)
|
||||
if err := s.commentMQ.Delete(ctx, commentID, key); err == nil {
|
||||
return nil
|
||||
}
|
||||
return s.store.DeleteComment(ctx, comment)
|
||||
}
|
||||
|
||||
func (s *CommentService) GetAll(ctx context.Context, videoID uint) ([]Comment, error) {
|
||||
exists, err := s.VideoRepository.IsExist(ctx, videoID)
|
||||
exists, err := s.videos.IsExist(ctx, videoID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, errors.New("video not found")
|
||||
return nil, fmt.Errorf("%w: video not found", apierror.ErrValidation)
|
||||
}
|
||||
return s.repo.GetAllComments(ctx, videoID)
|
||||
return s.store.GetAllComments(ctx, videoID)
|
||||
}
|
||||
|
||||
var mentionRegex = regexp.MustCompile(`@(\w+)`)
|
||||
|
||||
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment) {
|
||||
// notifyMentions 写入 @ 提及通知。
|
||||
//
|
||||
// 三次往返收敛成两次(一次批量查用户名、一次批量插),并且每条通知都带
|
||||
// 绑定到意图键的去重键:同一条评论被重复投递时,通知也只有一条。
|
||||
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) {
|
||||
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
|
||||
if len(matches) == 0 {
|
||||
return
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
|
||||
seen := make(map[string]struct{}, len(matches))
|
||||
names := make([]string, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
username := m[1]
|
||||
if seen[username] || username == comment.Username {
|
||||
name := m[1]
|
||||
if name == comment.Username {
|
||||
continue
|
||||
}
|
||||
seen[username] = true
|
||||
var accID uint
|
||||
if err := s.repo.db.WithContext(ctx).Table("accounts").Where("username = ?", username).Select("id").Scan(&accID).Error; err != nil || accID == 0 {
|
||||
if _, dup := seen[name]; dup {
|
||||
continue
|
||||
}
|
||||
notif := struct {
|
||||
RecipientID uint
|
||||
SenderID uint
|
||||
Type string
|
||||
TargetID uint
|
||||
Content string
|
||||
}{
|
||||
RecipientID: accID,
|
||||
seen[name] = struct{}{}
|
||||
names = append(names, name)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
ids, err := s.store.FindAccountIDs(ctx, names)
|
||||
if err != nil {
|
||||
log.Printf("intent_key=%s stage=mention.lookup err=%v", intentKey, err)
|
||||
return
|
||||
}
|
||||
|
||||
mentions := make([]Mention, 0, len(ids))
|
||||
for _, name := range names {
|
||||
id, ok := ids[name]
|
||||
if !ok || id == 0 {
|
||||
continue
|
||||
}
|
||||
if id == comment.AuthorID {
|
||||
continue // 不给自己发通知
|
||||
}
|
||||
mentions = append(mentions, Mention{
|
||||
RecipientID: id,
|
||||
SenderID: comment.AuthorID,
|
||||
Type: "mention",
|
||||
TargetID: comment.VideoID,
|
||||
Content: comment.Username + " 在评论中提到了你",
|
||||
}
|
||||
if err := s.repo.db.WithContext(ctx).Table("notifications").Create(¬if).Error; err != nil {
|
||||
log.Printf("create mention notification failed: %v", err)
|
||||
}
|
||||
DedupeKey: NotificationDedupeKey("mention", intentKey, id),
|
||||
})
|
||||
}
|
||||
if len(mentions) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.store.CreateMentions(ctx, mentions); err != nil {
|
||||
// 通知是派生副作用:失败不改变"评论已发布"的结论(保持现状语义),
|
||||
// 但必须留痕,否则"用户说没收到通知"无从排查。
|
||||
log.Printf("intent_key=%s stage=mention.create err=%v", intentKey, err)
|
||||
}
|
||||
}
|
||||
|
||||
// logIntent 返回一段可 grep 的公共前缀:一次意图的所有日志都带同一个 key,
|
||||
// 因此"用户说没看到评论"可以用 grep intent_key=<K> 串起 API 与 Worker 两侧。
|
||||
func logIntent(stage, key string, authorID, videoID uint) string {
|
||||
return fmt.Sprintf("intent_key=%s stage=%s author_id=%d video_id=%d", key, stage, authorID, videoID)
|
||||
}
|
||||
|
||||
func dedupeLabel(created bool) string {
|
||||
if created {
|
||||
return "miss"
|
||||
}
|
||||
return "hit"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user