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

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

View File

@@ -46,8 +46,6 @@ func (h *CommentHandler) PublishComment(c *gin.Context) {
AuthorID: authorId,
Content: req.Content,
}
// 客户端可以自带 request_id 来表达"这就是我刚才那次提交"。
// 不传则由服务端生成:同一个请求内的所有写入仍然共用一个键(G6)。
if req.RequestID != "" {
requestID := req.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()})
return
}
// 回显 request_id:客户端重试时可以带上同一个值,服务端据此判重。
// 刻意不返回评论 ID——MQ 路径上评论此刻可能还没落库,返回一个还不存在的
// id 只会制造"点进去 404"的错觉。
// 回显 request_id,供客户端重试时复用;不返回评论 ID,因为它可能尚未落库。
resp := gin.H{"message": "comment published successfully"}
if comment.IdempotencyKey != nil {
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
}
// CreateIdempotentWithPopularity 是 P0-4 的核心写入口。
//
// 它把两件必须同生共死的事放进同一个事务:
//
// 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 包与集成测试各有护栏。
// CreateIdempotentWithPopularity 由 uk_comments_author_key 判重。
// 热度增量与插入必须同事务,只在 created=true 时执行。
// 注意:DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) {
var created bool
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
}
if res.RowsAffected == 0 {
// 这条意图已经落过库:不是错误,也不再加热度。
return nil
}
created = true
if delta == 0 {
return nil
}
// 与插入同一个事务:要么"评论与热度"一起生效,要么都不生效。
// GREATEST(...,0) 防止热度被回滚到负数(与点赞侧一致)。
return tx.Model(&Video{}).
Where("id = ?", c.VideoID).
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
}
// DeleteByID 汇报"这次调用是否真的删掉了一行"。
//
// 删除的重复投递与新增的重复投递同样致命:把热度回退当成无条件动作,
// 同一条删除事件投递两次就会把热度减两次(P2-20 的门控点就是这个返回值)。
// DeleteByID 返回是否真的删除了一行,供调用方门控热度回退。
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
if id == 0 {
return false, nil
@@ -119,11 +97,6 @@ func (r *CommentRepository) GetByID(ctx context.Context, id uint) (*Comment, err
return &comment, nil
}
// CreateMentions 幂等写入提及通知:DedupeKey 相同则静默跳过。
//
// 显式写 CreatedAt 而不依赖 autoCreateTime:这一批行共享同一个时间戳,便于
// 按"同一次评论"检索;autoCreateTime 只在字段为零值时才生效,依赖它会让
// 同一批写入拿到毫秒级不同的时间(P2-16 ①)。
func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error {
if len(mentions) == 0 {
return nil
@@ -146,11 +119,7 @@ func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Menti
Create(&rows).Error
}
// FindAccountIDs 一次查询解析一批用户名。
//
// 逐个 SELECT 会让"一条评论里 @ 了 5 个人"变成 5 次往返,而这段代码跑在
// 用户请求路径上(P0-4 §6.5)。不存在的用户名不出现在结果里,调用方按
// map 的不存在分支跳过即可。
// FindAccountIDs 一次查询解析一批用户名;不存在的用户名不出现在结果里。
func (r *CommentRepository) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) {
out := make(map[string]uint, len(usernames))
if len(usernames) == 0 {

View File

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

View File

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

View File

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

View File

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

View File

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