style(backend): 清理幂等写入路径的注释

注释只保留一行级约束。
长段理由移入设计文档。
验证:go test -count=1 ./... 全绿。
This commit is contained in:
2026-10-31 00:03:53 +08:00
parent c0ab69118a
commit c210e75996
13 changed files with 50 additions and 239 deletions

View File

@@ -6,12 +6,11 @@ import (
"time" "time"
) )
// CommentMQ 通过连接管理器发布评论事件(不再持有长生命周期 channel)。 // CommentMQ 通过连接管理器发布评论事件。
type CommentMQ struct { type CommentMQ struct {
mgr *RabbitMQ mgr *RabbitMQ
} }
// 拓扑常量导出:见 likeMQ.go 中的说明。
const ( const (
CommentExchange = "comment.events" CommentExchange = "comment.events"
CommentQueue = "comment.events" CommentQueue = "comment.events"
@@ -40,9 +39,7 @@ func NewCommentMQ(base *RabbitMQ) (*CommentMQ, error) {
return &CommentMQ{mgr: base}, nil return &CommentMQ{mgr: base}, nil
} }
// Publish 直接接收完整事件:event_id 由调用方(服务层)生成,因为它是 // Publish 接收完整事件;EventID 由调用方生成,仅为空时补一个随机值。
// "这次用户意图"的标识,必须与兜底直写用的是同一个值(P0-4 §6.8)。
// 只有 EventID 为空时才在这里补一个随机 id(老调用方/测试路径)。
func (c *CommentMQ) Publish(ctx context.Context, evt CommentEvent) error { func (c *CommentMQ) Publish(ctx context.Context, evt CommentEvent) error {
return c.publish(ctx, "publish", CommentPublishRK, evt) return c.publish(ctx, "publish", CommentPublishRK, evt)
} }

View File

@@ -27,14 +27,8 @@ func (c *Client) Del(ctx context.Context, key string) error {
return c.rdb.Del(ctx, key).Err() return c.rdb.Del(ctx, key).Err()
} }
// SetNX 仅在 key 不存在时写入,返回是否抢到了这个键。 // SetNX 仅在 key 不存在时写入;key 由调用方拼好。
// // 失败必须返回 error,调用方据此判断占位是否生效。
// key 由调用方用 c.Key(...) 拼好(本方法不加前缀)——加前缀的时机必须
// 和其他原语一致,否则同一个逻辑键会因为调用路径不同变成两个物理键。
//
// 失败(含 nil client)必须返回 error 而不是 (false, nil):调用方用它
// 判断"这次意图是否已经生效过",把 Redis 故障静默说成"已生效"会导致
// 该次加分被永久跳过。
func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) { func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) {
if c == nil || c.rdb == nil { if c == nil || c.rdb == nil {
return false, errors.New("redis client not initialized") return false, errors.New("redis client not initialized")

View File

@@ -1,21 +1,9 @@
// Package notification 存放通知表的实体定义。 // Package notification 存放 notifications 表的实体定义。
// // worker 与 video 都依赖它,因此列标签只有一处。
// 它独立成包,是为了让"notifications 表的列结构"只有一个权威定义:
//
// - Worker 侧需要读写它(写通知、SSE 列表、标记已读、未读数);
// - video 包需要写它(评论里的 @ 提及通知)。
//
// video 不能 import worker(worker 已经 import video,会成环),而各自维护一份
// 结构体又会让列标签悄悄漂移——漂移不会报错,只会在 AutoMigrate 时试图改动
// 生产列类型。因此把实体放在两边都能引用的中立位置,依赖方向恒为
// worker → notification 与 video → notification。
//
// 本包不依赖项目内的任何其他包,只描述表结构。
package notification package notification
import "time" import "time"
// Notification 是 notifications 表的一行。
type Notification struct { type Notification struct {
ID uint `gorm:"primaryKey" json:"id"` ID uint `gorm:"primaryKey" json:"id"`
RecipientID uint `gorm:"index;not null" json:"recipient_id"` RecipientID uint `gorm:"index;not null" json:"recipient_id"`
@@ -26,19 +14,8 @@ type Notification struct {
IsRead bool `gorm:"default:false" json:"is_read"` IsRead bool `gorm:"default:false" json:"is_read"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
// DedupeKey 把"这条通知由哪一次用户意图产生"写进唯一索引。 // DedupeKey 用 *string:无意图键的通知写 NULL,不参与唯一约束。
//
// 同一条点赞/评论事件被投递两次(发布返回错误但实际已入队、重试、重放)时,
// 第二次会撞上 uk_notifications_dedupe 而不是再插一行——用户不会在通知
// 列表里看到两条一模一样的"点赞了你的视频",也不会收到两次 SSE 推送。
//
// 用 *string 而不是 string:没有意图键的事件(历史数据、旧客户端)宁可
// 不去重(NULL 不参与唯一约束),也不能把不同事件都判成同一条。
DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe" json:"-"` DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe" json:"-"`
} }
// TableName 固定表名。
//
// 默认命名(复数化)结果也是 notifications,但显式写出来可以避免有人把类型
// 改名之后表名跟着漂移——这张表的写入方有两个包,表名漂移的代价比多写一行大。
func (Notification) TableName() string { return "notifications" } func (Notification) TableName() string { return "notifications" }

View File

@@ -10,18 +10,7 @@ type Comment struct {
Content string `gorm:"type:text" json:"content"` Content string `gorm:"type:text" json:"content"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
// IdempotencyKey 是"这次发评论的意图"的稳定标识(P0-4)。 // IdempotencyKey 必须是 *string:空串会互撞唯一索引,NULL 不会。
//
// 与 AuthorID 组成唯一索引 uk_comments_author_key:同一次用户意图
// 无论被写入几次(MQ 假失败后的 DB 兜底、worker 重复投递、客户端
// 重试),在数据库里都只会留下一行。
//
// 必须是指针:MySQL 的唯一索引不约束 NULL,多个 NULL 可以共存。
// 若用 string + 空串,存量行与"没带 request_id"的行会全部撞在
// 同一个 '' 上,第二条无键评论就会被判成重复。
//
// json:"-" 让它不出现在任何 API 响应里:它是去重机制的内部标识,
// 不是用户可见的数据。
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"` IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
} }
@@ -29,11 +18,7 @@ type PublishCommentRequest struct {
VideoID uint `json:"video_id"` VideoID uint `json:"video_id"`
Content string `json:"content"` Content string `json:"content"`
// RequestID 由客户端为"一次发送动作"生成,重试时复用同一个值。 // RequestID 由客户端为一次发送动作生成,重试时复用;为空则服务端生成。
//
// 为空时服务端会生成一个(单次请求内仍然幂等,但客户端重试无法被识别)。
// 校验规则见 idempotency.go:8–64 个 [0-9a-zA-Z_-] 字符,非法值返回 400
// 而不是静默截断或忽略。
RequestID string `json:"request_id"` RequestID string `json:"request_id"`
} }

View File

@@ -46,8 +46,6 @@ func (h *CommentHandler) PublishComment(c *gin.Context) {
AuthorID: authorId, AuthorID: authorId,
Content: req.Content, Content: req.Content,
} }
// 客户端可以自带 request_id 来表达"这就是我刚才那次提交"。
// 不传则由服务端生成:同一个请求内的所有写入仍然共用一个键(G6)。
if req.RequestID != "" { if req.RequestID != "" {
requestID := req.RequestID requestID := req.RequestID
comment.IdempotencyKey = &requestID comment.IdempotencyKey = &requestID
@@ -56,9 +54,7 @@ func (h *CommentHandler) PublishComment(c *gin.Context) {
c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()}) c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()})
return return
} }
// 回显 request_id:客户端重试时可以带上同一个值,服务端据此判重。 // 回显 request_id,供客户端重试时复用;不返回评论 ID,因为它可能尚未落库。
// 刻意不返回评论 ID——MQ 路径上评论此刻可能还没落库,返回一个还不存在的
// id 只会制造"点进去 404"的错觉。
resp := gin.H{"message": "comment published successfully"} resp := gin.H{"message": "comment published successfully"}
if comment.IdempotencyKey != nil { if comment.IdempotencyKey != nil {
resp["request_id"] = *comment.IdempotencyKey resp["request_id"] = *comment.IdempotencyKey

View File

@@ -22,25 +22,9 @@ func (r *CommentRepository) CreateComment(ctx context.Context, comment *Comment)
return r.db.WithContext(ctx).Create(comment).Error return r.db.WithContext(ctx).Create(comment).Error
} }
// CreateIdempotentWithPopularity 是 P0-4 的核心写入口。 // CreateIdempotentWithPopularity 由 uk_comments_author_key 判重。
// // 热度增量与插入必须同事务,只在 created=true 时执行。
// 它把两件必须同生共死的事放进同一个事务: // 注意:DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
//
// 1. 插入评论——由 uk_comments_author_key(author_id, idempotency_key) 判重,
// 重复时静默返回 created=false,不报错、不覆盖。
// 2. 视频热度 +delta——只在真的插入了这一行时才执行。
//
// 为什么判重不能靠"先 SELECT 再 INSERT":两个 goroutine 之间永远有窗口,
// 而这条窗口正好是 P0-4 的场景(MQ 假失败后兜底直写 + worker 稍后消费)。
// 让数据库的唯一索引来裁决,判重与写入就变成同一个原子动作,没有窗口。
//
// 为什么不用 1062 判重:报错与去重是两种不同的语义,用报错表达去重会让
// 每一条正常路径都经过一次 error 分支,也难以区分"真冲突"与"别的 1062"。
// OnConflict DoNothing 直接给出 RowsAffected——它就是"我是否真的插入了"。
//
// 注意:本项目 DSN(internal/db/db.go)刻意没有 clientFoundRows。若有人
// 加上它,MySQL 会在"行未变化"时也报告 1 行受影响,本函数就会把重复写入
// 当成首次写入,热度变成 +2——判重静默失效。db 包与集成测试各有护栏。
func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) { func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) {
var created bool var created bool
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
@@ -49,15 +33,12 @@ func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context,
return res.Error return res.Error
} }
if res.RowsAffected == 0 { if res.RowsAffected == 0 {
// 这条意图已经落过库:不是错误,也不再加热度。
return nil return nil
} }
created = true created = true
if delta == 0 { if delta == 0 {
return nil return nil
} }
// 与插入同一个事务:要么"评论与热度"一起生效,要么都不生效。
// GREATEST(...,0) 防止热度被回滚到负数(与点赞侧一致)。
return tx.Model(&Video{}). return tx.Model(&Video{}).
Where("id = ?", c.VideoID). Where("id = ?", c.VideoID).
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
@@ -72,10 +53,7 @@ func (r *CommentRepository) DeleteComment(ctx context.Context, comment *Comment)
return r.db.WithContext(ctx).Delete(comment).Error return r.db.WithContext(ctx).Delete(comment).Error
} }
// DeleteByID 汇报"这次调用是否真的删掉了一行"。 // DeleteByID 返回是否真的删除了一行,供调用方门控热度回退。
//
// 删除的重复投递与新增的重复投递同样致命:把热度回退当成无条件动作,
// 同一条删除事件投递两次就会把热度减两次(P2-20 的门控点就是这个返回值)。
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) { func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
if id == 0 { if id == 0 {
return false, nil return false, nil
@@ -119,11 +97,6 @@ func (r *CommentRepository) GetByID(ctx context.Context, id uint) (*Comment, err
return &comment, nil return &comment, nil
} }
// CreateMentions 幂等写入提及通知:DedupeKey 相同则静默跳过。
//
// 显式写 CreatedAt 而不依赖 autoCreateTime:这一批行共享同一个时间戳,便于
// 按"同一次评论"检索;autoCreateTime 只在字段为零值时才生效,依赖它会让
// 同一批写入拿到毫秒级不同的时间(P2-16 ①)。
func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error { func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error {
if len(mentions) == 0 { if len(mentions) == 0 {
return nil return nil
@@ -146,11 +119,7 @@ func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Menti
Create(&rows).Error Create(&rows).Error
} }
// FindAccountIDs 一次查询解析一批用户名。 // FindAccountIDs 一次查询解析一批用户名;不存在的用户名不出现在结果里。
//
// 逐个 SELECT 会让"一条评论里 @ 了 5 个人"变成 5 次往返,而这段代码跑在
// 用户请求路径上(P0-4 §6.5)。不存在的用户名不出现在结果里,调用方按
// map 的不存在分支跳过即可。
func (r *CommentRepository) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) { func (r *CommentRepository) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) {
out := make(map[string]uint, len(usernames)) out := make(map[string]uint, len(usernames))
if len(usernames) == 0 { if len(usernames) == 0 {

View File

@@ -13,26 +13,18 @@ import (
rediscache "feedsystem_video_go/internal/middleware/redis" rediscache "feedsystem_video_go/internal/middleware/redis"
) )
// CommentPublisher 只暴露评论服务用得到的两个动作。 // CommentPublisher 只暴露评论服务用到的两个动作,便于在测试里注入发布失败。
// // 真实实现必须在 nil 接收者上返回 error:nil 装进接口后 != nil 仍为 true。
// 用接口而不是具体类型,是为了让"发布失败"成为可注入的场景:P0-4 的全部
// 分支都取决于"这条消息到底发出去了没有",而这恰恰是真实 broker 最难稳定
// 复现的状态。
//
// 注意:nil 指针装进接口后 != nil 依然为 true,所以真实实现必须在 nil
// 接收者上返回 error(commentMQ.go 现状已如此)。
type CommentPublisher interface { type CommentPublisher interface {
Publish(ctx context.Context, evt rabbitmq.CommentEvent) error Publish(ctx context.Context, evt rabbitmq.CommentEvent) error
Delete(ctx context.Context, commentID uint, intentKey string) error Delete(ctx context.Context, commentID uint, intentKey string) error
} }
// PopularityPublisher 是热度事件的最小接口。
type PopularityPublisher interface { type PopularityPublisher interface {
Update(ctx context.Context, videoID uint, change int64, intentKey string) error Update(ctx context.Context, videoID uint, change int64, intentKey string) error
} }
// videoExister 只暴露 CommentService 需要的那一个方法。 // videoExister 由 *VideoRepository 满足,因此 router.go 无需改动。
// *VideoRepository 天然满足它,因此 router.go 的构造代码不需要改。
type videoExister interface { type videoExister interface {
IsExist(ctx context.Context, id uint) (bool, error) IsExist(ctx context.Context, id uint) (bool, error)
} }
@@ -55,17 +47,7 @@ func NewCommentService(store CommentStore, videos videoExister, cache *rediscach
} }
} }
// Publish 把一次"用户想发一条评论"的意图变成一次写入(P0-4 §6.5.2)。 // Publish 用同一个意图键编排两条路径:MQ 成功则不直写,失败则直写。
//
// 关键在于:MQ 路径与兜底路径共用同一个意图键,而"判重"发生在唯一索引上,
// 不是在内存里。因此
//
// - 消息发布成功 → 由 worker 写库,API 不写(否则正常路径会稳定双写);
// - 消息发布失败 → API 直写,键仍是同一个,worker 稍后到达时命中唯一索引;
// - 客户端重试 → 同一个键,第二次什么都不做,但返回成功。
//
// 发布失败不代表"没送达"(短超时、channel 抖动都可能发生在 broker 已收下
// 之后),这正是旧代码的 D1:把 error 当成"未送达",于是必然双写。
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error { func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
if comment == nil { if comment == nil {
return errors.New("comment is nil") return errors.New("comment is nil")
@@ -110,8 +92,7 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
log.Printf("%s enqueue popularity failed, fallback to hot cache: %v", span, err) log.Printf("%s enqueue popularity failed, fallback to hot cache: %v", span, err)
} }
// —— 闸 1:只有评论事件没入队时才直写。 // 入队成功时不直写,避免正常路径上稳定双写。
// 入队成功时不写:让 worker 去写,避免"入队成功但 API 又写一遍"的必然双写。
if !commentEnqueued { if !commentEnqueued {
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1) created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
if err != nil { if err != nil {
@@ -120,8 +101,7 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created)) log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
} }
// —— 热度兜底:与评论事件彼此独立(两条事件是两次独立发布)。 // 热度与评论是两次独立发布,失败只降级。
// 热榜是"近似正确"的派生数据:失败只降级,不影响"评论已发布"的语义。
if !popularityEnqueued { if !popularityEnqueued {
if err := UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, key); err != nil { if err := UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, key); err != nil {
log.Printf("%s hot cache update failed (degraded): %v", span, err) log.Printf("%s hot cache update failed (degraded): %v", span, err)
@@ -143,8 +123,6 @@ func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID u
if comment.AuthorID != accountID { if comment.AuthorID != accountID {
return apierror.ErrUnauthorized return apierror.ErrUnauthorized
} }
// 删除事件的 event_id 也用意图键:同一次删除被重复投递时,worker 侧
// 按 id 删除并检查受影响行数,第二次是空操作。
key, keyErr := NewIntentKey() key, keyErr := NewIntentKey()
if keyErr != nil { if keyErr != nil {
key = "" key = ""
@@ -168,10 +146,8 @@ func (s *CommentService) GetAll(ctx context.Context, videoID uint) ([]Comment, e
var mentionRegex = regexp.MustCompile(`@(\w+)`) var mentionRegex = regexp.MustCompile(`@(\w+)`)
// notifyMentions 写入 @ 提及通知。 // notifyMentions 批量解析用户名并写入带去重键的提及通知。
// // 去重键必须含收件人:同一次评论可能通知多个人。
// 三次往返收敛成两次(一次批量查用户名、一次批量插),并且每条通知都带
// 绑定到意图键的去重键:同一条评论被重复投递时,通知也只有一条。
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) { func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) {
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1) matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
if len(matches) == 0 { if len(matches) == 0 {
@@ -208,7 +184,7 @@ func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, i
continue continue
} }
if id == comment.AuthorID { if id == comment.AuthorID {
continue // 不给自己发通知 continue
} }
mentions = append(mentions, Mention{ mentions = append(mentions, Mention{
RecipientID: id, RecipientID: id,
@@ -222,15 +198,12 @@ func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, i
return return
} }
// 通知是派生副作用:失败不改变"评论已发布",但必须留痕。
if err := s.store.CreateMentions(ctx, mentions); err != nil { if err := s.store.CreateMentions(ctx, mentions); err != nil {
// 通知是派生副作用:失败不改变"评论已发布"的结论(保持现状语义),
// 但必须留痕,否则"用户说没收到通知"无从排查。
log.Printf("intent_key=%s stage=mention.create err=%v", intentKey, err) 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 { 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) return fmt.Sprintf("intent_key=%s stage=%s author_id=%d video_id=%d", key, stage, authorID, videoID)
} }

View File

@@ -4,12 +4,7 @@ import (
"context" "context"
) )
// Mention 是一条"提及通知"的写入意图。 // Mention 是一条待写入的提及通知。
//
// DedupeKey 由 NotificationDedupeKey(notifType, intentKey, recipientID) 生成,
// 落到 notifications 表的唯一索引 uk_notifications_dedupe 上。它让"同一次
// 评论意图产生的提及通知"无论被写几次都只有一行——与评论本身用的是同一个
// 意图键,所以两侧的判重是同一个语义,而不是两套各自为政的计数器。
type Mention struct { type Mention struct {
RecipientID uint RecipientID uint
SenderID uint SenderID uint
@@ -18,16 +13,9 @@ type Mention struct {
DedupeKey string DedupeKey string
} }
// CommentStore 是 CommentService 与 CommentWorker 依赖的窄接口。
//
// 抽接口不是为了"面向接口编程",而是为了给"判重与写入必须发生在同一条 SQL
// 的同一个事务里"这条约束一个显式的名字:任何实现都必须提供
// CreateIdempotentWithPopularity,而不是先 Create 再补一条热度 UPDATE——
// 后者在两条语句之间崩溃就会留下"评论在、热度不在"的半成品。
type CommentStore interface { type CommentStore interface {
// CreateIdempotentWithPopularity 在同一个事务里完成 // CreateIdempotentWithPopularity 在同一事务内插入评论并给热度加 delta。
// "插入评论(幂等)" + "热度增量(仅首次插入时)"。 // created=false 表示该意图已落库,调用方不得再加热度。
// created=false 表示这条意图已经落过库,调用方不得再加热度。
CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (created bool, err error) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (created bool, err error)
GetByID(ctx context.Context, id uint) (*Comment, error) GetByID(ctx context.Context, id uint) (*Comment, error)
@@ -35,16 +23,11 @@ type CommentStore interface {
DeleteByID(ctx context.Context, id uint) (deleted bool, err error) DeleteByID(ctx context.Context, id uint) (deleted bool, err error)
GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) GetAllComments(ctx context.Context, videoID uint) ([]Comment, error)
// CreateMentions 按 DedupeKey 幂等写入提及通知。
CreateMentions(ctx context.Context, mentions []Mention) error CreateMentions(ctx context.Context, mentions []Mention) error
// FindAccountIDs 一次查询把用户名批量解析成账号 ID。
FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error)
} }
// nilIfEmpty 把空串转成 NULL。 // nilIfEmpty 供可空唯一列使用:空串会互撞,NULL 才是"没有这个键"。
//
// 用于 idempotency_key / dedupe_key 这类"可空唯一列":空串是一个真实的值,
// 多条空串会互相撞唯一索引;NULL 才是"没有这个键"。
func nilIfEmpty(s string) *string { func nilIfEmpty(s string) *string {
if s == "" { if s == "" {
return nil return nil

View File

@@ -10,20 +10,13 @@ import (
) )
const ( const (
// MaxIntentKeyLen 与 comments.idempotency_key VARCHAR(64) 保持一致。 // MaxIntentKeyLen 与 comments.idempotency_key 的列宽一致。
MaxIntentKeyLen = 64 MaxIntentKeyLen = 64
// minIntentKeyLen 防止客户端传 "1"、"a" 这类极易碰撞的键。
minIntentKeyLen = 8 minIntentKeyLen = 8
// intentKeyAlphabet 刻意排除 ':':通知去重键用 ':' 作分隔符 // intentKeyAlphabet 不含 ':',它是通知去重键的分隔符。
// ("comment:<K>:12"),若 K 含 ':' 则键的边界不可解析。
intentKeyAlphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_" intentKeyAlphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
) )
// NewIntentKey 生成 32 字符的随机意图键(16 字节 hex)。
//
// 为什么不用 uuid 库:项目当前没有该依赖,crypto/rand + hex 已足够;
// rabbitmq 包里的 newEventID 是同一模式,但它在包内私有,跨包复用
// 会把 video 拖进 rabbitmq → config 的依赖链。
func NewIntentKey() (string, error) { func NewIntentKey() (string, error) {
b := make([]byte, 16) b := make([]byte, 16)
if _, err := rand.Read(b); err != nil { if _, err := rand.Read(b); err != nil {
@@ -32,13 +25,6 @@ func NewIntentKey() (string, error) {
return hex.EncodeToString(b), nil return hex.EncodeToString(b), nil
} }
// ResolveIntentKey 把客户端传来的 request_id 解析成意图键。
//
// nil 或空白 → 生成新键(旧客户端,每次请求都是新意图,行为与今天一致);
// 合法 → 原样返回(客户端重试携带同一个值 → 命中同一次意图);
// 非法 → 返回错误,【不静默截断/不静默替换】。
//
// 静默替换会让"客户端以为去重了、服务端其实没有",比重试产生重复更难排查。
func ResolveIntentKey(raw *string) (string, error) { func ResolveIntentKey(raw *string) (string, error) {
if raw == nil || strings.TrimSpace(*raw) == "" { if raw == nil || strings.TrimSpace(*raw) == "" {
return NewIntentKey() return NewIntentKey()
@@ -50,9 +36,7 @@ func ResolveIntentKey(raw *string) (string, error) {
return key, nil return key, nil
} }
// validateIntentKey 的错误一律包 apierror.ErrValidation:request_id 写错 // validateIntentKey 的错误必须包 apierror.ErrValidation,否则会落 500。
// 是客户端的错,必须落 400。裸 error 会走 apierror.ClassifyHTTPStatus 的
// default 分支变成 500,把一次参数错误显示成服务端故障。
func validateIntentKey(key string) error { func validateIntentKey(key string) error {
if len(key) < minIntentKeyLen || len(key) > MaxIntentKeyLen { if len(key) < minIntentKeyLen || len(key) > MaxIntentKeyLen {
return fmt.Errorf("%w: request_id must be %d-%d characters", return fmt.Errorf("%w: request_id must be %d-%d characters",
@@ -67,10 +51,7 @@ func validateIntentKey(key string) error {
return nil return nil
} }
// NotificationDedupeKey 构造通知表的去重键。 // NotificationDedupeKey 返回空串表示"这条通知不参与去重"。
//
// intentKey 为空时返回空串:空串不写入唯一索引列(该列可空),
// 因此"没有意图键的事件"退化为不去重,而不是全部挤在同一个键上。
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string { func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
if intentKey == "" { if intentKey == "" {
return "" return ""

View File

@@ -57,8 +57,7 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
like.CreatedAt = time.Now() like.CreatedAt = time.Now()
// 一条意图键同时喂给"点赞事件"和"热度事件":两条消息若都重复投递, // 同一个键喂给点赞事件与热度事件,两条消费端各自去重。
// 各自的消费端会用同一个键去重(点赞走唯一索引,热度走 redis 占位)。
intentKey, err := NewIntentKey() intentKey, err := NewIntentKey()
if err != nil { if err != nil {
return err return err
@@ -77,14 +76,9 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
} }
} }
// 两条轨各自独立降级(P0-4 §6.10.4)。 // 两条轨各自独立降级:合并判断会在"点赞已入队、热度失败"时再插一次 likes,
// // 撞 idx_like_video_account 并返回 500。
// 这里【不能】写成 `if !likeEnqueued && !popEnqueued` 之外的任何"合并判断":
// 旧代码是"两个都成功才 return,否则无条件进兜底",于是"点赞已入队 +
// 热度发布失败"会再插一次 likes → 撞 idx_like_video_account 1062 →
// 接口返回 500,而用户其实点赞成功了。热度归热度,点赞归点赞。
if !likeEnqueued { if !likeEnqueued {
// Fallback: direct MySQL write when like MQ publish fails.
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { 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 err := tx.Select("id").First(&Video{}, like.VideoID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -110,8 +104,7 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
} }
} }
// Fallback: direct Redis update when popularity MQ publish fails. // 热度是展示数据:写失败只降级记日志,不回滚已经成立的点赞。
// 热度是"尽力而为"的展示数据,写失败只降级记日志,不回滚已经成立的点赞。
if !popEnqueued { if !popEnqueued {
if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, 1, intentKey); err != nil { if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, 1, intentKey); err != nil {
log.Printf("like: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err) log.Printf("like: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
@@ -166,7 +159,6 @@ func (s *LikeService) Unlike(ctx context.Context, like *Like) error {
// 与 Like 对称:两条轨各自降级,不做合并判断。 // 与 Like 对称:两条轨各自降级,不做合并判断。
if !likeEnqueued { if !likeEnqueued {
// Fallback: direct MySQL write when like MQ publish fails.
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { 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{}) del := tx.Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).Delete(&Like{})
if del.Error != nil { if del.Error != nil {
@@ -188,7 +180,6 @@ func (s *LikeService) Unlike(ctx context.Context, like *Like) error {
} }
} }
// Fallback: direct Redis update when popularity MQ publish fails.
if !popEnqueued { if !popEnqueued {
if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, -1, intentKey); err != nil { if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, -1, intentKey); err != nil {
log.Printf("unlike: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err) log.Printf("unlike: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)

View File

@@ -11,36 +11,18 @@ import (
) )
const ( const (
// hotAppliedTTL 是"这条意图已经加过分"占位的存活时间。 // hotAppliedTTL 覆盖同一次意图的重复投递窗口。
// 它只需要覆盖"同一事件的重复投递窗口"(重试 + 停泊重放 + 客户端重试),
// 2 小时远大于该窗口,同时又把键的数量限制在一个可估算的量级上。
hotAppliedTTL = 2 * time.Hour hotAppliedTTL = 2 * time.Hour
// hotWindowTTL 是分钟窗口 ZSET 的存活时间。热榜只需要最近若干个窗口, hotWindowTTL = 2 * time.Hour
// 留 2 小时是为了让"跨窗口查询"和事后核对仍然可读。 // hotOpTimeout 只约束 SetNX / ZINCRBY / EXPIRE 三次往返。
hotWindowTTL = 2 * time.Hour
// hotOpTimeout 约束三次"计数往返":SetNX / ZINCRBY / EXPIRE。
// 三次 Del 是 best-effort 的缓存失效,用 context.Background(),不受它约束
// ——把删缓存也算进预算,Redis 一抖动就会让整条热度消息失败并触发重投。
hotOpTimeout = 100 * time.Millisecond hotOpTimeout = 100 * time.Millisecond
) )
// UpdatePopularityCache 在热榜上给某个视频加一次分(P0-4 §6.10)。 // UpdatePopularityCache 给视频的分钟窗口热度加 change。
// //
// 返回值是这个函数与它前任最大的区别:原来所有错误都被 `_ =` 吞掉,导致 // intentKey 非空时先抢 hot:applied:<intentKey> 占位,抢不到说明该意图
// 消费端的 Nack/重试分支全是死代码(P0-3 的 N2)。现在"加分失败"必须 // 已生效,直接返回 nil。ZINCRBY 失败必须撤销占位,否则这次增量会被
// 上抛,让 ConsumeLoop 决定重投还是停泊——热度不是可选装饰,它是热榜的 // 永久跳过。
// 唯一数据来源。
//
// 幂等由 redis 的 SETNX 占位实现,键为 hot:applied:<意图键>:
//
// - intentKey 非空时,先抢占位;抢不到说明这条意图已经加过分,直接返回
// 成功(去重是正常语义,不是错误)。
// - intentKey 为空时不去重:调用方(点赞兜底)已经保证"只有事件发不出去
// 才走到这里",在这里再去重会把真实增量吞掉。
//
// 占位必须与"加分成功"同生共死:ZINCRBY 失败而占位留下,这条增量就会被
// 永久跳过——用户只会觉得"热度不动了",比重复加分更难发现。所以失败分支
// 必须撤销占位,且撤销本身也用不受 opCtx 约束的 ctx。
func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uint, change int64, intentKey string) error { func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uint, change int64, intentKey string) error {
if cache == nil || id == 0 || change == 0 { if cache == nil || id == 0 || change == 0 {
return nil return nil
@@ -57,13 +39,11 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
return fmt.Errorf("hot cache: claim intent %q: %w", intentKey, err) return fmt.Errorf("hot cache: claim intent %q: %w", intentKey, err)
} }
if !claimed { if !claimed {
// 这条意图已经生效过:不重复加分,也不重复失效缓存。
return nil return nil
} }
} }
// 缓存失效是 best-effort:失败最多让详情页多陈旧 5 分钟(缓存 TTL), // 缓存失效是 best-effort,不计入 opCtx 预算。
// 不值得让整条消息重投。
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id)) _ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id))
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", id)) _ = cache.Del(context.Background(), cache.Key("video:entity:%d", id))
@@ -74,8 +54,6 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
if err := cache.ZincrBy(opCtx, windowKey, member, float64(change)); err != nil { if err := cache.ZincrBy(opCtx, windowKey, member, float64(change)); err != nil {
if marker != "" { if marker != "" {
if delErr := cache.Del(context.Background(), marker); delErr != nil { if delErr := cache.Del(context.Background(), marker); delErr != nil {
// 撤销失败:这条增量会被跳过。宁可留下一条明确的日志,
// 也不要假装成功——人工可以按 hot:applied:<K> 清理。
log.Printf("hot cache: revoke intent marker %s failed: %v", marker, delErr) log.Printf("hot cache: revoke intent marker %s failed: %v", marker, delErr)
} }
} }
@@ -83,7 +61,6 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
} }
if err := cache.Expire(opCtx, windowKey, hotWindowTTL); err != nil { if err := cache.Expire(opCtx, windowKey, hotWindowTTL); err != nil {
// 窗口已经写好,缺过期时间只是键长期驻留,不影响正确性。
log.Printf("hot cache: expire %s failed (non-fatal): %v", windowKey, err) log.Printf("hot cache: expire %s failed (non-fatal): %v", windowKey, err)
} }
return nil return nil

View File

@@ -62,7 +62,7 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
return err return err
} }
if !ok { if !ok {
// 视频已被删除:没有可落评论的地方,但这是"处理完了",不是失败。 // 视频已删除:处理完了,不是失败。
return nil return nil
} }
@@ -72,8 +72,7 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
AuthorID: evt.AuthorID, AuthorID: evt.AuthorID,
Content: strings.TrimSpace(evt.Content), Content: strings.TrimSpace(evt.Content),
} }
// 事件里的 event_id 就是"这次用户意图"的键。API 侧若已经兜底直写过, // event_id 即意图键:API 已直写时这里会命中唯一索引。
// 这次插入会命中唯一索引:(created=false) 说明重复投递,热度不能再加一次。
if evt.EventID != "" { if evt.EventID != "" {
key := evt.EventID key := evt.EventID
c.IdempotencyKey = &key c.IdempotencyKey = &key

View File

@@ -16,12 +16,7 @@ import (
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
// notificationActions 记录每个通知队列期望收到哪种 action。 // 分派必须用队列 + body.action:重试回源会把 routing key 改写成队列名。
//
// 分派依据必须是队列 + 消息体里的 action,不能是 routing key:重试链路
// 回源时会把 routing key 改写成队列名(`like.like` → `notification.like`),
// 按 routing key 判断会让第二次投递变成"未知事件"而被立即停泊,重试预算
// 白丢。queue 在整个生命周期里不变,所以它是可靠的。
var notificationActions = map[string]string{ var notificationActions = map[string]string{
rabbitmq.NotificationLikeQueue: "like", rabbitmq.NotificationLikeQueue: "like",
rabbitmq.NotificationCommentQueue: "publish", rabbitmq.NotificationCommentQueue: "publish",
@@ -51,10 +46,7 @@ func (w *NotificationWorker) Run(ctx context.Context) error {
if w.queue == "" { if w.queue == "" {
return errors.New("queue is required") return errors.New("queue is required")
} }
// 这里刻意不再 AutoMigrate:建表由 API 进程的 db.AutoMigrate 统一负责 // 建表由 API 进程的 db.AutoMigrate 统一负责;三个消费者并发建索引会撞 1061。
// (internal/db/db.go 已包含 &notification.Notification{})。原来每个通知消费者
// 各跑一次 AutoMigrate,加唯一索引后三个 goroutine 会并发 CREATE INDEX
// 并撞上 1061;即使能靠重连自愈,也让"谁来建表"出现了两个答案。
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process) return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
} }
@@ -165,10 +157,7 @@ func (w *NotificationWorker) videoAuthorID(ctx context.Context, videoID uint) (u
} }
func (w *NotificationWorker) persist(ctx context.Context, notif *notification.Notification, eventID string) error { func (w *NotificationWorker) persist(ctx context.Context, notif *notification.Notification, eventID string) error {
// 意图键取自事件体里的 event_id:P0-4 之后它就是"这一次用户动作"的 // event_id 取不到时留空,此时该通知不参与去重。
// 稳定标识(发布端用意图键填充)。取不到时留空——结果是不去重,
// 这是刻意的保守选择:多一条通知可以接受,把两条不同事件判成同一条
// 会让用户永久收不到其中一条。
notif.DedupeKey = nilIfEmpty(video.NotificationDedupeKey(notif.Type, eventID, notif.RecipientID)) notif.DedupeKey = nilIfEmpty(video.NotificationDedupeKey(notif.Type, eventID, notif.RecipientID))
res := w.db.WithContext(ctx). res := w.db.WithContext(ctx).