Files
VLoop/backend/internal/video/idempotency.go
huanghaosheng 5ae04934ae feat(video): 新增评论意图键与通知去重键工具
评论写路径缺失一次用户想发一条评论的稳定标识,因此 MQ 发布返回
error 而消息实际已入队时,兜底直写与消费端写入会被判成两次不同的写,
同一内容入库两条、热度 +2。

引入 intent_key 作为意图的唯一身份:
- NewIntentKey 生成 32 字符随机键(16 字节 hex),不引入 uuid 依赖;
- ResolveIntentKey 把客户端 request_id 归一为意图键,nil/空白生成新键,
  非法输入报错而不静默截断——静默替换会让客户端误以为已去重;
- 非法键的错误包 apierror.ErrValidation,落 400 而不是 500;
- NotificationDedupeKey 给出通知表的去重键形状,空键返回空串以便
  退化不去重而不是把无键通知挤到同一个键上。

字符集排除 ':',因为通知去重键用它做分隔符。
2026-10-30 13:17:41 +08:00

80 lines
2.9 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 (
"crypto/rand"
"encoding/hex"
"fmt"
"strings"
"feedsystem_video_go/internal/apierror"
)
const (
// MaxIntentKeyLen 与 comments.idempotency_key VARCHAR(64) 保持一致。
MaxIntentKeyLen = 64
// minIntentKeyLen 防止客户端传 "1"、"a" 这类极易碰撞的键。
minIntentKeyLen = 8
// intentKeyAlphabet 刻意排除 ':':通知去重键用 ':' 作分隔符
// ("comment:<K>:12"),若 K 含 ':' 则键的边界不可解析。
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 {
return "", fmt.Errorf("generate intent key: %w", err)
}
return hex.EncodeToString(b), nil
}
// ResolveIntentKey 把客户端传来的 request_id 解析成意图键。
//
// nil 或空白 → 生成新键(旧客户端,每次请求都是新意图,行为与今天一致);
// 合法 → 原样返回(客户端重试携带同一个值 → 命中同一次意图);
// 非法 → 返回错误,【不静默截断/不静默替换】。
//
// 静默替换会让"客户端以为去重了、服务端其实没有",比重试产生重复更难排查。
func ResolveIntentKey(raw *string) (string, error) {
if raw == nil || strings.TrimSpace(*raw) == "" {
return NewIntentKey()
}
key := strings.TrimSpace(*raw)
if err := validateIntentKey(key); err != nil {
return "", err
}
return key, nil
}
// validateIntentKey 的错误一律包 apierror.ErrValidation:request_id 写错
// 是客户端的错,必须落 400。裸 error 会走 apierror.ClassifyHTTPStatus 的
// default 分支变成 500,把一次参数错误显示成服务端故障。
func validateIntentKey(key string) error {
if len(key) < minIntentKeyLen || len(key) > MaxIntentKeyLen {
return fmt.Errorf("%w: request_id must be %d-%d characters",
apierror.ErrValidation, minIntentKeyLen, MaxIntentKeyLen)
}
for _, r := range key {
if !strings.ContainsRune(intentKeyAlphabet, r) {
return fmt.Errorf("%w: request_id contains invalid character %q",
apierror.ErrValidation, r)
}
}
return nil
}
// NotificationDedupeKey 构造通知表的去重键。
//
// intentKey 为空时返回空串:空串不写入唯一索引列(该列可空),
// 因此"没有意图键的事件"退化为不去重,而不是全部挤在同一个键上。
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
if intentKey == "" {
return ""
}
return fmt.Sprintf("%s:%s:%d", notifType, intentKey, recipientID)
}