Files
VLoop/backend/internal/video/idempotency.go
huanghaosheng c210e75996 style(backend): 清理幂等写入路径的注释
注释只保留一行级约束。
长段理由移入设计文档。
验证:go test -count=1 ./... 全绿。
2026-10-31 00:03:53 +08:00

61 lines
1.6 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 的列宽一致。
MaxIntentKeyLen = 64
minIntentKeyLen = 8
// intentKeyAlphabet 不含 ':',它是通知去重键的分隔符。
intentKeyAlphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
)
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
}
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,否则会落 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 返回空串表示"这条通知不参与去重"。
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
if intentKey == "" {
return ""
}
return fmt.Sprintf("%s:%s:%d", notifType, intentKey, recipientID)
}