Files
VLoop/backend/internal/video/comment_service.go
huanghaosheng c210e75996 style(backend): 清理幂等写入路径的注释
注释只保留一行级约束。
长段理由移入设计文档。
验证:go test -count=1 ./... 全绿。
2026-10-31 00:03:53 +08:00

217 lines
6.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package video
import (
"context"
"errors"
"fmt"
"log"
"regexp"
"strings"
"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
}
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
}
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 用同一个意图键编排两条路径:MQ 成功则不直写,失败则直写。
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)
}
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)
}
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)
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)
}
}
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
}
key, keyErr := NewIntentKey()
if keyErr != nil {
key = ""
}
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.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"
}