package video import ( "context" "errors" "fmt" "log" "regexp" "strings" "time" "feedsystem_video_go/internal/apierror" "feedsystem_video_go/internal/middleware/rabbitmq" rediscache "feedsystem_video_go/internal/middleware/redis" ) // CommentPublisher 只暴露评论服务用到的两个动作,便于在测试里注入发布失败。 // 真实实现必须在 nil 接收者上返回 error:nil 装进接口后 != nil 仍为 true。 type CommentPublisher interface { Publish(ctx context.Context, evt rabbitmq.CommentEvent) error Delete(ctx context.Context, commentID uint, 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 } func NewCommentService(store CommentStore, videos videoExister, cache *rediscache.Client, commentMQ CommentPublisher) *CommentService { return &CommentService{ store: store, videos: videos, cache: cache, commentMQ: commentMQ, } } // Publish 先入队,入队失败才直写;热度只由"这次插入是否真的落库"驱动。 func (s *CommentService) Publish(ctx context.Context, comment *Comment) error { if comment == nil { return errors.New("comment is nil") } comment.Content = strings.TrimSpace(comment.Content) 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) } key, err := ResolveIntentKey(comment.IdempotencyKey) if err != nil { return err } 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) } // 行时间只在直写分支用到;worker 用消息里的 occurred_at。 comment.CreatedAt = time.Now().UTC() 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) } // 入队成功时不直写,避免正常路径上稳定双写。 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 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) } } } s.notifyMentions(ctx, comment, key) return nil } func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID uint) error { comment, err := s.store.GetByID(ctx, commentID) if err != nil { return err } if comment == nil { return errors.New("comment not found") } if comment.AuthorID != accountID { return apierror.ErrUnauthorized } 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) } deleted, ok, err := s.store.DeleteWithPopularity(ctx, commentID) if err != nil { return err } if !ok { // 已经被删除(重复投递或另一条路径先到):空操作,热度不能再减。 return nil } 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) { exists, err := s.videos.IsExist(ctx, videoID) if err != nil { return nil, err } if !exists { return nil, fmt.Errorf("%w: video not found", apierror.ErrValidation) } return s.store.GetAllComments(ctx, videoID) } var mentionRegex = regexp.MustCompile(`@(\w+)`) // 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]struct{}, len(matches)) names := make([]string, 0, len(matches)) for _, m := range matches { name := m[1] if name == comment.Username { continue } if _, dup := seen[name]; dup { continue } 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, TargetID: comment.VideoID, Content: comment.Username + " 在评论中提到了你", 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) } } 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" }