61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
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)
|
||
}
|