feat(video): 新增评论意图键与通知去重键工具
评论写路径缺失一次用户想发一条评论的稳定标识,因此 MQ 发布返回 error 而消息实际已入队时,兜底直写与消费端写入会被判成两次不同的写, 同一内容入库两条、热度 +2。 引入 intent_key 作为意图的唯一身份: - NewIntentKey 生成 32 字符随机键(16 字节 hex),不引入 uuid 依赖; - ResolveIntentKey 把客户端 request_id 归一为意图键,nil/空白生成新键, 非法输入报错而不静默截断——静默替换会让客户端误以为已去重; - 非法键的错误包 apierror.ErrValidation,落 400 而不是 500; - NotificationDedupeKey 给出通知表的去重键形状,空键返回空串以便 退化不去重而不是把无键通知挤到同一个键上。 字符集排除 ':',因为通知去重键用它做分隔符。
This commit is contained in:
79
backend/internal/video/idempotency.go
Normal file
79
backend/internal/video/idempotency.go
Normal file
@@ -0,0 +1,79 @@
|
||||
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)
|
||||
}
|
||||
100
backend/internal/video/idempotency_test.go
Normal file
100
backend/internal/video/idempotency_test.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
)
|
||||
|
||||
// 意图键是"一次用户想发一条评论"的唯一身份,它的格式一旦被放宽,
|
||||
// 判重就会静默失效(不同重试生成不同键 = 每次都是新意图)。因此这里
|
||||
// 逐条钉住边界:长度上下限、允许字符、以及非法输入必须是 400 而不是 500。
|
||||
func TestNewIntentKey_Format(t *testing.T) {
|
||||
t.Helper()
|
||||
seen := make(map[string]struct{}, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
key, err := NewIntentKey()
|
||||
if err != nil {
|
||||
t.Fatalf("NewIntentKey() error = %v", err)
|
||||
}
|
||||
if len(key) != 32 {
|
||||
t.Fatalf("NewIntentKey() len = %d, want 32 (16 字节 hex)", len(key))
|
||||
}
|
||||
if err := validateIntentKey(key); err != nil {
|
||||
t.Fatalf("NewIntentKey() 生成了自己都不接受的键 %q: %v", key, err)
|
||||
}
|
||||
if _, dup := seen[key]; dup {
|
||||
t.Fatalf("NewIntentKey() 连续生成重复键 %q", key)
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveIntentKey_Table(t *testing.T) {
|
||||
ptr := func(s string) *string { return &s }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
raw *string
|
||||
want string // 期望的原样返回;空串表示"应当生成新键"
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "nil 生成新键", raw: nil, want: ""},
|
||||
{name: "空白生成新键", raw: ptr(" "), want: ""},
|
||||
{name: "合法键原样返回", raw: ptr("abcdefgh"), want: "abcdefgh"},
|
||||
{name: "首尾空白被裁掉", raw: ptr(" abcdefgh1234 "), want: "abcdefgh1234"},
|
||||
{name: "恰好 64 字符可接受", raw: ptr(strings.Repeat("a", MaxIntentKeyLen)), want: strings.Repeat("a", MaxIntentKeyLen)},
|
||||
{name: "7 字符过短", raw: ptr("abcdefg"), wantErr: true},
|
||||
{name: "65 字符过长", raw: ptr(strings.Repeat("a", MaxIntentKeyLen+1)), wantErr: true},
|
||||
{name: "含空格非法", raw: ptr("abc defgh"), wantErr: true},
|
||||
{name: "含冒号非法", raw: ptr("abc:defgh"), wantErr: true},
|
||||
{name: "含斜杠非法", raw: ptr("abc/defgh"), wantErr: true},
|
||||
{name: "含中文非法", raw: ptr("意图键意图键"), wantErr: true},
|
||||
{name: "允许连字符与下划线", raw: ptr("abc-def_gh"), want: "abc-def_gh"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Helper()
|
||||
got, err := ResolveIntentKey(tc.raw)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ResolveIntentKey(%v) 期望报错,得到 %q", tc.raw, got)
|
||||
}
|
||||
// 非法 request_id 是客户端的错,必须落 400;500 会让前端把
|
||||
// "参数写错"显示成"服务端故障",也污染错误率指标。
|
||||
if status := apierror.ClassifyHTTPStatus(err); status != 400 {
|
||||
t.Fatalf("ClassifyHTTPStatus(%v) = %d, want 400", err, status)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveIntentKey(%v) error = %v", tc.raw, err)
|
||||
}
|
||||
if tc.want == "" {
|
||||
if len(got) != 32 {
|
||||
t.Fatalf("期望生成 32 字符新键,得到 %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("ResolveIntentKey(%v) = %q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 通知去重键的格式必须稳定:它同时是唯一索引值,写成别的形状会让
|
||||
// "同一条评论的两次投递"算出两个键,去重直接失效。
|
||||
func TestNotificationDedupeKey_Format(t *testing.T) {
|
||||
t.Helper()
|
||||
if got, want := NotificationDedupeKey("mention", "abc12345", 12), "mention:abc12345:12"; got != want {
|
||||
t.Fatalf("NotificationDedupeKey() = %q, want %q", got, want)
|
||||
}
|
||||
// 空意图键返回空串:该列可空,多个 NULL 共存,退化为"不去重",
|
||||
// 而不是把所有无键通知挤到同一个键上只留一条。
|
||||
if got := NotificationDedupeKey("mention", "", 12); got != "" {
|
||||
t.Fatalf("空意图键应返回空串,得到 %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user