Files
VLoop/backend/internal/video/comment_service.go

244 lines
7.9 KiB
Go
Raw Normal View History

2026-05-20 16:34:19 +08:00
package video
import (
"context"
"errors"
"fmt"
"log"
2026-05-20 16:34:19 +08:00
"regexp"
"strings"
"feedsystem_video_go/internal/apierror"
"feedsystem_video_go/internal/middleware/rabbitmq"
rediscache "feedsystem_video_go/internal/middleware/redis"
2026-05-20 16:34:19 +08:00
)
// 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)
}
2026-05-20 16:34:19 +08:00
type CommentService struct {
store CommentStore
videos videoExister
cache *rediscache.Client
commentMQ CommentPublisher
popularityMQ PopularityPublisher
2026-05-20 16:34:19 +08:00
}
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,
}
2026-05-20 16:34:19 +08:00
}
// Publish 把一次"用户想发一条评论"的意图变成一次写入(P0-4 §6.5.2)。
//
// 关键在于:MQ 路径与兜底路径共用同一个意图键,而"判重"发生在唯一索引上,
// 不是在内存里。因此
//
// - 消息发布成功 → 由 worker 写库,API 不写(否则正常路径会稳定双写);
// - 消息发布失败 → API 直写,键仍是同一个,worker 稍后到达时命中唯一索引;
// - 客户端重试 → 同一个键,第二次什么都不做,但返回成功。
//
// 发布失败不代表"没送达"(短超时、channel 抖动都可能发生在 broker 已收下
// 之后),这正是旧代码的 D1:把 error 当成"未送达",于是必然双写。
2026-05-20 16:34:19 +08:00
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)
2026-05-20 16:34:19 +08:00
}
key, err := ResolveIntentKey(comment.IdempotencyKey)
2026-05-20 16:34:19 +08:00
if err != nil {
return err
}
comment.IdempotencyKey = &key
span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID)
2026-05-20 16:34:19 +08:00
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)
2026-05-20 16:34:19 +08:00
}
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)
2026-05-20 16:34:19 +08:00
}
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)
2026-05-20 16:34:19 +08:00
}
// —— 闸 1:只有评论事件没入队时才直写。
// 入队成功时不写:让 worker 去写,避免"入队成功但 API 又写一遍"的必然双写。
if !commentEnqueued {
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
if err != nil {
return fmt.Errorf("fallback create comment: %w", err)
2026-05-20 16:34:19 +08:00
}
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
2026-05-20 16:34:19 +08:00
}
// —— 热度兜底:与评论事件彼此独立(两条事件是两次独立发布)。
// 热榜是"近似正确"的派生数据:失败只降级,不影响"评论已发布"的语义。
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)
}
2026-05-20 16:34:19 +08:00
}
s.notifyMentions(ctx, comment, key)
2026-05-20 16:34:19 +08:00
return nil
}
func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID uint) error {
comment, err := s.store.GetByID(ctx, commentID)
2026-05-20 16:34:19 +08:00
if err != nil {
return err
}
if comment == nil {
return errors.New("comment not found")
}
if comment.AuthorID != accountID {
return apierror.ErrUnauthorized
}
// 删除事件的 event_id 也用意图键:同一次删除被重复投递时,worker 侧
// 按 id 删除并检查受影响行数,第二次是空操作。
key, keyErr := NewIntentKey()
if keyErr != nil {
key = ""
}
if err := s.commentMQ.Delete(ctx, commentID, key); err == nil {
return nil
2026-05-20 16:34:19 +08:00
}
return s.store.DeleteComment(ctx, comment)
2026-05-20 16:34:19 +08:00
}
func (s *CommentService) GetAll(ctx context.Context, videoID uint) ([]Comment, error) {
exists, err := s.videos.IsExist(ctx, videoID)
2026-05-20 16:34:19 +08:00
if err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("%w: video not found", apierror.ErrValidation)
2026-05-20 16:34:19 +08:00
}
return s.store.GetAllComments(ctx, videoID)
2026-05-20 16:34:19 +08:00
}
var mentionRegex = regexp.MustCompile(`@(\w+)`)
// notifyMentions 写入 @ 提及通知。
//
// 三次往返收敛成两次(一次批量查用户名、一次批量插),并且每条通知都带
// 绑定到意图键的去重键:同一条评论被重复投递时,通知也只有一条。
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) {
2026-05-20 16:34:19 +08:00
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
if len(matches) == 0 {
return
}
seen := make(map[string]struct{}, len(matches))
names := make([]string, 0, len(matches))
2026-05-20 16:34:19 +08:00
for _, m := range matches {
name := m[1]
if name == comment.Username {
2026-05-20 16:34:19 +08:00
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 {
2026-05-20 16:34:19 +08:00
continue
}
if id == comment.AuthorID {
continue // 不给自己发通知
}
mentions = append(mentions, Mention{
RecipientID: id,
2026-05-20 16:34:19 +08:00
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)
}
}
// 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"
2026-05-20 16:34:19 +08:00
}
return "hit"
2026-05-20 16:34:19 +08:00
}