2026-10-30 13:17:41 +08:00
|
|
|
|
package video
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"crypto/rand"
|
|
|
|
|
|
"encoding/hex"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
|
|
"feedsystem_video_go/internal/apierror"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
const (
|
2026-10-31 00:03:53 +08:00
|
|
|
|
// MaxIntentKeyLen 与 comments.idempotency_key 的列宽一致。
|
2026-10-30 13:17:41 +08:00
|
|
|
|
MaxIntentKeyLen = 64
|
|
|
|
|
|
minIntentKeyLen = 8
|
2026-10-31 00:03:53 +08:00
|
|
|
|
// intentKeyAlphabet 不含 ':',它是通知去重键的分隔符。
|
2026-10-30 13:17:41 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 00:03:53 +08:00
|
|
|
|
// validateIntentKey 的错误必须包 apierror.ErrValidation,否则会落 500。
|
2026-10-30 13:17:41 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 00:03:53 +08:00
|
|
|
|
// NotificationDedupeKey 返回空串表示"这条通知不参与去重"。
|
2026-10-30 13:17:41 +08:00
|
|
|
|
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
|
|
|
|
|
|
if intentKey == "" {
|
|
|
|
|
|
return ""
|
|
|
|
|
|
}
|
|
|
|
|
|
return fmt.Sprintf("%s:%s:%d", notifType, intentKey, recipientID)
|
|
|
|
|
|
}
|