sky/internal/platform/idgen/idgen.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

50 lines
1.3 KiB
Go
Raw Permalink 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 idgen
import (
"crypto/rand"
"encoding/hex"
"fmt"
"time"
)
// NewUUIDv7 生成时间有序的 UUIDv7。
// 相比 v4 的随机分布,v7 前缀是毫秒时间戳,写入时索引局部性好得多,
// 避免随机主键在 B-Tree 上造成的页分裂与写放大。
func NewUUIDv7() string {
var b [16]byte
ms := uint64(time.Now().UnixMilli())
b[0] = byte(ms >> 40)
b[1] = byte(ms >> 32)
b[2] = byte(ms >> 24)
b[3] = byte(ms >> 16)
b[4] = byte(ms >> 8)
b[5] = byte(ms)
if _, err := rand.Read(b[6:]); err != nil {
// crypto/rand 失败极罕见,退化为时间戳 + 计数器仍可保证唯一性
n := time.Now().UnixNano()
for i := 0; i < 10; i++ {
b[6+i] = byte(n >> (8 * i))
}
}
b[6] = (b[6] & 0x0f) | 0x70 // version 7
b[8] = (b[8] & 0x3f) | 0x80 // variant RFC 4122
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
// MaskID 生成对外暴露的遮罩 ID,避免把内部 UUID 直接暴露给客户端。
// 前缀便于日志识别与路由分流,如 art_ / usr_ / sec_。
func MaskID(prefix string) string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
n := time.Now().UnixNano()
for i := 0; i < 8; i++ {
b[i] = byte(n >> (8 * i))
}
}
return prefix + "_" + hex.EncodeToString(b[:])
}